File size: 122,644 Bytes
b8370f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
import Foundation
import GRDB
import OpenClawKit
import Testing
@testable import OpenClawChatUI

func makeOutboxStore() throws -> (
    store: OpenClawChatSQLiteTranscriptCache,
    databases: OpenClawClientDatabases,
    directory: URL)
{
    let directory = FileManager.default.temporaryDirectory
        .appendingPathComponent("chat-outbox-tests-\(UUID().uuidString)", isDirectory: true)
    try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
    let databases = try OpenClawClientDatabases(directoryURL: directory)
    return (databases.store(gatewayID: "gw-test"), databases, directory)
}

func outboxTestCommand(
    id: String,
    text: String,
    createdAt: Double,
    sessionKey: String = "main",
    expectedSessionSettings: OpenClawChatSessionSettingsExpectation? = OpenClawChatSessionSettingsExpectation(
        permissionMode: nil,
        toolOverrides: nil)) -> OpenClawChatOutboxCommand
{
    OpenClawChatOutboxCommand(
        id: id,
        sessionKey: sessionKey,
        deliverySessionKey: "agent:main:\(sessionKey)",
        routingContract: "per-sender|main|main",
        agentID: "main",
        text: text,
        thinking: "off",
        expectedSessionSettings: expectedSessionSettings,
        createdAt: createdAt,
        status: .queued,
        retryCount: 0,
        lastError: nil)
}

private func userTexts(_ vm: OpenClawChatViewModel) async -> [String] {
    await MainActor.run {
        vm.messages
            .filter { $0.role == "user" }
            .map { $0.content.compactMap(\.text).joined() }
    }
}

private struct OutboxSendError: Error, LocalizedError {
    var errorDescription: String? {
        "transport unreachable"
    }
}

actor OutboxTransportState {
    enum BranchListingBehavior: Sendable {
        case unsupportedTransport
        case legacyAdminScopeRejection
        case unknownMethodRejection
        case unsupportedTextRejection
    }

    var sessionRoutingContract = "per-sender|main|main"
    var healthy: Bool
    var advertisedMethods: Set<String>?
    var branchListingBehavior: BranchListingBehavior = .unsupportedTransport
    var branchListCalls = 0
    var routeGeneration = 0
    var sendFails: Bool
    var sendFailsAfterRecording = false
    var sendRejects = false
    var sendResponseErrors = false
    var sendRoutingChanged = false
    var sendSettingsChanged = false
    var historyFails = false
    var sessionListFails = false
    var historyRequestCount = 0
    var heldSendGate: DeleteGate?
    var commandListGate: DeleteGate?
    let commandListStarted = DeleteGate()
    var sessionListGate: DeleteGate?
    let sessionListStarted = DeleteGate()
    var staleHistoryRows: [AnyCodable]?

    func update(_ operation: @Sendable (isolated OutboxTransportState) -> Void) {
        operation(self)
    }

    func awaitCommandListGate() async {
        await self.commandListStarted.open()
        if let commandListGate {
            await commandListGate.wait()
        }
    }

    func awaitSessionListGate() async {
        await self.sessionListStarted.open()
        if let sessionListGate {
            await sessionListGate.wait()
        }
    }

    var sentIdempotencyKeys: [String] = []
    var sentMessages: [String] = []
    var sentSessionKeys: [String] = []
    var sentAgentIDs: [String?] = []
    var historyRequestAgentIDs: [String?] = []
    var sentThinkingLevels: [String] = []
    var sentSessionSettings: [OpenClawChatSessionSettingsExpectation?] = []

    init(healthy: Bool, sendFails: Bool) {
        self.healthy = healthy
        self.sendFails = sendFails
    }

    func recordHistoryRequest(agentID: String?) {
        self.historyRequestCount += 1
        self.historyRequestAgentIDs.append(agentID)
    }

    func recordBranchListing() -> BranchListingBehavior {
        self.branchListCalls += 1
        return self.branchListingBehavior
    }

    func recordSend(
        sessionKey: String,
        agentID: String?,
        message: String,
        idempotencyKey: String,
        thinking: String,
        expectedSessionSettings: OpenClawChatSessionSettingsExpectation? = nil)
    {
        self.sentSessionKeys.append(sessionKey)
        self.sentAgentIDs.append(agentID)
        self.sentMessages.append(message)
        self.sentIdempotencyKeys.append(idempotencyKey)
        self.sentThinkingLevels.append(thinking)
        self.sentSessionSettings.append(expectedSessionSettings)
    }
}

/// Scripted transport for offline-outbox flows: health is switchable, sends
/// can be forced to fail, and history synthesizes the durable user rows for
/// every accepted send (what the gateway would persist).
final class OutboxTestTransport: @unchecked Sendable, OpenClawChatTransport {
    let state: OutboxTransportState
    private let sessions: [OpenClawChatSessionEntry]
    private let supportsSlashCommands: Bool
    private let requiresRoutingContract: Bool
    private let routeUnavailableReason: String?
    private let supportsSessionSettingsCAS: Bool
    private let composerCapabilityCatalog: OpenClawChatComposerCapabilityCatalog?
    private let sessionSettingsPatchHook: (@Sendable () async throws -> Void)?
    private let stream: AsyncStream<OpenClawChatTransportEvent>
    private let continuation: AsyncStream<OpenClawChatTransportEvent>.Continuation

    init(
        healthy: Bool,
        sendFails: Bool = false,
        sessions: [OpenClawChatSessionEntry] = [],
        supportsSlashCommands: Bool = false,
        requiresRoutingContract: Bool = true,
        supportsSessionSettingsCAS: Bool = true,
        composerCapabilityCatalog: OpenClawChatComposerCapabilityCatalog? = nil,
        sessionSettingsPatchHook: (@Sendable () async throws -> Void)? = nil,
        routeUnavailableReason: String? = nil)
    {
        self.state = OutboxTransportState(healthy: healthy, sendFails: sendFails)
        self.sessions = sessions
        self.supportsSlashCommands = supportsSlashCommands
        self.requiresRoutingContract = requiresRoutingContract
        self.supportsSessionSettingsCAS = supportsSessionSettingsCAS
        self.composerCapabilityCatalog = composerCapabilityCatalog
        self.sessionSettingsPatchHook = sessionSettingsPatchHook
        self.routeUnavailableReason = routeUnavailableReason
        var cont: AsyncStream<OpenClawChatTransportEvent>.Continuation!
        self.stream = AsyncStream { c in cont = c }
        self.continuation = cont
    }

    func goOnline() async {
        await self.state.update { $0.healthy = true }
        self.continuation.yield(.health(ok: true))
    }

    func emit(_ event: OpenClawChatTransportEvent) {
        self.continuation.yield(event)
    }

    func requestHistory(sessionKey: String) async throws -> OpenClawChatHistoryPayload {
        try await self.requestHistory(sessionKey: sessionKey, agentID: nil, expectedRoute: nil)
    }

    func gatewayAdvertisesMethod(_ method: String) async -> Bool? {
        let advertisedMethods = await state.advertisedMethods
        return advertisedMethods.map { $0.contains(method) }
    }

    var supportsSlashCommandCatalog: Bool {
        self.supportsSlashCommands
    }

    var supportsComposerCapabilities: Bool {
        self.composerCapabilityCatalog != nil
    }

    func loadComposerCapabilityCatalog(
        sessionKey _: String,
        agentID _: String?) async -> OpenClawChatComposerCapabilityCatalog
    {
        self.composerCapabilityCatalog ?? OpenClawChatComposerCapabilityCatalog()
    }

    func patchSessionSettings(
        sessionKey: String,
        agentID _: String?,
        patch: OpenClawChatSessionSettingsPatch) async throws -> OpenClawChatModelPatchResult?
    {
        try await self.sessionSettingsPatchHook?()
        if let model = patch.model {
            try await self.setSessionModel(sessionKey: sessionKey, model: model)
        }
        return nil
    }

    var outboxRequiresSessionRoutingContract: Bool {
        self.requiresRoutingContract
    }

    func listCommands(sessionKey _: String) async throws -> [OpenClawChatCommandChoice] {
        await self.state.awaitCommandListGate()
        return []
    }

    func listSessionBranches(
        sessionKey _: String,
        agentID _: String?) async throws -> OpenClawChatSessionBranchesResponse
    {
        switch await self.state.recordBranchListing() {
        case .unsupportedTransport:
            throw NSError(
                domain: "OpenClawChatTransport",
                code: 0,
                userInfo: [NSLocalizedDescriptionKey: "sessions.branches.list not supported by this transport"])
        case .legacyAdminScopeRejection:
            throw GatewayResponseError(
                method: "sessions.branches.list",
                code: "INVALID_REQUEST",
                message: "missing scope: operator.admin",
                details: nil)
        case .unknownMethodRejection:
            throw GatewayResponseError(
                method: "sessions.branches.list",
                code: "INVALID_REQUEST",
                message: "unknown method: sessions.branches.list",
                details: nil)
        case .unsupportedTextRejection:
            throw GatewayResponseError(
                method: "sessions.branches.list",
                code: "UNSUPPORTED",
                message: "sessions.branches.list is unsupported on this gateway",
                details: nil)
        }
    }

    private func requestHistory(
        sessionKey: String,
        agentID: String?,
        expectedRoute: Int?) async throws -> OpenClawChatHistoryPayload
    {
        await self.state.recordHistoryRequest(agentID: agentID)
        if let expectedRoute, await state.routeGeneration != expectedRoute {
            throw CancellationError()
        }
        guard await self.state.healthy, await !self.state.historyFails else { throw OutboxSendError() }
        if let stale = await state.staleHistoryRows {
            // Gateway lag: the snapshot predates the just-acked send.
            return OpenClawChatHistoryPayload(
                sessionKey: sessionKey,
                sessionId: "sess-live",
                messages: stale,
                thinkingLevel: "off")
        }
        let keys = await state.sentIdempotencyKeys
        let texts = await state.sentMessages
        let sessions = await state.sentSessionKeys
        let agents = await state.sentAgentIDs
        let durableUserRows = keys.indices.compactMap { index -> AnyCodable? in
            guard index < sessions.count,
                  index < agents.count,
                  sessions[index] == sessionKey,
                  agents[index] == agentID
            else { return nil }
            let key = keys[index]
            return AnyCodable([
                "role": "user",
                "content": [["type": "text", "text": index < texts.count ? texts[index] : ""]],
                "timestamp": Double(1000 + index),
                "__openclaw": ["idempotencyKey": "\(key):user"],
            ] as [String: Any])
        }
        return OpenClawChatHistoryPayload(
            sessionKey: sessionKey,
            sessionId: "sess-live",
            messages: durableUserRows,
            thinkingLevel: "off")
    }

    func sendMessage(
        sessionKey: String,
        message: String,
        thinking: String,
        idempotencyKey: String,
        attachments _: [OpenClawChatAttachmentPayload]) async throws -> OpenClawChatSendResponse
    {
        try await self.sendMessage(
            sessionKey: sessionKey,
            agentID: nil,
            message: message,
            thinking: thinking,
            idempotencyKey: idempotencyKey,
            expectedSessionSettings: nil,
            expectedRoute: nil)
    }

    private func sendMessage(
        sessionKey: String,
        agentID: String?,
        message: String,
        thinking: String,
        idempotencyKey: String,
        expectedSessionSettings: OpenClawChatSessionSettingsExpectation?,
        expectedRoute: Int?) async throws -> OpenClawChatSendResponse
    {
        if let expectedRoute, await state.routeGeneration != expectedRoute {
            throw OpenClawChatTransportSendError.notDispatched
        }
        if let gate = await state.heldSendGate {
            // One-shot: only the first send is held so tests can pin the
            // window where the flush is mid-drain.
            await self.state.update { $0.heldSendGate = nil }
            await gate.wait()
        }
        if let expectedRoute, await state.routeGeneration != expectedRoute {
            throw OpenClawChatTransportSendError.notDispatched
        }
        if await self.state.sendFails {
            throw OutboxSendError()
        }
        if await self.state.sendResponseErrors {
            throw GatewayResponseError(
                method: "chat.send",
                code: "INVALID_REQUEST",
                message: "rejected",
                details: nil)
        }
        if await self.state.sendRoutingChanged {
            throw GatewayResponseError(
                method: "chat.send",
                code: "INVALID_REQUEST",
                message: "session routing changed; review and retry",
                details: [
                    "reason": AnyCodable(OpenClawChatSessionRoutingContract.changedErrorReason),
                ])
        }
        if await self.state.sendSettingsChanged {
            throw GatewayResponseError(
                method: "chat.send",
                code: "INVALID_REQUEST",
                message: "session settings changed; review and retry",
                details: ["reason": AnyCodable(OpenClawChatSessionSettingsContract.changedErrorReason)])
        }
        if await self.state.sendRejects {
            // Gateway responded but refused to start the run.
            return OpenClawChatSendResponse(runId: idempotencyKey, status: "error")
        }
        await self.state.recordSend(
            sessionKey: sessionKey,
            agentID: agentID,
            message: message,
            idempotencyKey: idempotencyKey,
            thinking: thinking,
            expectedSessionSettings: expectedSessionSettings)
        if await self.state.sendFailsAfterRecording {
            throw OutboxSendError()
        }
        return OpenClawChatSendResponse(runId: idempotencyKey, status: "accepted")
    }

    func acquireOutboxRouteLease() async -> OpenClawChatTransportRouteLeaseResult {
        if let routeUnavailableReason {
            return .unavailable(reason: routeUnavailableReason)
        }
        if !self.requiresRoutingContract {
            let transport = self
            return .available(OpenClawChatTransportRouteLease(
                sendMessage: { sessionKey, message, thinking, idempotencyKey, attachments in
                    try await transport.sendMessage(
                        sessionKey: sessionKey,
                        message: message,
                        thinking: thinking,
                        idempotencyKey: idempotencyKey,
                        attachments: attachments)
                },
                requestHistory: { sessionKey in
                    try await transport.requestHistory(sessionKey: sessionKey)
                }))
        }
        let expectedRoute = await state.routeGeneration
        let routingContract = await state.sessionRoutingContract
        let transport = self
        return .available(OpenClawChatTransportRouteLease(
            sendTargetedMessageWithSettings: {
                sessionKey, agentID, expectedSettings, message, thinking, idempotencyKey, _ in
                try await transport.sendMessage(
                    sessionKey: sessionKey,
                    agentID: agentID,
                    message: message,
                    thinking: thinking,
                    idempotencyKey: idempotencyKey,
                    expectedSessionSettings: expectedSettings,
                    expectedRoute: expectedRoute)
            },
            requestTargetedHistory: { sessionKey, agentID in
                try await transport.requestHistory(
                    sessionKey: sessionKey,
                    agentID: agentID,
                    expectedRoute: expectedRoute)
            },
            sessionRoutingContract: routingContract,
            supportsSessionSettingsCAS: self.supportsSessionSettingsCAS))
    }

    /// Gated model patch: `setSessionModel` blocks until `releaseModelPatch`
    /// so tests can hold a patch in flight while the outbox flushes.
    private let modelPatchGate = AsyncStream<Void>.makeStream()
    private let modelPatchStarted = DeleteGate()

    func releaseModelPatch() {
        self.modelPatchGate.continuation.yield(())
    }

    func modelPatchHasStarted() async -> Bool {
        await self.modelPatchStarted.opened()
    }

    func setSessionModel(sessionKey _: String, model _: String?) async throws {
        await self.modelPatchStarted.open()
        var iterator = self.modelPatchGate.stream.makeAsyncIterator()
        _ = await iterator.next()
    }

    func listSessions(
        limit _: Int?,
        search _: String?,
        archived _: Bool) async throws -> OpenClawChatSessionsListResponse
    {
        await self.state.awaitSessionListGate()
        guard await !self.state.sessionListFails else { throw OutboxSendError() }
        return OpenClawChatSessionsListResponse(
            ts: nil,
            path: nil,
            count: self.sessions.count,
            defaults: nil,
            sessions: self.sessions)
    }

    func requestHealth(timeoutMs _: Int) async throws -> Bool {
        await self.state.healthy
    }

    func events() -> AsyncStream<OpenClawChatTransportEvent> {
        self.stream
    }
}

func outboxSessionEntry(
    key: String,
    thinkingLevels: [String],
    sessionID: String? = nil,
    permissionMode: OpenClawChatPermissionMode? = nil) -> OpenClawChatSessionEntry
{
    OpenClawChatSessionEntry(
        key: key,
        kind: nil,
        displayName: nil,
        surface: nil,
        subject: nil,
        room: nil,
        space: nil,
        updatedAt: nil,
        sessionId: sessionID,
        systemSent: nil,
        abortedLastRun: nil,
        thinkingLevel: nil,
        verboseLevel: nil,
        inputTokens: nil,
        outputTokens: nil,
        totalTokens: nil,
        modelProvider: nil,
        model: nil,
        contextTokens: nil,
        thinkingLevels: thinkingLevels.map { OpenClawChatThinkingLevelOption(id: $0, label: $0) },
        permissionMode: permissionMode)
}

func makeOutboxViewModel(
    transport: OutboxTestTransport,
    outbox: any OpenClawChatCommandOutbox,
    transcriptCache: (any OpenClawChatTranscriptCache)? = nil,
    retryDelaysMs: [UInt64] = [1, 1],
    sessionKey: String = "main",
    activeAgentID: String? = "main",
    sessionRoutingContract: String? = "per-sender|main|main") async -> OpenClawChatViewModel
{
    await MainActor.run {
        let vm = OpenClawChatViewModel(
            sessionKey: sessionKey,
            transport: transport,
            activeAgentId: activeAgentID,
            sessionRoutingContract: sessionRoutingContract,
            transcriptCache: transcriptCache,
            outbox: outbox,
            modelPickerStore: ChatModelPickerStore(
                defaults: UserDefaults(
                    suiteName: "ChatViewModelOutboxTests.\(UUID().uuidString)") ?? .standard))
        vm.outboxRetryDelaysMs = retryDelaysMs
        return vm
    }
}

private func sendWhileOffline(_ vm: OpenClawChatViewModel, text: String) async throws {
    await MainActor.run {
        vm.input = text
        vm.send()
    }
    try await waitUntil("queued bubble for \(text)") {
        await MainActor.run {
            vm.messages.contains { message in
                message.role == "user" && message.content.contains { $0.text == text }
            }
        }
    }
}

/// Protocol delegation plus switches makes race windows deterministic without copying the store contract.
actor ScriptedOutbox: OpenClawChatCommandOutbox {
    enum Forwarding { case full, minimal, holdingCancellation }

    private nonisolated let base: OpenClawChatSQLiteTranscriptCache
    private let forwarding: Forwarding
    private var loadDelayNanoseconds: UInt64 = 0
    private var enqueueRelease: DeleteGate?
    private var recoveryAvailable = true
    private var terminalWriteResult: OpenClawChatOutboxUpdateResult = .updated
    private var parkingAvailable = true
    private var captured = DeleteGate()
    private var snapshotRelease = DeleteGate()
    private var shouldHoldNextLoad = false
    private var shouldHoldLoadAfterFailure = false
    private let enqueueStarted = DeleteGate()
    private let recoveryAttempted = DeleteGate()
    private let canceled = DeleteGate()
    private let cancellationRelease = DeleteGate()

    init(base: OpenClawChatSQLiteTranscriptCache, forwarding: Forwarding = .full) {
        self.base = base
        self.forwarding = forwarding
    }

    nonisolated func changes() -> AsyncStream<OpenClawChatOutboxChange> {
        self.base.changes()
    }

    func setLoadDelayNanoseconds(_ delay: UInt64) {
        self.loadDelayNanoseconds = delay
    }

    func setRecoveryAvailable(_ available: Bool) {
        self.recoveryAvailable = available
    }

    func setTerminalWritesAvailable(_ available: Bool) {
        self.terminalWriteResult = available ? .updated : .unavailable
    }

    func setTerminalWriteResult(_ result: OpenClawChatOutboxUpdateResult) {
        self.terminalWriteResult = result
    }

    func setParkingAvailable(_ available: Bool) {
        self.parkingAvailable = available
    }

    func waitUntilRecoveryAttempted() async {
        await self.recoveryAttempted.wait()
    }

    func holdEnqueue() {
        self.enqueueRelease = DeleteGate()
    }

    func waitUntilEnqueueStarted() async {
        await self.enqueueStarted.wait()
    }

    func releaseEnqueue() async {
        await self.enqueueRelease?.open()
        self.enqueueRelease = nil
    }

    func holdLoadAfterFailure() {
        self.captured = DeleteGate()
        self.snapshotRelease = DeleteGate()
        self.shouldHoldLoadAfterFailure = true
    }

    func holdNextLoad() {
        self.captured = DeleteGate()
        self.snapshotRelease = DeleteGate()
        self.shouldHoldNextLoad = true
    }

    func waitUntilSnapshotCaptured() async {
        await self.captured.wait()
    }

    func releaseSnapshot() async {
        await self.snapshotRelease.open()
    }

    func waitUntilCanceled() async {
        await self.canceled.wait()
    }

    func releaseCancellation() async {
        await self.cancellationRelease.open()
    }

    func enqueueCommand(_ command: OpenClawChatOutboxCommand) async -> Bool {
        if let enqueueRelease {
            await self.enqueueStarted.open()
            await enqueueRelease.wait()
        }
        return await self.base.enqueueCommand(command)
    }

    func loadCommands() async -> [OpenClawChatOutboxCommand] {
        await self.delayLoad()
        let commands = await base.loadCommands()
        await self.finishHeldLoad()
        return commands
    }

    func loadCommandsIfAvailable() async -> [OpenClawChatOutboxCommand]? {
        await self.delayLoad()
        guard let commands = await base.loadCommandsIfAvailable() else { return nil }
        await self.finishHeldLoad()
        return commands
    }

    private func delayLoad() async {
        guard self.loadDelayNanoseconds > 0 else { return }
        try? await Task.sleep(nanoseconds: self.loadDelayNanoseconds)
    }

    private func finishHeldLoad() async {
        if self.shouldHoldNextLoad {
            self.shouldHoldNextLoad = false
            await self.captured.open()
            await self.snapshotRelease.wait()
        }
    }

    @discardableResult
    func recoverInterruptedSends() async -> Bool {
        await self.recoveryAttempted.open()
        guard self.recoveryAvailable else { return false }
        return await self.base.recoverInterruptedSends()
    }

    func claimNextCommand() async -> OpenClawChatOutboxCommand? {
        await self.base.claimNextCommand()
    }

    func markCommandQueued(
        id: String,
        attemptVersion: Int,
        retryCount: Int,
        lastError: String?) async -> OpenClawChatOutboxUpdateResult
    {
        await self.base.markCommandQueued(
            id: id,
            attemptVersion: attemptVersion,
            retryCount: retryCount,
            lastError: lastError)
    }

    func markCommandAwaitingConfirmation(id: String, attemptVersion: Int) async -> OpenClawChatOutboxUpdateResult {
        await self.base.markCommandAwaitingConfirmation(id: id, attemptVersion: attemptVersion)
    }

    func markCommandFailedIfPresent(
        id: String, attemptVersion: Int,
        retryCount: Int,
        lastError: String?) async -> OpenClawChatOutboxUpdateResult
    {
        switch self.terminalWriteResult {
        case .unavailable:
            return .unavailable
        case .confirmed, .missing:
            _ = await self.base.confirmCommand(id: id, attemptVersion: attemptVersion)
            return self.terminalWriteResult
        case .superseded:
            _ = await self.base.markCommandQueued(
                id: id, attemptVersion: attemptVersion, retryCount: retryCount, lastError: nil)
            _ = await self.base.claimNextCommand()
            return .superseded
        case .updated:
            break
        }
        let result = await self.base.markCommandFailedIfPresent(
            id: id,
            attemptVersion: attemptVersion,
            retryCount: retryCount,
            lastError: lastError)
        if result == .updated, self.shouldHoldLoadAfterFailure {
            self.shouldHoldLoadAfterFailure = false
            self.shouldHoldNextLoad = true
        }
        return result
    }

    func parkQueuedCommands(
        in scope: OpenClawChatOutboxScope,
        lastError: String) async -> Bool
    {
        guard self.parkingAvailable else { return false }
        return await self.base.parkQueuedCommands(in: scope, lastError: lastError)
    }

    func markCommandRetriedIfPresent(
        id: String,
        expectation: OpenClawChatOutboxRetryExpectation,
        agentID: String?,
        deliverySessionKey: String,
        routingContract: String,
        expectedSessionSettings: OpenClawChatSessionSettingsExpectation,
        replacementID: String?) async -> OpenClawChatOutboxUpdateResult
    {
        await self.base.markCommandRetriedIfPresent(
            id: id,
            expectation: expectation,
            agentID: agentID,
            deliverySessionKey: deliverySessionKey,
            routingContract: routingContract,
            expectedSessionSettings: expectedSessionSettings,
            replacementID: replacementID)
    }

    func cancelCommand(id: String) async -> OpenClawChatOutboxUpdateResult {
        let result = await base.cancelCommand(id: id)
        if self.forwarding == .holdingCancellation {
            await self.canceled.open()
            await self.cancellationRelease.wait()
        }
        return result
    }

    func confirmCommand(id: String, attemptVersion: Int) async -> OpenClawChatOutboxUpdateResult {
        await self.base.confirmCommand(id: id, attemptVersion: attemptVersion)
    }

    func branchState(for scope: OpenClawChatOutboxScope) async -> OpenClawChatOutboxBranchState? {
        guard self.forwarding == .full else { return nil }
        return await self.base.branchState(for: scope)
    }

    func beginBranchSwitch(_ scope: OpenClawChatOutboxScope) async -> Bool {
        guard self.forwarding == .full else { return false }
        return await self.base.beginBranchSwitch(scope)
    }

    func cancelBranchSwitch(_ scope: OpenClawChatOutboxScope) async -> Bool {
        guard self.forwarding == .full else { return false }
        return await self.base.cancelBranchSwitch(scope)
    }

    func reconcileBranchScope(
        _ scope: OpenClawChatOutboxScope,
        previousState: OpenClawChatOutboxBranchState,
        activeLeafEntryID: String?,
        branchLeafEntryIDs: Set<String>,
        activeTranscriptEntryIDs: Set<String>,
        lastError: String) async -> [OpenClawChatOutboxCommand]?
    {
        guard self.forwarding == .full else { return nil }
        return await self.base.reconcileBranchScope(
            scope, previousState: previousState, activeLeafEntryID: activeLeafEntryID,
            branchLeafEntryIDs: branchLeafEntryIDs,
            activeTranscriptEntryIDs: activeTranscriptEntryIDs,
            lastError: lastError)
    }

    func confirmBranchChange(
        _ scope: OpenClawChatOutboxScope,
        activeLeafEntryID: String,
        lastError: String) async -> [OpenClawChatOutboxCommand]?
    {
        guard self.forwarding == .full else { return nil }
        return await self.base.confirmBranchChange(
            scope,
            activeLeafEntryID: activeLeafEntryID,
            lastError: lastError)
    }

    func updateLastActiveLeafEntryID(
        _ leafEntryID: String,
        expectedEpoch: Int,
        for scope: OpenClawChatOutboxScope) async -> Bool
    {
        guard self.forwarding == .full else { return false }
        return await self.base.updateLastActiveLeafEntryID(
            leafEntryID,
            expectedEpoch: expectedEpoch,
            for: scope)
    }
}

struct ChatViewModelOutboxTests {
    @Test func `offline send queues durably and renders queued row`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)
        #expect(await MainActor.run { vm.supportsOfflineTextOutbox })

        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: "hello offline")

        // Nothing hit the transport; the command is durable instead.
        #expect(await transport.state.sentIdempotencyKeys.isEmpty)
        let commands = await store.loadCommands()
        #expect(commands.map(\.text) == ["hello offline"])
        #expect(commands.map(\.status) == [.queued])
        #expect(commands.map(\.sessionKey) == ["main"])
        #expect(commands.map(\.deliverySessionKey) == ["agent:main:main"])
        #expect(commands.map(\.expectedSessionSettings) == [
            OpenClawChatSessionSettingsExpectation(permissionMode: nil, toolOverrides: nil),
        ])

        // The visible row carries the queued state and the draft was cleared.
        #expect(await MainActor.run { vm.input.isEmpty })
        let queuedStates = await MainActor.run {
            vm.messages.compactMap { vm.outboxState(for: $0.id) }
        }
        #expect(queuedStates == [.queued])

        // Recreating the view model (fresh cold open, still offline)
        // restores the queued bubble from the durable store.
        let vm2 = await makeOutboxViewModel(transport: transport, outbox: store)
        await MainActor.run { vm2.load() }
        try await waitUntil("queued bubble restored after recreation") {
            await MainActor.run {
                vm2.messages.contains { vm2.outboxState(for: $0.id) == .queued }
            }
        }
        #expect(await userTexts(vm2) == ["hello offline"])

        // A cold launch can restore before the gateway provides its default
        // agent. The captured owner still keeps the bubble visible; replay
        // remains blocked on the route lease's owner/contract verification.
        let ownerlessColdOpen = await makeOutboxViewModel(
            transport: transport,
            outbox: store,
            activeAgentID: nil,
            sessionRoutingContract: nil)
        await MainActor.run { ownerlessColdOpen.load() }
        try await waitUntil("ownerless cold open restores queued bubble") {
            await MainActor.run {
                ownerlessColdOpen.messages.contains {
                    ownerlessColdOpen.outboxState(for: $0.id) == .queued
                }
            }
        }
        #expect(await userTexts(ownerlessColdOpen) == ["hello offline"])
    }

    @Test func `unsupported gateway keeps queued work and surfaces upgrade action`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let message = OpenClawChatTransportUpgradeMessage.routingContract
        let transport = OutboxTestTransport(
            healthy: false,
            routeUnavailableReason: message)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: "wait for upgrade")
        await transport.goOnline()

        try await waitUntil("gateway upgrade guidance") {
            await MainActor.run { vm.errorText == message }
        }
        #expect(await store.loadCommands().map(\.status) == [.queued])
        #expect(await transport.state.sentMessages.isEmpty)
    }

    @Test func `released 2026.7.x gateway without branch listing dispatches queued send without polling branches`()
        async throws
    {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        await transport.state.update {
            $0.advertisedMethods = ["chat.send", "chat.history", "sessions.list"]
            $0.branchListingBehavior = .legacyAdminScopeRejection
        }
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)
        let text = "legacy gateway must flush"

        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: text)
        await transport.goOnline()

        try await waitUntil("legacy gateway dispatches queued send") {
            await transport.state.sentMessages == [text]
        }
        #expect(await transport.state.branchListCalls == 0)
    }

    @Test func `modern gateway unknown-method rejection still releases queued send`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        await transport.state.update {
            $0.advertisedMethods = nil
            $0.branchListingBehavior = .unknownMethodRejection
        }
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)
        let text = "unknown method still flushes"

        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: text)
        await transport.goOnline()

        try await waitUntil("modern gateway dispatches queued send") {
            await transport.state.sentMessages == [text]
        }
        #expect(await transport.state.branchListCalls >= 1)
    }

    @Test @MainActor func `branch listing unsupported matcher rejects scope denials and accepts definitive absence`() {
        #expect(!OpenClawChatViewModel.branchListingIsUnsupported(GatewayResponseError(
            method: "sessions.branches.list",
            code: "INVALID_REQUEST",
            message: "missing scope: operator.admin",
            details: nil)))
        #expect(OpenClawChatViewModel.branchListingIsUnsupported(GatewayResponseError(
            method: "sessions.branches.list",
            code: "INVALID_REQUEST",
            message: "unknown method: sessions.branches.list",
            details: nil)))
        #expect(OpenClawChatViewModel.branchListingIsUnsupported(GatewayResponseError(
            method: "sessions.branches.list",
            code: "UNSUPPORTED",
            message: "sessions.branches.list is unsupported on this gateway",
            details: nil)))
        #expect(OpenClawChatViewModel.branchListingIsUnsupported(
            OpenClawChatViewModel.BranchListingUnadvertisedError()))
    }

    @Test func `explicit unsupported reply on a pre-catalog gateway still releases queued send`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        await transport.state.update {
            $0.advertisedMethods = nil
            $0.branchListingBehavior = .unsupportedTextRejection
        }
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)
        let text = "explicit unsupported still flushes"

        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: text)
        await transport.goOnline()

        try await waitUntil("pre-catalog gateway dispatches queued send") {
            await transport.state.sentMessages == [text]
        }
        #expect(await transport.state.branchListCalls >= 1)
    }

    @Test func `offline queue persists the effective thinking level`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let sessions = [outboxSessionEntry(key: "main", thinkingLevels: ["off"])]
        let transport = OutboxTestTransport(healthy: false, sessions: sessions)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { vm.load() }
        await MainActor.run {
            vm.sessions = sessions
            vm.preferredThinkingLevel = "ultra"
            vm.syncThinkingLevelOptions()
        }
        #expect(await MainActor.run { !vm.showsThinkingPicker })

        try await sendWhileOffline(vm, text: "persist the send-safe level")
        #expect(await store.loadCommands().map(\.thinking) == ["off"])
    }

    @Test func `inert outbox does not capability gate healthy live chat`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(
            healthy: true,
            routeUnavailableReason: OpenClawChatTransportUpgradeMessage.routingContract)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { vm.load() }
        try await waitUntil("empty outbox becomes ready") {
            await MainActor.run {
                vm.healthOK && !vm.isLoading && vm.hasRestoredOutboxMessages
            }
        }
        #expect(await MainActor.run { vm.healthOK })
        #expect(await MainActor.run { vm.errorText == nil })

        var parked = outboxTestCommand(id: "c-parked", text: "review me", createdAt: 1)
        parked.status = .failed
        parked.lastError = OpenClawChatSQLiteTranscriptCache.outboxChangedTargetError
        #expect(await store.enqueueCommand(parked))
        let parkedVM = await makeOutboxViewModel(transport: transport, outbox: store)
        await MainActor.run { parkedVM.load() }
        try await waitUntil("parked outbox becomes ready") {
            await MainActor.run {
                parkedVM.healthOK && !parkedVM.isLoading && parkedVM.hasRestoredOutboxMessages
            }
        }
        #expect(await MainActor.run { parkedVM.healthOK })
        #expect(await MainActor.run { parkedVM.errorText == nil })
    }

    @Test func `legacy transport preserves its untargeted session key`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false, requiresRoutingContract: false)
        let vm = await makeOutboxViewModel(
            transport: transport,
            outbox: store,
            sessionKey: "OpaquePeer",
            activeAgentID: nil,
            sessionRoutingContract: nil)

        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: "legacy route")
        let command = try #require(await store.claimNextCommand())
        #expect(command.deliverySessionKey == "OpaquePeer")
        #expect(command.agentID == nil)
        #expect(await store.markCommandFailedIfPresent(
            id: command.id,
            attemptVersion: command.attemptVersion,
            retryCount: 1,
            lastError: "legacy failure") == .updated)

        let retryView = await makeOutboxViewModel(
            transport: transport,
            outbox: store,
            sessionKey: "OpaquePeer",
            activeAgentID: nil,
            sessionRoutingContract: nil)
        await MainActor.run { retryView.load() }
        try await waitUntil("legacy failed bubble") {
            await MainActor.run {
                retryView.messages.contains { message in
                    retryView.outboxState(for: message.id)?.isFailed == true
                }
            }
        }
        let failedMessageID = try #require(await MainActor.run { retryView.messages.last?.id })
        await MainActor.run { retryView.retryOutboxMessage(failedMessageID) }
        try await waitUntil("legacy retry queues") {
            await store.loadCommands().first?.status == .queued
        }

        await transport.goOnline()
        try await waitUntil("legacy outbox send") {
            await transport.state.sentMessages == ["legacy route"]
        }
        #expect(await transport.state.sentSessionKeys == ["OpaquePeer"])
        #expect(await transport.state.sentAgentIDs == [nil])
    }

    @Test func `reserved unknown session stays unscoped in durable delivery`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(
            transport: transport,
            outbox: store,
            sessionKey: "unknown")

        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: "reserved route")
        let command = try #require(await store.loadCommands().first)

        #expect(command.deliverySessionKey == "unknown")
        #expect(command.agentID == nil)

        await transport.goOnline()
        try await waitUntil("reserved outbox send") {
            await transport.state.sentMessages == ["reserved route"]
        }
        #expect(await transport.state.sentSessionKeys == ["unknown"])
        #expect(await transport.state.sentAgentIDs == [nil])
    }

    @Test(arguments: ["global", "main"])
    func `mutable alias queued turn keeps its original agent target`(_ sessionKey: String) async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let offlineTransport = OutboxTestTransport(healthy: false)
        let agentAView = await makeOutboxViewModel(
            transport: offlineTransport,
            outbox: store,
            transcriptCache: store,
            sessionKey: sessionKey,
            activeAgentID: "agent-a")
        await MainActor.run { agentAView.load() }
        try await sendWhileOffline(agentAView, text: "for agent A")
        #expect(await store.loadCommands().map(\.agentID) == ["agent-a"])

        let reconnectTransport = OutboxTestTransport(healthy: false)
        let agentBView = await makeOutboxViewModel(
            transport: reconnectTransport,
            outbox: store,
            transcriptCache: store,
            sessionKey: sessionKey,
            activeAgentID: "agent-b")
        await MainActor.run { agentBView.load() }
        try await waitUntil("agent B restore completes without adopting agent A bubble") {
            await MainActor.run { agentBView.hasRestoredOutboxMessages }
        }
        #expect(await userTexts(agentBView).isEmpty)

        await reconnectTransport.goOnline()
        try await waitUntil("agent A command drains after agent B reconnects") {
            await store.loadCommands().isEmpty
        }
        let deliverySessionKey = sessionKey == "global" ? "global" : "agent:agent-a:main"
        #expect(await reconnectTransport.state.sentSessionKeys == [deliverySessionKey])
        #expect(await reconnectTransport.state.sentAgentIDs == ["agent-a"])
        #expect(await reconnectTransport.state.historyRequestAgentIDs.contains("agent-a"))
        #expect(await store.loadTranscript(sessionKey: sessionKey, agentID: "agent-a")
            .map { $0.content.compactMap(\.text).joined() } == ["for agent A"])
        #expect(await store.loadTranscript(sessionKey: sessionKey, agentID: "agent-b").isEmpty)
    }

    @Test func `reconnect waits for canonical session metadata before flushing Ultra`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        #expect(await store.updateLastActiveLeafEntryID(
            "leaf-new",
            expectedEpoch: 0,
            for: OpenClawChatOutboxScope(sessionKey: "main", agentID: "main")))
        #expect(await store.updateLastActiveLeafEntryID(
            "leaf-new",
            expectedEpoch: 0,
            for: OpenClawChatOutboxScope(sessionKey: "main", agentID: nil)))
        #expect(await store.enqueueCommand(OpenClawChatOutboxCommand(
            id: "alpha-ultra",
            sessionKey: "main",
            deliverySessionKey: "agent:alpha:main",
            routingContract: "per-sender|main|main",
            agentID: "alpha",
            text: "use canonical Luna metadata",
            thinking: "ultra",
            expectedSessionSettings: OpenClawChatSessionSettingsExpectation(permissionMode: nil, toolOverrides: nil),
            createdAt: Date().timeIntervalSince1970,
            status: .queued,
            retryCount: 0,
            lastError: nil)))
        let listGate = DeleteGate()
        let sessions = [
            outboxSessionEntry(key: "agent:alpha:main", thinkingLevels: ["off", "max"]),
            outboxSessionEntry(key: "agent:beta:main", thinkingLevels: ["off", "ultra"]),
        ]
        let transport = OutboxTestTransport(healthy: false, sessions: sessions)
        await transport.state.update { $0.sessionListGate = listGate }
        let vm = await makeOutboxViewModel(
            transport: transport,
            outbox: store,
            sessionKey: "main",
            activeAgentID: "beta")

        await MainActor.run { vm.load() }
        await transport.goOnline()
        await transport.state.sessionListStarted.wait()
        try await Task.sleep(for: .milliseconds(50))
        #expect(await transport.state.sentMessages.isEmpty)
        #expect(await store.loadCommands().map(\.status) == [.queued])

        await listGate.open()
        try await waitUntil("canonical Alpha command flushes after list metadata") {
            await store.loadCommands().isEmpty
        }
        #expect(await transport.state.sentSessionKeys == ["agent:alpha:main"])
        #expect(await transport.state.sentAgentIDs == ["alpha"])
        #expect(await transport.state.sentThinkingLevels == ["max"])
    }

    @Test func `reconnect retries metadata after a transient session list failure`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        #expect(await store.enqueueCommand(outboxTestCommand(
            id: "retry-metadata",
            text: "send after retry",
            createdAt: Date().timeIntervalSince1970)))
        let transport = OutboxTestTransport(healthy: false)
        await transport.state.update { $0.sessionListFails = true }
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { vm.load() }
        await transport.goOnline()
        await transport.state.sessionListStarted.wait()
        try await waitUntil("failed metadata fetch returns to unhealthy") {
            await MainActor.run { !vm.healthOK }
        }
        #expect(await store.loadCommands().map(\.status) == [.queued])

        await transport.state.update { $0.sessionListFails = false }
        await transport.goOnline()
        try await waitUntil("next healthy transition retries metadata and drains") {
            await store.loadCommands().isEmpty
        }
        #expect(await transport.state.sentMessages == ["send after retry"])
    }

    @Test func `unscoped opaque peer ID preserves case in its durable target`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let sessionKey = "Matrix:Channel:!MixedRoomAbCdEf:example.org"
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(
            transport: transport,
            outbox: store,
            sessionKey: sessionKey,
            activeAgentID: "agent-a")
        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: "preserve opaque room")

        let command = try #require(await store.loadCommands().first)
        #expect(command.deliverySessionKey == "agent:agent-a:\(sessionKey)")

        await transport.goOnline()
        try await waitUntil("mixed-case target drains") {
            await store.loadCommands().isEmpty
        }
        #expect(await transport.state.sentSessionKeys == ["agent:agent-a:\(sessionKey)"])
    }

    @Test func `changed default agent parks command visibly for retry`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let oldTransport = OutboxTestTransport(healthy: false)
        await oldTransport.state.update { $0.sessionRoutingContract = "per-sender|main|agent-a" }
        let oldView = await makeOutboxViewModel(
            transport: oldTransport,
            outbox: store,
            activeAgentID: "agent-a",
            sessionRoutingContract: "per-sender|main|agent-a")
        await MainActor.run { oldView.load() }
        try await sendWhileOffline(oldView, text: "old main target")

        let newTransport = OutboxTestTransport(healthy: false)
        await newTransport.state.update { $0.sessionRoutingContract = "per-sender|main|agent-b" }
        let newView = await makeOutboxViewModel(
            transport: newTransport,
            outbox: store,
            activeAgentID: "agent-b",
            sessionRoutingContract: "per-sender|main|agent-b")
        await MainActor.run { newView.load() }

        await newTransport.goOnline()
        try await waitUntil("changed target is parked") {
            await store.loadCommands().map(\.status) == [.failed]
        }
        #expect(await store.loadCommands().first?.lastError ==
            OpenClawChatSQLiteTranscriptCache.outboxChangedTargetError)
        #expect(await newTransport.state.sentMessages.isEmpty)
        try await waitUntil("parked target stays visible") {
            await MainActor.run {
                newView.messages.contains { newView.outboxState(for: $0.id)?.isFailed == true }
            }
        }

        let messageID = try #require(await MainActor.run {
            newView.messages.first { newView.outboxState(for: $0.id)?.isFailed == true }?.id
        })
        await MainActor.run { newView.retryOutboxMessage(messageID) }
        try await waitUntil("changed target retry drains") {
            await store.loadCommands().isEmpty
        }
        #expect(await newTransport.state.sentAgentIDs == ["agent-b"])
        #expect(await newTransport.state.sentSessionKeys == ["agent:agent-b:main"])
    }

    @Test func `atomic gateway routing rejection parks without retrying`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)
        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: "do not cross config reload")

        await transport.state.update { $0.sendRoutingChanged = true }
        await transport.goOnline()
        try await waitUntil("atomic routing rejection parks") {
            await store.loadCommands().first?.status == .failed
        }
        let command = try #require(await store.loadCommands().first)
        #expect(command.lastError == OpenClawChatSQLiteTranscriptCache.outboxChangedTargetError)
        #expect(command.retryCount == 0)
        #expect(await transport.state.sentMessages.isEmpty)
    }

    @Test func `failed alias row remains reachable after owner change`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        #expect(await store.enqueueCommand(OpenClawChatOutboxCommand(
            id: "c-old-failure",
            sessionKey: "main",
            deliverySessionKey: "agent:agent-a:main",
            routingContract: "per-sender|main|agent-a",
            agentID: "agent-a",
            text: "review old failure",
            thinking: "off",
            expectedSessionSettings: OpenClawChatSessionSettingsExpectation(permissionMode: nil, toolOverrides: nil),
            createdAt: Date().timeIntervalSince1970,
            status: .failed,
            retryCount: 1,
            lastError: OpenClawChatSQLiteTranscriptCache.outboxExpiredError)))
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(
            transport: transport,
            outbox: store,
            activeAgentID: "agent-b",
            sessionRoutingContract: "per-sender|main|agent-b")

        await MainActor.run { vm.load() }
        try await waitUntil("old failed row stays visible") {
            await MainActor.run {
                vm.messages.contains { vm.outboxState(for: $0.id)?.isFailed == true }
            }
        }
        let messageID = try #require(await MainActor.run { vm.messages.last?.id })
        await MainActor.run { vm.deleteOutboxMessage(messageID) }
        try await waitUntil("old failed row can be deleted") { await store.loadCommands().isEmpty }
    }

    @Test func `ownerless global retry stays failed without a selected agent`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        #expect(await store.enqueueCommand(OpenClawChatOutboxCommand(
            id: "c-ownerless",
            sessionKey: "global",
            text: "choose my owner",
            thinking: "off",
            expectedSessionSettings: OpenClawChatSessionSettingsExpectation(permissionMode: nil, toolOverrides: nil),
            createdAt: Date().timeIntervalSince1970,
            status: .failed,
            retryCount: 0,
            lastError: OpenClawChatSQLiteTranscriptCache.outboxUnknownTargetError)))
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(
            transport: transport,
            outbox: store,
            sessionKey: "global",
            activeAgentID: nil)
        await MainActor.run { vm.load() }
        try await waitUntil("ownerless failed row visible") {
            await MainActor.run { vm.messages.contains { vm.outboxState(for: $0.id)?.isFailed == true } }
        }
        let messageID = try #require(await MainActor.run {
            vm.messages.first { vm.outboxState(for: $0.id)?.isFailed == true }?.id
        })

        await MainActor.run { vm.retryOutboxMessage(messageID) }
        try await waitUntil("ownerless retry asks for an agent") {
            await MainActor.run { vm.errorText == "Select an agent before retrying this message." }
        }
        let command = await store.loadCommands().first
        #expect(command?.status == .failed)
        #expect(command?.agentID == nil)
    }

    @Test func `unavailable recovery keeps the live send FIFO gate closed`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let outbox = ScriptedOutbox(base: store)
        await outbox.setRecoveryAvailable(false)
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: outbox)

        await MainActor.run { vm.load() }
        await outbox.waitUntilRecoveryAttempted()

        #expect(await MainActor.run { !vm.hasRestoredOutboxMessages })
    }

    @Test func `reconnect flushes queued commands in order with their idempotency keys`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        // One facade routes cache and outbox operations to their separate files.
        let vm = await makeOutboxViewModel(transport: transport, outbox: store, transcriptCache: store)

        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: "first")
        try await sendWhileOffline(vm, text: "second")
        let queuedIDs = await store.loadCommands().map(\.id)
        #expect(queuedIDs.count == 2)

        await transport.goOnline()

        try await waitUntil("outbox drained") {
            await store.loadCommands().isEmpty
        }
        // At-least-once contract: the transport saw each command exactly once
        // here, keyed by its client UUID, in strict createdAt order.
        #expect(await transport.state.sentIdempotencyKeys == queuedIDs)
        #expect(await transport.state.sentMessages == ["first", "second"])
        #expect(await transport.state.sentSessionKeys == ["agent:main:main", "agent:main:main"])

        // Durable history replaced the queued bubbles without duplicating
        // them, and no outbox state markers remain.
        try await waitUntil("durable history reconciled") {
            await MainActor.run { vm.sessionId == "sess-live" }
        }
        #expect(await userTexts(vm) == ["first", "second"])
        #expect(await MainActor.run { vm.outboxStatesByMessageID.count } == 0)

        // The refreshed gateway history is cached for cold offline browsing.
        let cached = await store.loadTranscript(sessionKey: "main", agentID: "main")
        let cachedUserTexts = cached
            .filter { $0.role == "user" }
            .map { $0.content.compactMap(\.text).joined() }
        #expect(cachedUserTexts == ["first", "second"])
    }

    @Test func `overlapping view models share one atomic FIFO sender`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let now = Date().timeIntervalSince1970
        #expect(await store.enqueueCommand(outboxTestCommand(id: "c-1", text: "first", createdAt: now)))
        #expect(await store.enqueueCommand(outboxTestCommand(id: "c-2", text: "second", createdAt: now + 1)))
        let transport = OutboxTestTransport(healthy: false)
        let firstVM = await makeOutboxViewModel(transport: transport, outbox: store)
        let secondVM = await makeOutboxViewModel(transport: transport, outbox: store)

        await transport.state.update { $0.healthy = true }
        await MainActor.run {
            firstVM.load()
            secondVM.load()
            firstVM.applyTransportHealth(true)
            secondVM.applyTransportHealth(true)
        }

        try await waitUntil("shared queue drained") {
            await store.loadCommands().isEmpty
        }
        #expect(await transport.state.sentIdempotencyKeys == ["c-1", "c-2"])
        #expect(await transport.state.sentMessages == ["first", "second"])
    }

    @Test func `assistant reply for a flushed run lands via the external-run final event`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: "question")
        await transport.goOnline()
        try await waitUntil("outbox drained") {
            await store.loadCommands().isEmpty
        }
        let runId = try #require(await transport.state.sentIdempotencyKeys.first)

        // Drop history availability so the assertion below can only be
        // satisfied by the event path, not a lucky history refresh. (The
        // scripted history never contains assistant rows, so leaving it on
        // would wipe the appended final with an incomplete snapshot.)
        await transport.state.update { $0.historyFails = true }

        // Flushed runs are intentionally not in pendingRuns; the reply is
        // delivered through the session-scoped external-run final branch.
        transport.emit(
            .chat(
                OpenClawChatEventPayload(
                    runId: runId,
                    sessionKey: "main",
                    state: "final",
                    message: AnyCodable([
                        "role": "assistant",
                        "content": [["type": "text", "text": "answer"]],
                        "timestamp": 5000.0,
                    ] as [String: Any]),
                    errorMessage: nil)))

        try await waitUntil("assistant reply visible") {
            await MainActor.run {
                vm.messages.contains { message in
                    message.role == "assistant" && message.content.contains { $0.text == "answer" }
                }
            }
        }
    }

    @Test func `acknowledged turn stays in client state until history confirms it`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store, transcriptCache: store)

        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: "must survive")

        // chat.send ACKs before user-turn persistence. With history still
        // unreachable, the row must remain durable and non-replayable.
        await transport.state.update { $0.historyFails = true }
        await transport.goOnline()
        try await waitUntil("acknowledgement awaits history") {
            await store.loadCommands().map(\.status) == [.awaitingConfirmation]
        }

        let cached = await store.loadTranscript(sessionKey: "main", agentID: "main")
        #expect(cached.isEmpty)
        #expect(await store.loadCommands().map(\.text) == ["must survive"])
        #expect(await MainActor.run {
            vm.messages.contains { vm.outboxState(for: $0.id) == .confirming }
        })

        await transport.state.update { $0.historyFails = false }
        await MainActor.run { vm.refresh() }
        try await waitUntil("canonical history confirms send") {
            await store.loadCommands().isEmpty
        }
    }

    @Test func `healthy restore reconciles a previously acknowledged turn`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        #expect(await store.enqueueCommand(outboxTestCommand(
            id: "c-awaiting",
            text: "already acknowledged",
            createdAt: Date().timeIntervalSince1970)))
        let claimed = await store.claimNextCommand()
        #expect(claimed?.id == "c-awaiting")
        #expect(await store.markCommandAwaitingConfirmation(
            id: "c-awaiting",
            attemptVersion: claimed?.attemptVersion ?? 0) == .updated)

        let transport = OutboxTestTransport(healthy: true)
        await transport.state.recordSend(
            sessionKey: "main",
            agentID: nil,
            message: "already acknowledged",
            idempotencyKey: "c-awaiting",
            thinking: "off")
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)
        await MainActor.run { vm.load() }

        try await waitUntil("restore history confirms acknowledged turn") {
            await store.loadCommands().isEmpty
        }
        #expect(await transport.state.sentMessages == ["already acknowledged"])
    }

    @Test func `delete race preserves a turn already proven by canonical history`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        #expect(await store.enqueueCommand(outboxTestCommand(
            id: "c-delivered",
            text: "delivered already",
            createdAt: Date().timeIntervalSince1970)))
        let holdingOutbox = ScriptedOutbox(base: store, forwarding: .holdingCancellation)
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(
            transport: transport,
            outbox: holdingOutbox,
            transcriptCache: store)
        await MainActor.run { vm.load() }
        try await waitUntil("delivered command restored") {
            await MainActor.run { vm.messages.contains { vm.outboxState(for: $0.id) == .queued } }
        }
        let canonicalMessage = OpenClawChatMessage(
            role: "user",
            content: [OpenClawChatMessageContent(
                type: "text",
                text: "delivered already",
                mimeType: nil,
                fileName: nil,
                content: nil)],
            timestamp: 1,
            idempotencyKey: "c-delivered:user")
        let messageID = try #require(await MainActor.run { vm.messages.last?.id })
        await MainActor.run { vm.deleteOutboxMessage(messageID) }
        await holdingOutbox.waitUntilCanceled()
        // Canonical proof lands after SQLite committed the cancellation but
        // before its result can remove presentation state on the MainActor.
        await MainActor.run { vm.confirmOutboxCommands(in: [canonicalMessage]) }
        await holdingOutbox.releaseCancellation()
        try await waitUntil("canonical proof wins delete race") {
            let commandsEmpty = await store.loadCommands().isEmpty
            let badgeCleared = await MainActor.run { vm.outboxState(for: messageID) == nil }
            return commandsEmpty && badgeCleared
        }
        #expect(await userTexts(vm) == ["delivered already"])
    }

    @Test func `offline local slash command keeps its draft and skips transport`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)
        await MainActor.run {
            // A transient transport loss can leave the preserved view model
            // healthy until the next explicit probe.
            vm.healthOK = true
            vm.input = "/new"
            vm.send()
        }
        try await waitUntil("offline slash command rejected") {
            await MainActor.run { vm.errorText == "Connect to the gateway to run this command." }
        }
        #expect(await MainActor.run { vm.input } == "/new")
        #expect(await store.loadCommands().isEmpty)
        #expect(await transport.state.sentMessages.isEmpty)
    }

    @Test func `lagging history does not recursively refresh an acknowledged turn`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        #expect(await store.enqueueCommand(outboxTestCommand(
            id: "c-lagging",
            text: "not persisted yet",
            createdAt: Date().timeIntervalSince1970)))
        let claimed = await store.claimNextCommand()
        #expect(claimed?.id == "c-lagging")
        #expect(await store.markCommandAwaitingConfirmation(
            id: "c-lagging",
            attemptVersion: claimed?.attemptVersion ?? 0) == .updated)

        let transport = OutboxTestTransport(healthy: true)
        await transport.state.update { $0.staleHistoryRows = [] }
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)
        await MainActor.run { vm.load() }
        try await waitUntil("bootstrap history settles") {
            let bootstrapComplete = await MainActor.run { !vm.isLoading }
            let requestCount = await transport.state.historyRequestCount
            return bootstrapComplete && requestCount >= 1
        }
        // A recursive refresh starts immediately after applying stale history.
        // Observe beyond bootstrap completion instead of sampling between its
        // ordinary history request and the health-triggered reconciliation.
        try await Task.sleep(nanoseconds: 1_000_000_000)

        // load() also owns its ordinary visible-session history request. The
        // exact count can be one or two; neither may trigger a recursive pass.
        #expect(await transport.state.historyRequestCount <= 2)
        #expect(await store.loadCommands().map(\.status) == [.awaitingConfirmation])
    }

    @Test func `gateway rejections burn attempts then fail terminally and support tap retry`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: "doomed")

        // Gateway is reachable again but rejects the run on every attempt.
        await transport.state.update { $0.sendRejects = true }
        await transport.goOnline()

        try await waitUntil("command failed after max attempts") {
            await store.loadCommands().map(\.status) == [.failed]
        }
        let failed = try #require(await store.loadCommands().first)
        #expect(failed.retryCount == OpenClawChatViewModel.maxOutboxSendAttempts)
        #expect(failed.lastError != nil)
        try await waitUntil("failed state visible") {
            await MainActor.run {
                vm.messages.contains { vm.outboxState(for: $0.id)?.isFailed == true }
            }
        }
        try await waitUntil("terminal failure flush settled") {
            await MainActor.run { !vm.isFlushingOutbox }
        }

        // Tap-to-retry resets attempts; with the gateway accepting again the
        // command now flushes and the row disappears.
        await transport.state.update { $0.sendRejects = false }
        let failedMessageID = try #require(await MainActor.run {
            vm.messages.first { vm.outboxState(for: $0.id)?.isFailed == true }?.id
        })
        await MainActor.run { vm.retryOutboxMessage(failedMessageID) }
        try await waitUntil("retried command drained", timeoutSeconds: 30) {
            await store.loadCommands().isEmpty
        }
        #expect(await transport.state.sentIdempotencyKeys.count == 1)
    }

    @Test func `unavailable terminal write drops health instead of advancing FIFO`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        #expect(await store.updateLastActiveLeafEntryID(
            "leaf-new",
            expectedEpoch: 0,
            for: OpenClawChatOutboxScope(sessionKey: "main", agentID: "main")))
        #expect(await store.updateLastActiveLeafEntryID(
            "leaf-new",
            expectedEpoch: 0,
            for: OpenClawChatOutboxScope(sessionKey: "main", agentID: nil)))
        #expect(await store.enqueueCommand(OpenClawChatOutboxCommand(
            id: "c-terminal-write",
            sessionKey: "main",
            routingContract: "per-sender|main|main",
            text: "do not skip me",
            thinking: "off",
            expectedSessionSettings: OpenClawChatSessionSettingsExpectation(permissionMode: nil, toolOverrides: nil),
            createdAt: Date().timeIntervalSince1970,
            status: .queued,
            retryCount: OpenClawChatViewModel.maxOutboxSendAttempts - 1,
            lastError: "rejected")))
        let outbox = ScriptedOutbox(base: store)
        await outbox.setTerminalWritesAvailable(false)
        let transport = OutboxTestTransport(healthy: false)
        await transport.state.update { $0.sendRejects = true }
        let vm = await makeOutboxViewModel(transport: transport, outbox: outbox)

        await MainActor.run { vm.load() }
        await transport.goOnline()

        try await waitUntil("terminal write failure closes health with claim intact") {
            let status = await store.loadCommands().first?.status
            let healthDown = await MainActor.run { !vm.healthOK }
            return status == .sending && healthDown
        }
        #expect(await MainActor.run {
            vm.messages.allSatisfy { vm.outboxState(for: $0.id)?.isFailed != true }
        })
    }

    @Test func `gateway response errors are definitive and burn retry attempts`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: "definitively rejected")
        await transport.state.update { $0.sendResponseErrors = true }
        await transport.goOnline()

        try await waitUntil("response error exhausts retry budget") {
            await store.loadCommands().map(\.status) == [.failed]
        }
        let failed = try #require(await store.loadCommands().first)
        #expect(failed.retryCount == OpenClawChatViewModel.maxOutboxSendAttempts)
        #expect(await transport.state.sentIdempotencyKeys.isEmpty)
    }

    @Test func `definitive live-send rejection restores draft without queueing`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: true)
        await transport.state.update { $0.sendResponseErrors = true }
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { vm.load() }
        // Wait for outbox restore too: until it completes, sends deliberately
        // route behind the outbox (FIFO gate), which is not the path under test.
        try await waitUntil("bootstrap healthy") {
            await MainActor.run { vm.healthOK && vm.hasRestoredOutboxMessages }
        }
        await MainActor.run {
            vm.input = "keep this draft"
            vm.send()
        }
        try await waitUntil("definitive rejection surfaced") {
            await MainActor.run { vm.errorText != nil }
        }
        #expect(await MainActor.run { vm.input } == "keep this draft")
        #expect(await userTexts(vm).isEmpty)
        #expect(await store.loadCommands().isEmpty)
    }

    @Test func `ambiguous live transport failure requires explicit retry`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        // Health reads true, but the actual send path is down: the send gate
        // is bypassed and the transport error must preserve instead of losing
        // the optimistic turn.
        let transport = OutboxTestTransport(healthy: true, sendFails: true)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { vm.load() }
        // Wait for outbox restore too: until it completes, sends deliberately
        // route behind the outbox (FIFO gate), which is not the path under test.
        try await waitUntil("bootstrap healthy") {
            await MainActor.run { vm.healthOK && vm.hasRestoredOutboxMessages }
        }
        await MainActor.run {
            vm.input = "stale health send"
            vm.send()
        }

        // The optimistic bubble survives, but delivery is ambiguous. It must
        // not return to the automatic queue after dedupe expiry or restart.
        try await waitUntil("ambiguous send preserved durably") {
            await store.loadCommands().map(\.status) == [.failed]
        }
        let preserved = try #require(await store.loadCommands().first)
        #expect(preserved.lastError == OpenClawChatSQLiteTranscriptCache.outboxUnconfirmedError)
        #expect(preserved.retryCount == 0)
        #expect(preserved.text == "stale health send")
        #expect(preserved.expectedSessionSettings ==
            OpenClawChatSessionSettingsExpectation(permissionMode: nil, toolOverrides: nil))
        #expect(await userTexts(vm) == ["stale health send"])
        let bubbleKey = await MainActor.run {
            vm.messages.first { $0.role == "user" }?.idempotencyKey
        }
        #expect(bubbleKey == "\(preserved.id):user")
        #expect(await MainActor.run {
            vm.messages.contains { vm.outboxState(for: $0.id)?.isFailed == true }
        })
        #expect(await MainActor.run { !vm.healthOK })

        // Connectivity recovery only reconciles history; it cannot replay an
        // unproven send. A user retry creates the new delivery intent.
        await transport.state.update { $0.sendFails = false }
        await transport.goOnline()
        try await Task.sleep(nanoseconds: 50_000_000)
        #expect(await store.loadCommands().map(\.status) == [.failed])
        #expect(await transport.state.sentIdempotencyKeys.isEmpty)

        let messageID = try #require(await MainActor.run { vm.messages.last?.id })
        await MainActor.run { vm.retryOutboxMessage(messageID) }
        try await waitUntil("explicit retry drained", timeoutSeconds: 10) {
            await store.loadCommands().isEmpty
        }
        #expect(await transport.state.sentIdempotencyKeys == [preserved.id])
        #expect(await transport.state.sentSessionSettings == [
            OpenClawChatSessionSettingsExpectation(permissionMode: nil, toolOverrides: nil),
        ])
    }

    @Test func `lost queued send ack reconciles history without replay`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: "accepted before disconnect")
        await transport.state.update { $0.sendFailsAfterRecording = true }
        await transport.goOnline()

        try await waitUntil("gateway accepted before ack loss") {
            await transport.state.sentIdempotencyKeys.count == 1
        }
        try await waitUntil("canonical history retires ambiguous send") {
            await store.loadCommands().isEmpty
        }
        #expect(await transport.state.sentMessages == ["accepted before disconnect"])
        #expect(await transport.state.sentIdempotencyKeys.count == 1)
    }

    @Test func `tap retry refreshes createdAt so an expired command can resend`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        // A command that sat offline past the staleness bound.
        let staleCreatedAt = Date().timeIntervalSince1970 -
            OpenClawChatSQLiteTranscriptCache.outboxCommandMaxAge - 60
        #expect(await store.enqueueCommand(
            OpenClawChatOutboxCommand(
                id: "c-expired",
                sessionKey: "main",
                text: "old message",
                thinking: "off",
                expectedSessionSettings: OpenClawChatSessionSettingsExpectation(
                    permissionMode: nil,
                    toolOverrides: nil),
                createdAt: staleCreatedAt,
                status: .queued,
                retryCount: 0,
                lastError: nil)))
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { vm.load() }
        // Restore surfaces the expired command as failed("expired").
        try await waitUntil("expired command visible as failed") {
            await MainActor.run {
                vm.messages.contains { vm.outboxState(for: $0.id)?.isFailed == true }
            }
        }
        #expect(await store.loadCommands().map(\.lastError) == [
            OpenClawChatSQLiteTranscriptCache.outboxExpiredError,
        ])

        // Explicit retry is new intent: createdAt refreshes, so the row goes
        // back to queued instead of immediately re-expiring, and it flushes
        // once the gateway is reachable.
        let messageID = try #require(await MainActor.run {
            vm.messages.first { vm.outboxState(for: $0.id)?.isFailed == true }?.id
        })
        await MainActor.run { vm.retryOutboxMessage(messageID) }
        try await waitUntil("retried command re-queued") {
            await store.loadCommands().map(\.status) == [.queued]
        }
        await transport.goOnline()
        try await waitUntil("expired-then-retried command drained") {
            await store.loadCommands().isEmpty
        }
        try await waitUntil("expired-then-retried bubble clears") {
            await MainActor.run { vm.outboxState(for: messageID) == nil }
        }
        #expect(await transport.state.sentMessages == ["old message"])
    }

    @Test func `flush gates captured thinking using the queued session metadata`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let now = Date().timeIntervalSince1970
        #expect(await store.enqueueCommand(
            OpenClawChatOutboxCommand(
                id: "c-think",
                sessionKey: "reasoning-session",
                routingContract: "per-sender|main|main",
                text: "think hard",
                thinking: "high",
                expectedSessionSettings: OpenClawChatSessionSettingsExpectation(
                    permissionMode: nil,
                    toolOverrides: nil),
                createdAt: now,
                status: .queued,
                retryCount: 0,
                lastError: nil)))
        #expect(await store.enqueueCommand(
            OpenClawChatOutboxCommand(
                id: "c-plain",
                sessionKey: "plain-session",
                routingContract: "per-sender|main|main",
                text: "no thinking",
                thinking: "medium",
                expectedSessionSettings: OpenClawChatSessionSettingsExpectation(
                    permissionMode: nil,
                    toolOverrides: nil),
                createdAt: now + 1,
                status: .queued,
                retryCount: 0,
                lastError: nil)))
        let sessionEntries = [
            outboxSessionEntry(key: "main", thinkingLevels: ["off"]),
            outboxSessionEntry(key: "reasoning-session", thinkingLevels: ["off", "high"]),
            outboxSessionEntry(key: "plain-session", thinkingLevels: ["off"]),
        ]
        let transport = OutboxTestTransport(healthy: false, sessions: sessionEntries)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { vm.load() }
        await MainActor.run {
            vm.sessions = sessionEntries
            vm.syncThinkingLevelOptions()
        }
        #expect(await MainActor.run { !vm.showsThinkingPicker })
        await transport.goOnline()
        try await waitUntil("background send confirmed") {
            await store.loadCommands().isEmpty
        }
        #expect(await transport.state.sentThinkingLevels == ["high", "off"])
        #expect(await transport.state.sentSessionKeys == ["reasoning-session", "plain-session"])
        _ = vm
    }

    @Test func `gateway history caches a flushed background-session turn`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        // Queued for a session the user is no longer viewing.
        #expect(await store.enqueueCommand(
            OpenClawChatOutboxCommand(
                id: "c-background",
                sessionKey: "other-session",
                routingContract: "per-sender|main|main",
                text: "sent from elsewhere",
                thinking: "off",
                expectedSessionSettings: OpenClawChatSessionSettingsExpectation(
                    permissionMode: nil,
                    toolOverrides: nil),
                createdAt: Date().timeIntervalSince1970,
                status: .queued,
                retryCount: 0,
                lastError: nil)))
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store, transcriptCache: store)

        await MainActor.run { vm.load() }
        await transport.goOnline()
        try await waitUntil("background send confirmed without opening its session") {
            await store.loadCommands().isEmpty
        }

        // Canonical gateway history, not the optimistic outbox row, owns the
        // cached background transcript.
        let cached = await store.loadTranscript(sessionKey: "other-session")
        #expect(cached.map { $0.content.compactMap(\.text).joined() } == ["sent from elsewhere"])
        #expect(cached.map(\.idempotencyKey) == ["c-background:user"])
    }

    @Test func `background canonical alias event confirms by idempotency key`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        #expect(await store.enqueueCommand(OpenClawChatOutboxCommand(
            id: "c-alias",
            sessionKey: "main",
            deliverySessionKey: "agent:main:main",
            routingContract: "per-sender|main|main",
            agentID: "main",
            text: "canonical alias",
            thinking: "off",
            expectedSessionSettings: OpenClawChatSessionSettingsExpectation(permissionMode: nil, toolOverrides: nil),
            createdAt: Date().timeIntervalSince1970,
            status: .queued,
            retryCount: 0,
            lastError: nil)))
        let claimed = await store.claimNextCommand()
        #expect(claimed?.id == "c-alias")
        #expect(await store.markCommandAwaitingConfirmation(
            id: "c-alias",
            attemptVersion: claimed?.attemptVersion ?? 0) == .updated)
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store, transcriptCache: store)
        await MainActor.run {
            vm.load()
            vm.switchSession(to: "other-session")
        }

        transport.emit(.sessionMessage(OpenClawSessionMessageEventPayload(
            sessionKey: "agent:main:main",
            agentId: "main",
            message: OpenClawChatMessage(
                role: "user",
                content: [OpenClawChatMessageContent(
                    type: "text",
                    text: "canonical alias",
                    mimeType: nil,
                    fileName: nil,
                    content: nil)],
                timestamp: 1,
                idempotencyKey: "c-alias:user"),
            messageId: "message-c-alias",
            messageSeq: 1)))

        try await waitUntil("canonical alias confirms background command") {
            await store.loadCommands().isEmpty
        }
        let cached = await store.loadTranscript(sessionKey: "main", agentID: "main")
        #expect(cached.map(\.idempotencyKey) == ["c-alias:user"])
        #expect(cached.map { $0.content.compactMap(\.text).joined() } == ["canonical alias"])
    }

    @Test func `full queue refuses enqueue and keeps the draft`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        for index in 0..<OpenClawChatSQLiteTranscriptCache.maxQueuedCommands {
            let accepted = await store.enqueueCommand(
                OpenClawChatOutboxCommand(
                    id: "prefill-\(index)",
                    sessionKey: "other",
                    text: "m\(index)",
                    thinking: "off",
                    expectedSessionSettings: OpenClawChatSessionSettingsExpectation(
                        permissionMode: nil,
                        toolOverrides: nil),
                    createdAt: Date().timeIntervalSince1970,
                    status: .queued,
                    retryCount: 0,
                    lastError: nil))
            #expect(accepted)
        }
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run {
            vm.input = "does not fit"
            vm.send()
        }
        try await waitUntil("refusal surfaced") {
            await MainActor.run { vm.errorText != nil }
        }
        // The draft survives so the text is not lost, and no row was added.
        #expect(await MainActor.run { vm.input } == "does not fit")
        #expect(await userTexts(vm).isEmpty)
        #expect(await store.loadCommands().count == OpenClawChatSQLiteTranscriptCache.maxQueuedCommands)
    }

    @Test func `accepted enqueue after session switch preserves newer original-session draft`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let outbox = ScriptedOutbox(base: store)
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: outbox)
        await MainActor.run { vm.load() }
        try await waitUntil("initial outbox restore") {
            await MainActor.run { vm.hasRestoredOutboxMessages }
        }
        await outbox.holdEnqueue()

        await MainActor.run {
            vm.input = "queued once"
            vm.send()
        }
        await outbox.waitUntilEnqueueStarted()
        await MainActor.run {
            vm.switchSession(to: "other")
            vm.switchSession(to: "main")
            vm.input = ""
            vm.input = "queued once"
            vm.switchSession(to: "other")
        }
        await outbox.releaseEnqueue()
        try await waitUntil("enqueue accepted after switch") {
            await store.loadCommands().count == 1
        }
        try await waitUntil("newer original-session draft preserved") {
            await MainActor.run { vm.draftsBySession[vm.composerSessionKey(for: "main")] == "queued once" }
        }

        await MainActor.run { vm.switchSession(to: "main") }
        #expect(await MainActor.run { vm.input } == "queued once")
        #expect(await MainActor.run { vm.recallPreviousInput(caretOnFirstLine: true) })
        #expect(await MainActor.run { vm.input } == "queued once")
        #expect(await MainActor.run { vm.recallNextInput() })
        #expect(await MainActor.run { vm.input } == "queued once")
    }

    @Test func `accepted enqueue preserves retyped identical current-session draft`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let outbox = ScriptedOutbox(base: store)
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: outbox)
        await MainActor.run { vm.load() }
        try await waitUntil("initial outbox restore") {
            await MainActor.run { vm.hasRestoredOutboxMessages }
        }
        await outbox.holdEnqueue()

        await MainActor.run {
            vm.input = "queued once"
            vm.send()
        }
        await outbox.waitUntilEnqueueStarted()
        await MainActor.run {
            vm.input = ""
            vm.input = "queued once"
        }
        await outbox.releaseEnqueue()
        try await waitUntil("enqueue accepted") {
            await store.loadCommands().count == 1
        }
        try await waitUntil("submission finished") {
            await MainActor.run { !vm.isSubmittingDraft }
        }

        #expect(await MainActor.run { vm.input } == "queued once")
    }

    @Test(arguments: [false, true])
    func `queued send transport failure fails closed until explicit retry`(retryBeforeReconnect: Bool) async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false, sendFails: true)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { vm.load() }
        try await waitUntil("offline bootstrap settled") {
            await MainActor.run { !vm.isLoading && vm.hasRestoredOutboxMessages }
        }
        // A failed history request cannot refresh the displayed retry version.
        await transport.state.update { $0.historyFails = retryBeforeReconnect }
        try await sendWhileOffline(vm, text: "stuck in transit")

        // Gateway reports healthy but the send throws. One ambiguous attempt
        // must fail closed and drop health without automatic replay.
        await transport.goOnline()
        try await waitUntil("ambiguous queued send fails closed") {
            let failed = await store.loadCommands().first?.status == .failed
            let healthDown = await MainActor.run { !vm.healthOK }
            return failed && healthDown
        }
        let command = try #require(await store.loadCommands().first)
        #expect(command.lastError == OpenClawChatSQLiteTranscriptCache.outboxUnconfirmedError)
        #expect(command.retryCount == 0)
        #expect(await transport.state.sentIdempotencyKeys.isEmpty)

        try await waitUntil("failed send is visible and settled") {
            await MainActor.run {
                !vm.isFlushingOutbox && vm.messages.contains { vm.outboxState(for: $0.id)?.isFailed == true }
            }
        }
        // Retry must work from the displayed failure, even before reconnect
        // or a successful history refresh can reload the durable command.
        await transport.state.update { $0.sendFails = false }
        if !retryBeforeReconnect {
            let historyRequests = await transport.state.historyRequestCount
            await transport.goOnline()
            try await waitUntil("reconnect reconciles without replay") {
                let historyRefreshed = await transport.state.historyRequestCount > historyRequests
                return await MainActor.run { historyRefreshed && vm.healthOK && !vm.isFlushingOutbox }
            }
        }
        #expect(await store.loadCommands().map(\.status) == [.failed])

        let messageID = try #require(await MainActor.run {
            vm.messages.first { vm.outboxState(for: $0.id)?.isFailed == true }?.id
        })
        await MainActor.run { vm.retryOutboxMessage(messageID) }
        if retryBeforeReconnect {
            try await waitUntil("offline explicit retry queues command") {
                await store.loadCommands().map(\.status) == [.queued]
            }
            await transport.state.update { $0.historyFails = false }
            await transport.goOnline()
        }
        try await waitUntil("explicit retry drains command") {
            await store.loadCommands().isEmpty
        }
        #expect(await transport.state.sentIdempotencyKeys == [command.id])
    }

    @Test func `deleting a queued message removes bubble and durable row`() async throws {
        let (store, databases, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store, transcriptCache: store)

        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: "changed my mind")

        let messageID = try #require(await MainActor.run {
            vm.messages.first { vm.outboxState(for: $0.id) == .queued }?.id
        })
        let commandID = try #require(await store.loadCommands().first?.id)
        let staleMessage = OpenClawChatMessage(
            role: "user",
            content: [OpenClawChatMessageContent(
                type: "text",
                text: "changed my mind",
                mimeType: nil,
                fileName: nil,
                content: nil)],
            timestamp: 1,
            idempotencyKey: "\(commandID):user")
        let stalePayload = try String(decoding: JSONEncoder().encode(staleMessage), as: UTF8.self)
        try await databases.cacheQueue.write { db in
            try db.execute(
                sql: """
                INSERT INTO cached_transcripts(gateway_id, session_key, agent_id, updated_at)
                VALUES (?, ?, ?, ?)
                """,
                arguments: ["gw-test", "main", "", 1])
            try db.execute(
                sql: """
                INSERT INTO cached_messages(
                    gateway_id, session_key, agent_id, position,
                    timestamp_ms, idempotency_key, payload_json
                ) VALUES (?, ?, ?, ?, ?, ?, ?)
                """,
                arguments: ["gw-test", "main", "", 0, 1, "\(commandID):user", stalePayload])
        }
        await MainActor.run { vm.deleteOutboxMessage(messageID) }

        // The bubble disappears only after the durable delete lands, so a
        // process kill can never orphan a hidden-but-persisted command.
        try await waitUntil("bubble removed after durable delete") {
            await userTexts(vm).isEmpty
        }
        #expect(await MainActor.run { vm.outboxStatesByMessageID.count } == 0)
        try await waitUntil("durable row deleted") {
            await store.loadCommands().isEmpty
        }
        try await waitUntil("canceled bubble removed from transcript cache") {
            await store.loadTranscript(sessionKey: "main", agentID: "main").isEmpty
        }

        // A later cold open must not repaint the canceled local bubble as an
        // ordinary sent transcript row after its outbox metadata is gone.
        let recreated = await makeOutboxViewModel(transport: transport, outbox: store, transcriptCache: store)
        await MainActor.run { recreated.load() }
        try await Task.sleep(nanoseconds: 100_000_000)
        #expect(await userTexts(recreated).isEmpty)
    }
}

actor DeleteGate {
    private var isOpen = false
    private var waiters: [CheckedContinuation<Void, Never>] = []

    func open() {
        self.isOpen = true
        for waiter in self.waiters {
            waiter.resume()
        }
        self.waiters.removeAll()
    }

    func wait() async {
        if self.isOpen {
            return
        }
        await withCheckedContinuation { self.waiters.append($0) }
    }

    func opened() -> Bool {
        self.isOpen
    }
}

extension ChatViewModelOutboxTests {
    @Test func `double submit during the offline health probe enqueues once`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { vm.load() }
        // Two rapid submits of the same draft: the second lands while the
        // first is still awaiting the forced health probe. The isSending
        // guard must swallow it instead of enqueueing a duplicate row.
        await MainActor.run {
            vm.input = "tap tap"
            vm.send()
            vm.send()
        }
        try await waitUntil("queued bubble for tap tap") {
            await MainActor.run {
                vm.messages.contains { message in
                    message.role == "user" && message.content.contains { $0.text == "tap tap" }
                }
            }
        }

        let commands = await store.loadCommands()
        #expect(commands.map(\.text) == ["tap tap"])
        #expect(await MainActor.run { vm.outboxStatesByMessageID.count } == 1)
    }

    @Test func `double submit during slash validation enqueues once`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false, supportsSlashCommands: true)
        let commandListGate = DeleteGate()
        await transport.state.update { $0.commandListGate = commandListGate }
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run {
            vm.input = "/remote-command"
            vm.send()
        }
        await transport.state.commandListStarted.wait()
        await MainActor.run {
            vm.input = "newer draft"
            #expect(!vm.canSend)
            vm.send()
        }
        await commandListGate.open()

        try await waitUntil("slash command queued once") {
            await store.loadCommands().count == 1
        }
        #expect(await store.loadCommands().map(\.text) == ["/remote-command"])
        #expect(await MainActor.run { vm.input } == "newer draft")
    }

    @Test func `stale history after the flush ack keeps the durable turn visible`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store, transcriptCache: store)

        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: "must survive stale history")

        // The gateway acks the flush but its history snapshot lags: it still
        // returns only an older turn without the just-sent idempotency key.
        let staleRow = AnyCodable([
            "role": "assistant",
            "content": [["type": "text", "text": "older turn"]],
            "timestamp": 500.0,
        ] as [String: Any])
        await transport.state.update { $0.staleHistoryRows = [staleRow] }
        await transport.goOnline()
        try await waitUntil("acknowledgement awaits canonical history") {
            await store.loadCommands().map(\.status) == [.awaitingConfirmation]
        }
        try await waitUntil("stale refresh applied") {
            await MainActor.run { vm.messages.contains { message in
                message.content.contains { $0.text == "older turn" }
            } }
        }
        // The cache remains a pure gateway snapshot. The durable confirmation
        // row is merged into the live view instead of being copied into it.
        if let pendingWrite = await MainActor.run(body: { vm.pendingCacheWriteTask }) {
            await pendingWrite.value
        }
        let cached = await store.loadTranscript(sessionKey: "main", agentID: "main")
        #expect(!cached.contains { message in
            message.content.contains { $0.text == "must survive stale history" }
        })
        #expect(await MainActor.run {
            vm.messages.contains { message in
                message.content.contains { $0.text == "must survive stale history" } &&
                    vm.outboxState(for: message.id) == .confirming
            }
        })
        await transport.state.update { $0.staleHistoryRows = nil }
        await MainActor.run { vm.refresh() }
        try await waitUntil("fresh history confirms send") {
            await store.loadCommands().isEmpty
        }
    }

    @Test func `send before restore adopts durable rows still queues behind them`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        // Persist a row as an earlier process would have.
        #expect(await store.enqueueCommand(OpenClawChatOutboxCommand(
            id: UUID().uuidString,
            sessionKey: "main",
            routingContract: "per-sender|main|main",
            text: "queued by the previous launch",
            thinking: "off",
            expectedSessionSettings: OpenClawChatSessionSettingsExpectation(permissionMode: nil, toolOverrides: nil),
            createdAt: Date().timeIntervalSince1970 - 60,
            status: .queued,
            retryCount: 0,
            lastError: nil)))

        // Healthy cold open: fire a send synchronously after load(), before
        // the async restore has adopted the durable row. The FIFO gate must
        // still route it behind the backlog.
        let transport = OutboxTestTransport(healthy: true)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)
        await MainActor.run {
            vm.load()
            vm.input = "typed instantly on open"
            vm.send()
        }

        try await waitUntil("both turns delivered") {
            await transport.state.sentMessages.count == 2
        }
        #expect(await transport.state.sentMessages == [
            "queued by the previous launch",
            "typed instantly on open",
        ])
        try await waitUntil("rows drained") {
            await store.loadCommands().isEmpty
        }
    }

    @Test func `send right after a session switch still queues behind that session's backlog`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        #expect(await store.updateLastActiveLeafEntryID(
            "leaf-new",
            expectedEpoch: 0,
            for: OpenClawChatOutboxScope(sessionKey: "second", agentID: nil)))
        #expect(await store.updateLastActiveLeafEntryID(
            "leaf-new",
            expectedEpoch: 0,
            for: OpenClawChatOutboxScope(sessionKey: "second", agentID: "main")))
        // Backlog persisted for a session that is not initially visible.
        #expect(await store.enqueueCommand(OpenClawChatOutboxCommand(
            id: UUID().uuidString,
            sessionKey: "second",
            routingContract: "per-sender|main|main",
            text: "backlog in second session",
            thinking: "off",
            expectedSessionSettings: OpenClawChatSessionSettingsExpectation(permissionMode: nil, toolOverrides: nil),
            createdAt: Date().timeIntervalSince1970 - 60,
            status: .queued,
            retryCount: 0,
            lastError: nil)))

        // Start offline so the backlog cannot drain before the switch.
        let transport = OutboxTestTransport(healthy: false)
        let outbox = ScriptedOutbox(base: store)
        let vm = await makeOutboxViewModel(transport: transport, outbox: outbox)
        await MainActor.run { vm.load() }
        // Let "main" finish restoring so the FIFO gate flag is set for it.
        try await waitUntil("initial session restored") {
            await MainActor.run { vm.hasRestoredOutboxMessages }
        }

        // Delay outbox reads from here on so, after the switch, neither the
        // new session's restore nor the reconnect flush can observe the
        // backlog before the send's gate check runs. Only the reset-on-switch
        // keeps ordering safe in that window.
        await outbox.setLoadDelayNanoseconds(150_000_000)

        // Switch, reconnect, and send immediately: the restore gate must
        // reset with the switch, so this send routes behind the new
        // session's backlog instead of going live ahead of it.
        await MainActor.run { vm.switchSession(to: "second") }
        await transport.goOnline()
        await MainActor.run {
            vm.input = "typed right after switching"
            vm.send()
        }

        try await waitUntil("both turns delivered") {
            await transport.state.sentMessages.count == 2
        }
        #expect(await transport.state.sentMessages == [
            "backlog in second session",
            "typed right after switching",
        ])
        try await waitUntil("rows drained") {
            await store.loadCommands().isEmpty
        }
    }

    @Test func `flush waits for an in-flight model patch before sending`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: "after the model change")

        // A model change is still patching when health recovers. The flush
        // must honor the same ordering as live sends and hold until the
        // patch resolves, or the run would start on the stale model.
        await MainActor.run { vm.selectModel("anthropic/claude-test") }
        try await waitUntil("model patch starts before outbox flush") {
            await transport.modelPatchHasStarted()
        }
        await transport.goOnline()
        try await Task.sleep(nanoseconds: 100_000_000)
        #expect(await transport.state.sentMessages.isEmpty)

        transport.releaseModelPatch()
        try await waitUntil("outbox drained after patch resolved") {
            await store.loadCommands().isEmpty
        }
        #expect(await transport.state.sentMessages == ["after the model change"])
    }

    @Test func `offline enqueue waits for a truly in-flight model patch`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { vm.load() }
        await MainActor.run {
            vm.selectModel("anthropic/claude-test")
            vm.input = "enqueue after model patch"
            vm.send()
        }
        try await waitUntil("model patch starts before offline enqueue") {
            await transport.modelPatchHasStarted()
        }
        try await Task.sleep(for: .milliseconds(50))
        #expect(await store.loadCommands().isEmpty)

        transport.releaseModelPatch()
        try await waitUntil("enqueue resumes after model patch") {
            await store.loadCommands().map(\.text) == ["enqueue after model patch"]
        }
        #expect(await transport.state.sentMessages.isEmpty)
    }

    @Test func `live send after reconnect queues behind draining outbox rows`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: "first, written offline")

        // Reconnect with the first send held mid-flight, then send live text
        // immediately: it must fall in line behind the draining row, not
        // race ahead of it.
        let gate = DeleteGate()
        await transport.state.update { $0.heldSendGate = gate }
        await transport.goOnline()
        try await waitUntil("first row claimed for sending") {
            await store.loadCommands().map(\.status) == [.sending]
        }
        await MainActor.run {
            vm.input = "second, right after reconnect"
            vm.send()
        }
        try await waitUntil("second row queued behind the first") {
            await store.loadCommands().map(\.text).contains("second, right after reconnect")
        }
        #expect(await transport.state.sentMessages.isEmpty)

        await gate.open()
        try await waitUntil("both rows drained in order") {
            await store.loadCommands().isEmpty
        }
        #expect(await transport.state.sentMessages == [
            "first, written offline",
            "second, right after reconnect",
        ])
    }

    @Test func `a stale second view model cannot cancel a claimed send`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        let sender = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { sender.load() }
        try await sendWhileOffline(sender, text: "already claimed")
        let observer = await makeOutboxViewModel(transport: transport, outbox: store)
        await MainActor.run { observer.load() }
        try await waitUntil("second view model restores queued bubble") {
            await MainActor.run { observer.outboxStatesByMessageID.count == 1 }
        }

        let messageID = try #require(await MainActor.run {
            observer.messages.first { observer.outboxState(for: $0.id) == .queued }?.id
        })
        let sendGate = DeleteGate()
        await transport.state.update { $0.heldSendGate = sendGate }
        // This fake exposes one shared event stream, unlike native transports that
        // broadcast reconnects. Select the intended owner instead of racing the observer.
        await MainActor.run { sender.applyTransportHealth(true) }
        try await waitUntil("first view model claims row") {
            await store.loadCommands().map(\.status) == [.sending]
        }
        await MainActor.run { observer.deleteOutboxMessage(messageID) }
        try await waitUntil("observer adopts sending status") {
            await MainActor.run { observer.outboxState(for: messageID) == .sending }
        }
        #expect(await store.loadCommands().map(\.status) == [.sending])

        await transport.state.update { $0.healthy = true }
        await sendGate.open()
        try await waitUntil("claimed send confirms") {
            await store.loadCommands().isEmpty
        }
        #expect(await transport.state.sentMessages == ["already claimed"])
    }

    @Test func `both view models remove a command canceled by either one`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        let first = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { first.load() }
        try await sendWhileOffline(first, text: "cancel everywhere")
        let second = await makeOutboxViewModel(transport: transport, outbox: store)
        await MainActor.run { second.load() }
        try await waitUntil("both views show queued command") {
            await MainActor.run {
                first.outboxStatesByMessageID.count == 1 && second.outboxStatesByMessageID.count == 1
            }
        }

        let firstID = try #require(await MainActor.run { first.messages.last?.id })
        let secondID = try #require(await MainActor.run { second.messages.last?.id })
        await MainActor.run { first.deleteOutboxMessage(firstID) }
        try await waitUntil("first view cancels durable row") {
            let rowsEmpty = await store.loadCommands().isEmpty
            let textEmpty = await userTexts(first).isEmpty
            return rowsEmpty && textEmpty
        }

        await MainActor.run { second.deleteOutboxMessage(secondID) }
        try await waitUntil("second view removes stale canceled bubble") {
            await userTexts(second).isEmpty
        }
        #expect(await transport.state.sentMessages.isEmpty)
    }

    @Test func `cancellation invalidates another views in flight restore snapshot`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        let cancelingView = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { cancelingView.load() }
        try await sendWhileOffline(cancelingView, text: "stale snapshot")
        #expect(await store.enqueueCommand(outboxTestCommand(
            id: "c-survivor",
            text: "survivor",
            createdAt: Date().timeIntervalSince1970 + 1)))
        let staleOutbox = ScriptedOutbox(base: store, forwarding: .minimal)
        await staleOutbox.holdNextLoad()
        let staleView = await MainActor.run {
            OpenClawChatViewModel(
                sessionKey: "main",
                transport: transport,
                activeAgentId: "main",
                sessionRoutingContract: "per-sender|main|main",
                outbox: staleOutbox)
        }
        await MainActor.run { staleView.load() }
        await staleOutbox.waitUntilSnapshotCaptured()

        let messageID = try #require(await MainActor.run { cancelingView.messages.last?.id })
        await MainActor.run { cancelingView.deleteOutboxMessage(messageID) }
        try await waitUntil("durable cancellation broadcasts") {
            await store.loadCommands().map(\.id) == ["c-survivor"]
        }
        await staleOutbox.releaseSnapshot()
        try await Task.sleep(nanoseconds: 100_000_000)

        try await waitUntil("invalidated restore reloads surviving command") {
            await userTexts(staleView) == ["survivor"]
        }
        #expect(await MainActor.run { staleView.outboxStatesByMessageID.count } == 1)
        #expect(await transport.state.sentMessages.isEmpty)
    }

    @Test func `confirmation invalidates cancellation claimed row reload`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let outbox = ScriptedOutbox(base: store, forwarding: .minimal)
        let transport = OutboxTestTransport(healthy: false)
        let vm = await MainActor.run {
            OpenClawChatViewModel(
                sessionKey: "main",
                transport: transport,
                activeAgentId: "main",
                sessionRoutingContract: "per-sender|main|main",
                outbox: outbox)
        }

        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: "confirmed during delete")
        let command = try #require(await store.claimNextCommand())
        let messageID = try #require(await MainActor.run { vm.messages.last?.id })
        await outbox.holdNextLoad()
        await MainActor.run { vm.deleteOutboxMessage(messageID) }
        await outbox.waitUntilSnapshotCaptured()

        #expect(await store.confirmCommand(
            id: command.id,
            attemptVersion: command.attemptVersion) == .updated)
        await outbox.releaseSnapshot()
        try await waitUntil("confirmation clears stale sending badge") {
            await MainActor.run { vm.outboxState(for: messageID) == nil }
        }
        #expect(await userTexts(vm) == ["confirmed during delete"])
    }

    @Test func `route replacement cannot retarget a claimed command`() async throws {
        let (store, _, databaseDirectory) = try makeOutboxStore()
        defer { try? FileManager.default.removeItem(at: databaseDirectory) }
        let transport = OutboxTestTransport(healthy: false)
        let vm = await makeOutboxViewModel(transport: transport, outbox: store)

        await MainActor.run { vm.load() }
        try await sendWhileOffline(vm, text: "belongs to the old route")
        let sendGate = DeleteGate()
        await transport.state.update { $0.heldSendGate = sendGate }
        await transport.goOnline()
        try await waitUntil("old route claims command") {
            await store.loadCommands().map(\.status) == [.sending]
        }

        await transport.state.update { $0.routeGeneration += 1 }
        await sendGate.open()
        try await waitUntil("pre-dispatch route cancellation requeues command") {
            await store.loadCommands().map(\.status) == [.queued]
        }
        #expect(await transport.state.sentMessages.isEmpty)
        #expect(await store.loadCommands().first?.lastError == nil)
        #expect(await MainActor.run { !vm.healthOK })
    }
}