File size: 75,048 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
import Foundation
import Observation
import OpenClawKit
import OpenClawProtocol
import OSLog

// Module-internal: ChatViewModel extension files share this logger.
let chatUILogger = Logger(subsystem: "ai.openclaw", category: "OpenClawChatUI")

@MainActor
@Observable
public final class OpenClawChatViewModel {
    static let maxAttachmentBytes = 5_000_000
    static let sessionListFetchLimit = 200

    public internal(set) var messages: [OpenClawChatMessage] = [] {
        didSet { self.sourcePreviewState.update(self.messages) }
    }

    let sourcePreviewState = ChatSourcePreviewState()

    public var input: String = "" {
        didSet {
            guard self.input != oldValue else { return }
            self.noteComposerInputChanged()
        }
    }

    public internal(set) var replyTarget: OpenClawChatReplyTarget?
    @ObservationIgnored
    var inputHistoriesBySession: [String: ChatInputHistory] = [:]
    /// Native attachments, including images restored by rewind/fork, stay in memory only.
    /// The staging guard prevents session switches while attachments are being prepared.
    @ObservationIgnored
    var draftsBySession: [String: String] = [:]
    @ObservationIgnored
    var composerRevisionsBySession: [String: UInt64] = [:]
    @ObservationIgnored
    var savedDraftRevisionsBySession: [String: UInt64] = [:]
    @ObservationIgnored
    var isApplyingRecalledInput = false
    /// Setter is module-internal for the thinking-level extension only.
    public internal(set) var thinkingLevel: String
    /// User intent stays stable while `thinkingLevel` follows the selected model's advertised levels.
    var preferredThinkingLevel: String
    /// Setter is module-internal for the thinking-level extension only.
    public internal(set) var thinkingLevelOptions: [OpenClawChatThinkingLevelOption]
    /// Setter is module-internal for the thinking-level extension only.
    public internal(set) var showsThinkingPicker = false
    public internal(set) var preferredVerboseLevel: String
    var prefersExplicitVerboseLevel: Bool
    public private(set) var modelSelectionID: String = "__default__"
    public internal(set) var modelChoices: [OpenClawChatModelChoice] = []
    var modelAvailabilityIsSessionScoped = false
    public internal(set) var modelCatalogMessage: String?
    var agentCatalog: OpenClawChatAgentsListResponse?
    var isLoadingAgents = false
    var agentsErrorText: String?
    @ObservationIgnored
    var hasRequestedAgents = false
    @ObservationIgnored
    var agentCatalogGeneration: UInt64 = 0
    @ObservationIgnored
    var nextModelCatalogRequestID: UInt64 = 0
    var modelPickerFavorites: [String]
    var modelPickerRecents: [String]
    /// Setters are module-internal for the sending extension's command catalog.
    public internal(set) var slashCommands: [OpenClawChatCommandChoice] = []
    public internal(set) var isLoadingSlashCommands = false
    public internal(set) var slashCommandsErrorText: String?
    public internal(set) var hasLoadedSlashCommands = false
    @ObservationIgnored
    var slashFilterCache: SlashFilterCache?

    private struct DeferredDeliveryIdentity {
        let activeAgentID: String?
        let sessionRoutingContract: String?
    }

    public private(set) var isLoading = false
    /// Setters are module-internal for the sending extension only.
    public internal(set) var isSending = false
    public internal(set) var isSendingAttachmentDraft = false
    private var deferredExternalSessionKey: String?
    private var deferredDeliveryIdentity: DeferredDeliveryIdentity?
    var isSubmittingDraft = false
    @ObservationIgnored
    var isCreatingSession = false
    var attachmentStagingCount = 0
    public private(set) var isAborting = false
    public var errorText: String?
    public var attachments: [OpenClawPendingAttachment] = []
    /// Setter is module-internal for the health/outbox extension only.
    public internal(set) var healthOK: Bool = false
    /// Bumped after every successful group-catalog mutation so views keyed on it
    /// refetch; catalog-only changes (e.g. creating an empty group) alter no
    /// session rows and would otherwise stay stale until reconnect.
    public internal(set) var sessionGroupsRevision = 0
    public internal(set) var sessionBranches: [OpenClawChatSessionBranch] = []
    public internal(set) var isLoadingSessionBranches = false
    @ObservationIgnored
    var sessionBranchesRefreshGeneration: UInt64 = 0
    var sessionBranchSwitchActivity: SessionBranchSwitchActivity?
    @ObservationIgnored
    var nextSessionBranchSwitchGeneration: UInt64 = 0

    public private(set) var pendingRunCount: Int = 0
    public internal(set) var questionCards: [OpenClawQuestionCardModel] = []
    var questionAttentionOwnerID = UUID()
    public internal(set) var isQuestionAuthorityRetired = false
    var questionRefreshGeneration: UInt64 = 0
    var questionStateRevision: UInt64 = 0
    var questionExpiryTasks: [String: Task<Void, Never>] = [:]
    var questionExpiryDeadlines: [String: Date] = [:]
    var questionRefreshRetryTask: Task<Void, Never>?
    var questionRefreshRetryDelaysMs: [Int64] = [1000, 2000, 4000]
    var hasActiveSessionRunWithoutChatSnapshot = false
    var activeSessionRunIDs: [String] = []
    var liveRunStateByRunID: [String: ChatLiveRunState] = [:]
    public internal(set) var progressCard: ProgressCard?
    var progressCardStoreAvailable: Bool?
    @ObservationIgnored
    var progressCardGeneration: UInt64 = 0
    @ObservationIgnored
    var preparedProgressCardTarget: (session: SessionSnapshot, generation: UInt64, target: OpenClawChatSessionTarget)?
    @ObservationIgnored
    var lastIssuedProgressCardRequestID: UInt64 = 0
    @ObservationIgnored
    var legacyProgressCardRevision = 0

    public private(set) var sessionKey: String {
        didSet {
            syncContextUsageFraction()
            syncActiveSessionRunIDsFromCurrentSession()
        }
    }

    public internal(set) var sessionId: String?
    public var currentSessionTarget: OpenClawChatSessionTarget {
        OpenClawChatSessionTarget(
            sessionKey: self.sessionKey,
            agentID: OpenClawChatSessionKey.agentID(from: self.sessionKey) == nil
                ? self.explicitSessionAgentID ?? self.activeAgentId : nil)
    }

    public private(set) var streamingAssistantText: String?

    public private(set) var pendingToolCalls: [OpenClawChatPendingToolCall] = []
    var subagentActivities: [ChatSubagentActivity] = []
    var hiddenWorkingSubagentCount = 0
    private(set) var timelineRevision: UInt64 = 0
    /// Setter is module-internal for the transcript-cache extension only.
    public internal(set) var sessions: [OpenClawChatSessionEntry] = [] {
        didSet {
            syncContextUsageFraction()
            syncActiveSessionRunIDsFromCurrentSession()
        }
    }

    public internal(set) var swarmSessions: [OpenClawChatSessionEntry] = []
    var activeSwarmGroups: [OpenClawChatSwarmGroup] = []
    var swarmActivityState = OpenClawChatSwarmActivityState()
    @ObservationIgnored
    var swarmRefreshGeneration: UInt64 = 0
    @ObservationIgnored
    var swarmSessionKey: String?
    @ObservationIgnored
    var swarmEnabled = false
    @ObservationIgnored
    var swarmRefreshTask: Task<Void, Never>?

    public internal(set) var contextUsageFraction: Double?
    let composerCapabilityState = OpenClawChatComposerCapabilityState()
    /// True while the visible transcript came from the offline cache and no
    /// live history response has replaced it yet (possibly stale).
    public internal(set) var isShowingCachedTranscript = false
    /// Guard the cache pre-paint: once a live response applied (even an empty
    /// one), a slow cache read must never paint stale rows over it.
    var hasAppliedLiveHistory = false
    var hasAppliedLiveSessions = false
    @ObservationIgnored
    var unreadPatchGuard = ChatSessionUnreadPatchGuard()
    let unreadMutationQueue = ChatSessionUnreadMutationQueue()
    /// Internal for the outbox extension's flush path only.
    let defaultTransport: any OpenClawChatTransport
    @ObservationIgnored
    var scopedSessionTransport: (any OpenClawChatTransport)?
    var explicitSessionAgentID: String?
    var transport: any OpenClawChatTransport {
        self.scopedSessionTransport ?? self.defaultTransport
    }

    let haptics: OpenClawChatHaptics
    let transcriptCache: (any OpenClawChatTranscriptCache)?
    let outbox: (any OpenClawChatCommandOutbox)?
    @ObservationIgnored
    let modelPickerStore: ChatModelPickerStore
    /// Per-message outbox display state; rows without an entry are normal
    /// transcript rows. Observable so bubbles update when flush progresses.
    public internal(set) var outboxStatesByMessageID: [UUID: OpenClawChatOutboxMessageState] = [:]
    @ObservationIgnored
    var outboxCommandIDsByMessageID: [UUID: String] = [:]
    @ObservationIgnored
    var outboxMessageIDsByCommandID: [String: UUID] = [:]
    @ObservationIgnored
    var outboxFailureVersionsByMessageID: [
        UUID: (attemptVersion: Int, retryCount: Int, lastError: String?)
    ] = [:]
    /// Recent canonical keys let the MainActor resolve proof that arrives
    /// after SQLite cancellation commits but before its UI continuation runs.
    @ObservationIgnored
    var canonicalOutboxMessageKeys: [String] = []
    @ObservationIgnored
    var isFlushingOutbox = false
    @ObservationIgnored
    var isOutboxFlushRequestedWhileActive = false
    @ObservationIgnored
    var reconciledOutboxBranchScopes: Set<OpenClawChatOutboxScope> = []
    @ObservationIgnored
    var reconcilingOutboxBranchScopes: Set<OpenClawChatOutboxScope> = []
    @ObservationIgnored
    var outboxBranchReconcileRetryAttempts: [OpenClawChatOutboxScope: Int] = [:]
    @ObservationIgnored
    var outboxBranchReconcileRetryTasks: [OpenClawChatOutboxScope: Task<Void, Never>] = [:]
    @ObservationIgnored
    var outboxBranchConnectionGeneration: UInt64 = 0
    @ObservationIgnored
    var bootstrapOutboxBranchStateCapture: (
        generation: UInt64,
        session: SessionSnapshot,
        task: Task<OpenClawChatOutboxBranchState?, Never>)?
    @ObservationIgnored
    var cancelingOutboxCommandIDs: Set<String> = []
    @ObservationIgnored
    var outboxPresentationGeneration: UInt64 = 0
    @ObservationIgnored
    var outboxChangesTask: Task<Void, Never>?
    /// Backoff between failed flush attempts; internal so tests can shorten it.
    @ObservationIgnored
    var outboxRetryDelaysMs: [UInt64] = [2000, 8000]
    /// False until restoreOutboxMessages has adopted durable rows for the
    /// visible session. Until then the in-memory outbox state is blind to
    /// rows persisted by an earlier process, so the FIFO send gate must
    /// assume a backlog exists.
    var hasRestoredOutboxMessages = false
    @ObservationIgnored
    nonisolated(unsafe) var outboxRetryTask: Task<Void, Never>?
    /// A command becomes terminally 'failed' after this many send attempts.
    nonisolated static let maxOutboxSendAttempts = 3
    @ObservationIgnored
    var pendingCacheWriteTask: Task<Void, Never>?
    private(set) var activeAgentId: String?
    private(set) var sessionRoutingContract: String?
    var sessionDefaults: OpenClawChatSessionsDefaults? {
        didSet { syncContextUsageFraction() }
    }

    var prefersExplicitThinkingLevel: Bool
    private let onSessionChanged: (@MainActor (String) -> Void)?
    let onThinkingLevelChanged: (@MainActor @Sendable (String) -> Void)?
    let onThinkingPreferenceChanged: (@MainActor @Sendable (String?) -> Void)?
    let onVerboseLevelChanged: (@MainActor @Sendable (String) -> Void)?
    let onVerbosePreferenceChanged: (@MainActor @Sendable (String?) -> Void)?
    private let diagnosticsLog: (@MainActor @Sendable (String) -> Void)?
    let onToolActivity: OpenClawChatToolActivityHandler?
    let attachmentOwnerIsActive: @MainActor () -> Bool

    @ObservationIgnored
    private nonisolated(unsafe) var eventTask: Task<Void, Never>?
    private(set) var isTransportDetached = false
    @ObservationIgnored
    private nonisolated(unsafe) var bootstrapTask: Task<Void, Never>?
    var runOwnershipGeneration: UInt64 = 0
    var latestAppliedRunSnapshotRequestID: UInt64 = 0
    var isApplyingRunSnapshot = false
    var pendingRuns = Set<String>() {
        didSet {
            if self.pendingRuns != oldValue, !self.isApplyingRunSnapshot {
                self.runOwnershipGeneration &+= 1
            }
            let nextCount = self.pendingRuns.count
            guard nextCount != self.pendingRunCount else { return }
            self.pendingRunCount = nextCount
            self.markTimelineChanged()
        }
    }

    var pendingLocalUserEchoMessageIDsByRunID: [String: UUID] = [:]
    // Final chat events and durable session-message rows arrive independently.
    // Keep each provisional final scoped to the run's user turn so a later identical
    // answer in the same session does not adopt or suppress the wrong row.
    var runMessageScopesByRunID: [String: RunMessageScope] = [:]
    var provisionalFinalMessagesByID: [UUID: ProvisionalFinalMessage] = [:]
    var sessionGeneration: UInt64 = 0
    private var bootstrapGeneration: UInt64 = 0
    // A newer same-session history request only invalidates older responses after it applies.
    // Failed later refreshes must not drop the last successful pending-run history payload.
    var lastIssuedHistoryRequestID: UInt64 = 0
    var latestAppliedHistoryRequestID: UInt64 = 0
    var historyMutationGeneration: UInt64 = 0
    private var nextSessionsFetchRequestID: UInt64 = 0
    private var latestAppliedSessionsFetchRequestID: UInt64 = 0
    /// Outbox replay waits for a sessions list from the current connection generation.
    var sessionMetadataGeneration: UInt64 = 0
    var readySessionMetadataGeneration: UInt64?

    @ObservationIgnored
    nonisolated(unsafe) var pendingRunOwnerTasks: [String: Task<Void, Never>] = [:]
    var nextPendingRunOwnerArmID: UInt64 = 0
    var pendingRunOwnerArmIDs: [String: UInt64] = [:]
    @ObservationIgnored
    nonisolated(unsafe) var activeSessionRunIndicatorTimeoutTask: Task<Void, Never>?
    var pendingRunWaitTimeoutMs: UInt64 = 120_000
    var pendingRunUnavailableRetryMs: UInt64 = 30000
    var pendingRunTerminalRetryMs: UInt64 = 2000
    var pendingRunTerminalHistoryGraceMs: UInt64 = 10000
    var pendingRunRefreshDelaysMs: [UInt64] = [
        1500,
        4000,
        9000,
        20000,
        45000,
    ]
    var pendingRunSteadyRefreshDelayMs: UInt64 = 60000
    // Session switches can overlap in-flight picker patches, so stale completions
    // must compare against the latest request and latest desired value for that session.
    private var nextSessionSettingsRequestID: UInt64 = 0
    private var latestModelSelectionRequestIDsByTarget: [ModelPatchTarget: UInt64] = [:]
    private var lastSuccessfulModelSelectionIDsByTarget: [ModelPatchTarget: String] = [:]
    var lastSuccessfulSettingsPatchRequestIDsByTarget: [ModelPatchTarget: UInt64] = [:]
    /// Rollback and pre-refresh sends need the authoritative state from the latest settings patch.
    var lastSuccessfulSettingsPatchResultsByTarget: [ModelPatchTarget: OpenClawChatModelPatchResult] = [:]
    var completedModelPatchTargets: Set<ModelPatchTarget> = []
    var inFlightSettingsPatchCountsByTarget: [ModelPatchTarget: Int] = [:]
    var capabilityPatchFailureRevisionsByTarget: [ModelPatchTarget: UInt64] = [:]
    var capabilityPatchFailureMessagesByTarget: [ModelPatchTarget: String] = [:]
    var confirmedCapabilityToolOverridesByTarget: [ModelPatchTarget: ToolOverridesState] = [:]
    var settingsPatchRevisionsByTarget: [ModelPatchTarget: UInt64] = [:]
    private var settingsPatchWaitersByTarget: [ModelPatchTarget: [CheckedContinuation<Void, Never>]] = [:]
    @ObservationIgnored
    private var settingsPatchTailsByTarget: [ModelPatchTarget: SettingsPatchTail] = [:]
    var nextThinkingSelectionRequestID: UInt64 = 0
    var latestThinkingSelectionRequestIDsByTarget: [ModelPatchTarget: UInt64] = [:]
    var confirmedThinkingPreference: ThinkingPreferenceState
    var emittedThinkingPreference: ThinkingPreferenceState
    var thinkingPreferenceRequests: [UInt64: ThinkingPreferenceRequest] = [:]
    var nextVerboseSelectionRequestID: UInt64 = 0
    var confirmedVerbosePreference: VerbosePreferenceState
    var emittedVerbosePreference: VerbosePreferenceState
    var verbosePreferenceRequests: [UInt64: VerbosePreferenceRequest] = [:]
    var acceptedVerboseLevelsByTarget: [ModelPatchTarget: VerboseLevelState] = [:]
    var acceptedFastModesByTarget: [ModelPatchTarget: FastModeState] = [:]
    var lastSuccessfulThinkingOverrideClearedByTarget: [ModelPatchTarget: Bool] = [:]
    var lastSuccessfulFastOverrideClearedByTarget: [ModelPatchTarget: Bool] = [:]
    var lastSuccessfulVerboseOverrideClearedByTarget: [ModelPatchTarget: Bool] = [:]
    var acceptedSettingsPatchResultsByTarget: [ModelPatchTarget: OpenClawChatModelPatchResult] = [:]
    var acceptedThinkingLevelsByTarget: [ModelPatchTarget: String] = [:]
    var acceptedPreferredThinkingLevelsByTarget: [ModelPatchTarget: String] = [:]
    var acceptedExplicitThinkingPreferencesByTarget: [ModelPatchTarget: Bool] = [:]
    var acceptedThinkingOverrideClearedByTarget: [ModelPatchTarget: Bool] = [:]
    private(set) var isCompacting = false
    private var lastCompactAt: Date?
    private let compactCooldown: TimeInterval = 60

    private enum SessionSwitchIntent {
        case userInitiated
        case externalSync
    }

    struct ModelPatchTarget: Hashable {
        let canonicalSessionKey: String
        let agentID: String?
        let sessionRoutingContract: String?
    }

    struct VerbosePreferenceState: Equatable {
        let level: String
        let isExplicit: Bool
    }

    enum VerbosePreferenceRequest {
        case pending(VerbosePreferenceState)
        case succeeded(VerbosePreferenceState)
        case failed
    }

    struct ThinkingPreferenceState: Equatable {
        let level: String
        let isExplicit: Bool
    }

    enum ThinkingPreferenceRequest {
        case pending(ThinkingPreferenceState)
        case succeeded(ThinkingPreferenceState)
        case failed
    }

    enum VerboseLevelState {
        case none
        case value(String)

        var level: String? {
            if case let .value(level) = self { return level }
            return nil
        }
    }

    enum ToolOverridesState {
        case none
        case value(OpenClawChatSessionToolOverrides)

        var overrides: OpenClawChatSessionToolOverrides? {
            if case let .value(overrides) = self { return overrides }
            return nil
        }
    }

    struct FastModeState {
        let override: OpenClawChatFastMode?
        let effective: OpenClawChatFastMode?
    }

    private struct ModelSelectionRequest {
        let id: UInt64
        let target: ModelPatchTarget
        let session: SessionSnapshot
        let sessionEntryKey: String?
        let rollbackSelectionID: String
        let previousRequestID: UInt64?
        let selectionID: String
        let modelRef: String?
    }

    private struct SettingsPatchTail {
        let requestID: UInt64
        let routeLeaseTask: Task<OpenClawChatSessionSettingsRouteLease?, Never>
        let task: Task<Void, Never>
    }

    private struct BootstrapContext {
        var id: UInt64
        var historyRequest: HistoryRequest

        var session: SessionSnapshot {
            self.historyRequest.session
        }
    }

    struct HistoryRequest {
        var id: UInt64
        var session: SessionSnapshot
        var pendingRunIDs: Set<String>
        var visibleMessagesByID: [UUID: OpenClawChatMessage]
        var historyMutationGeneration: UInt64
        var progressCardGeneration: UInt64
        var runOwnershipGeneration: UInt64
        var latestUserTurn: LatestUserTurn?
    }

    struct RunHistoryRefreshResult {
        let applied: Bool
        let runSnapshotApplied: Bool
        let supportsInFlightRunState: Bool
        let hasInFlightRun: Bool
        let sessionHasActiveRun: Bool

        static let failed = RunHistoryRefreshResult(
            applied: false,
            runSnapshotApplied: false,
            supportsInFlightRunState: false,
            hasInFlightRun: false,
            sessionHasActiveRun: false)
    }

    struct LatestUserTurn {
        var idempotencyKey: String?
        var refreshKey: String?
        var occurrence: Int
        var timestamp: Double?
    }

    struct RunMessageScope {
        var session: SessionSnapshot
        var latestUserTurn: LatestUserTurn?
    }

    struct ProvisionalFinalMessage {
        var reconciliationKey: String
        var runId: String?
        var scope: RunMessageScope
    }

    var pendingToolCallsById: [String: OpenClawChatPendingToolCall] = [:] {
        didSet {
            guard self.pendingToolCallsById != oldValue else { return }
            reportToolActivityChanges(from: oldValue, to: self.pendingToolCallsById)
            self.pendingToolCalls = self.pendingToolCallsById.values
                .sorted { ($0.startedAt ?? 0) < ($1.startedAt ?? 0) }
            markTimelineChanged()
        }
    }

    @ObservationIgnored
    var subagentActivityState = ChatSubagentActivityState()
    @ObservationIgnored
    var subagentActivityCleanupTask: Task<Void, Never>?

    var lastHealthPollAt: Date?

    public init(
        sessionKey: String,
        transport: any OpenClawChatTransport,
        activeAgentId: String? = nil,
        sessionRoutingContract: String? = nil,
        attachmentOwnerIsActive: @escaping @MainActor () -> Bool = { false },
        haptics: OpenClawChatHaptics = OpenClawChatHaptics(),
        transcriptCache: (any OpenClawChatTranscriptCache)? = nil,
        outbox: (any OpenClawChatCommandOutbox)? = nil,
        modelPickerStore: ChatModelPickerStore = ChatModelPickerStore(),
        initialThinkingLevel: String? = nil,
        initialVerboseLevel: String? = nil,
        onSessionChanged: (@MainActor (String) -> Void)? = nil,
        onThinkingLevelChanged: (@MainActor @Sendable (String) -> Void)? = nil,
        onToolActivity: OpenClawChatToolActivityHandler? = nil,
        onThinkingPreferenceChanged: (@MainActor @Sendable (String?) -> Void)? = nil,
        onVerboseLevelChanged: (@MainActor @Sendable (String) -> Void)? = nil,
        onVerbosePreferenceChanged: (@MainActor @Sendable (String?) -> Void)? = nil,
        diagnosticsLog: (@MainActor @Sendable (String) -> Void)? = nil)
    {
        self.sessionKey = sessionKey
        self.defaultTransport = transport
        self.haptics = haptics
        self.transcriptCache = transcriptCache
        self.modelPickerStore = modelPickerStore
        self.modelPickerFavorites = modelPickerStore.favorites
        self.modelPickerRecents = modelPickerStore.recents
        self.outbox = outbox
        let normalizedAgentId = activeAgentId?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
        self.activeAgentId = normalizedAgentId?.isEmpty == false ? normalizedAgentId : nil
        let normalizedRoutingContract = sessionRoutingContract?
            .trimmingCharacters(in: .whitespacesAndNewlines)
        self.sessionRoutingContract = normalizedRoutingContract?.isEmpty == false ? normalizedRoutingContract : nil
        let normalizedThinkingLevel = Self.normalizedThinkingLevel(initialThinkingLevel)
        let initialResolvedThinkingLevel = normalizedThinkingLevel ?? "off"
        self.thinkingLevel = initialResolvedThinkingLevel
        self.preferredThinkingLevel = initialResolvedThinkingLevel
        self.thinkingLevelOptions = []
        self.prefersExplicitThinkingLevel = normalizedThinkingLevel != nil
        let initialThinkingPreference = ThinkingPreferenceState(
            level: initialResolvedThinkingLevel,
            isExplicit: normalizedThinkingLevel != nil)
        self.confirmedThinkingPreference = initialThinkingPreference
        self.emittedThinkingPreference = initialThinkingPreference
        let normalizedVerboseLevel = Self.normalizedVerboseLevel(initialVerboseLevel)
        let initialResolvedVerboseLevel = normalizedVerboseLevel ?? "off"
        self.preferredVerboseLevel = initialResolvedVerboseLevel
        self.prefersExplicitVerboseLevel = normalizedVerboseLevel != nil
        let initialVerbosePreference = VerbosePreferenceState(
            level: initialResolvedVerboseLevel,
            isExplicit: normalizedVerboseLevel != nil)
        self.confirmedVerbosePreference = initialVerbosePreference
        self.emittedVerbosePreference = initialVerbosePreference
        self.onSessionChanged = onSessionChanged
        self.onThinkingLevelChanged = onThinkingLevelChanged
        self.onToolActivity = onToolActivity
        self.onThinkingPreferenceChanged = onThinkingPreferenceChanged
        self.onVerboseLevelChanged = onVerboseLevelChanged
        self.onVerbosePreferenceChanged = onVerbosePreferenceChanged
        self.diagnosticsLog = diagnosticsLog
        self.attachmentOwnerIsActive = attachmentOwnerIsActive

        let transport = self.transport
        self.eventTask = Task { [weak self, transport] in
            let stream = transport.events()
            for await evt in stream {
                if Task.isCancelled {
                    return
                }
                await MainActor.run { [weak self] in
                    self?.handleTransportEvent(evt)
                }
            }
        }
        if let outbox = self.outbox {
            let changes = outbox.changes()
            self.outboxChangesTask = Task { [weak self, changes] in
                for await change in changes {
                    guard !Task.isCancelled else { return }
                    self?.handleOutboxChange(change)
                }
            }
        }
    }

    isolated deinit {
        self.detachTransport()
    }

    /// Permanently retires a replaced presentation without aborting its gateway run.
    public func detachTransport() {
        guard !self.isTransportDetached else { return }
        self.retireQuestionAuthority()
        self.isTransportDetached = true
        self.invalidateSourceContext()
        self.endPendingToolActivities()
        self.eventTask?.cancel()
        self.bootstrapTask?.cancel()
        self.bootstrapOutboxBranchStateCapture?.task.cancel()
        self.swarmRefreshTask?.cancel()
        self.outboxRetryTask?.cancel()
        for task in self.outboxBranchReconcileRetryTasks.values {
            task.cancel()
        }
        self.outboxChangesTask?.cancel()
        self.activeSessionRunIndicatorTimeoutTask?.cancel()
        self.subagentActivityCleanupTask?.cancel()
        for (_, task) in self.pendingRunOwnerTasks {
            task.cancel()
        }
        for tail in self.settingsPatchTailsByTarget.values {
            tail.routeLeaseTask.cancel()
            tail.task.cancel()
        }
    }

    public func load() {
        startBootstrap()
    }

    public func refresh() {
        startBootstrap()
    }

    public func resumeFromForeground() {
        Task { await self.refreshRunStateAfterForeground() }
    }

    public func abort() {
        Task { await self.performAbort() }
    }

    public func switchSession(to sessionKey: String, agentID: String? = nil) {
        applySessionSwitch(to: sessionKey, intent: .userInitiated, agentID: agentID)
    }

    public func syncSession(to sessionKey: String) {
        applySessionSwitch(to: sessionKey, intent: .externalSync)
    }

    // periphery:ignore - package tests vary one identity field while preserving the current routing contract.
    public func syncActiveAgentId(_ agentId: String?) {
        self.syncDeliveryIdentity(
            activeAgentId: agentId,
            sessionRoutingContract: self.deferredDeliveryIdentity?.sessionRoutingContract
                ?? self.sessionRoutingContract)
    }

    public func syncSessionRoutingContract(_ contract: String?) {
        self.syncDeliveryIdentity(
            activeAgentId: self.deferredDeliveryIdentity?.activeAgentID ?? self.activeAgentId,
            sessionRoutingContract: contract)
    }

    /// Updates the alias owner and its gateway routing contract as one
    /// identity change so an intermediate bootstrap cannot win either value.
    public func syncDeliveryIdentity(
        activeAgentId agentId: String?,
        sessionRoutingContract contract: String?)
    {
        let normalized = agentId?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
        let nextAgentId = normalized?.isEmpty == false ? normalized : nil
        let normalizedContract = contract?.trimmingCharacters(in: .whitespacesAndNewlines)
        let nextContract = normalizedContract?.isEmpty == false ? normalizedContract : nil
        let agentChanged = self.activeAgentId != nextAgentId
        let contractChanged = self.sessionRoutingContract != nextContract
        guard agentChanged || contractChanged else {
            if blocksAttachmentOwnerChange {
                self.deferredDeliveryIdentity = nil
            }
            return
        }
        if blocksAttachmentOwnerChange {
            self.deferredDeliveryIdentity = DeferredDeliveryIdentity(
                activeAgentID: nextAgentId,
                sessionRoutingContract: nextContract)
            return
        }
        self.deferredDeliveryIdentity = nil
        // A scoped key can be the main alias under either side of a contract
        // change. Check both or stale transcript state can survive the switch.
        let contractRoutingChanged = contractChanged &&
            (usesMutableContractRouting(for: sessionRoutingContract) ||
                self.usesMutableContractRouting(for: nextContract))
        if agentChanged {
            self.sessions = ChatSessionSidebarModel.clearingForeignGlobalObserverDigest(
                in: self.sessions,
                activeAgentId: self.explicitSessionAgentID ??
                    OpenClawChatSessionKey.agentID(from: self.sessionKey) ?? nextAgentId)
        }
        self.activeAgentId = nextAgentId
        self.sessionRoutingContract = nextContract
        let bootstrapIdentityChanged =
            (agentChanged && self.usesMutableAgentRouting) ||
            contractRoutingChanged
        guard bootstrapIdentityChanged else {
            if contractChanged, self.healthOK {
                reconcilePendingOutboxBranchScopes()
            }
            return
        }
        // Restart when this key depends on a changed routing value so cleared
        // state cannot remain stuck or cross session owners.
        advanceSessionGeneration()
        clearSessionOwnedState()
        startBootstrap()
    }

    public func selectModel(_ selectionID: String) {
        guard self.composerModelMutationAvailable,
              self.canSelectModel(selectionID),
              let request = reserveModelSelection(selectionID)
        else { return }
        enqueueSessionSettingsPatch(requestID: request.id, target: request.target) { [weak self] routeLease in
            guard let self else { return }
            await self.performSelectModel(request, routeLease: routeLease)
        }
    }

    var resolvedMainSessionKey: String {
        if let agentID = self.explicitSessionAgentID ?? OpenClawChatSessionKey.agentID(from: self.sessionKey) {
            return self.mainSessionKey(forAgent: agentID)
        }
        let trimmed = self.sessionDefaults?.mainSessionKey?
            .trimmingCharacters(in: .whitespacesAndNewlines)
        return (trimmed?.isEmpty == false ? trimmed : nil) ?? "main"
    }

    private var usesMutableAgentRouting: Bool {
        self.explicitSessionAgentID == nil && OpenClawChatSessionKey.agentID(from: self.sessionKey) == nil
    }

    private func usesMutableContractRouting(for contract: String?) -> Bool {
        self.usesMutableContractRouting(sessionKey: self.sessionKey, contract: contract)
    }

    public var showsModelPicker: Bool {
        !self.modelChoices.isEmpty
    }

    public var defaultModelLabel: String {
        guard let defaultModelID = normalizedModelSelectionID(sessionDefaults?.model) else {
            return "Default"
        }
        return "Default: \(modelLabel(for: defaultModelID))"
    }
}

extension OpenClawChatViewModel {
    // MARK: - Internals

    func markTimelineChanged() {
        self.timelineRevision &+= 1
    }

    func appendMessage(_ message: OpenClawChatMessage) {
        self.messages.append(message)
        self.markTimelineChanged()
    }

    func removeMessage(id: UUID) {
        let previousCount = self.messages.count
        self.messages.removeAll { $0.id == id }
        if self.messages.count != previousCount {
            self.markTimelineChanged()
        }
    }

    func updateStreamingAssistantText(_ text: String?) {
        guard self.streamingAssistantText != text else { return }
        self.streamingAssistantText = text
        self.markTimelineChanged()
    }

    func logDiagnostic(_ message: String) {
        self.diagnosticsLog?(message)
    }

    func currentSessionSnapshot() -> SessionSnapshot {
        SessionSnapshot(
            key: self.sessionKey,
            generation: self.sessionGeneration,
            agentID: self.activeAgentId,
            deliveryAgentID: self.explicitSessionAgentID ??
                OpenClawChatSessionKey.agentID(from: self.sessionKey) ?? self.activeAgentId,
            sessionRoutingContract: self.sessionRoutingContract)
    }

    func isCurrentSession(_ snapshot: SessionSnapshot) -> Bool {
        let contractSensitive = self.usesMutableContractRouting(for: snapshot.sessionRoutingContract) ||
            self.usesMutableContractRouting(for: self.sessionRoutingContract)
        return !self.isTransportDetached && self.sessionKey == snapshot.key &&
            self.sessionGeneration == snapshot.generation &&
            (!self.usesMutableAgentRouting || self.activeAgentId == snapshot.agentID) &&
            (!contractSensitive || self.sessionRoutingContract == snapshot.sessionRoutingContract)
    }

    func beginSessionBranchSwitchActivity(for session: SessionSnapshot) -> SessionBranchSwitchActivity {
        self.nextSessionBranchSwitchGeneration &+= 1
        let activity = SessionBranchSwitchActivity(
            session: session,
            generation: self.nextSessionBranchSwitchGeneration)
        self.sessionBranchSwitchActivity = activity
        return activity
    }

    func isCurrentSessionBranchSwitchActivity(_ activity: SessionBranchSwitchActivity) -> Bool {
        self.sessionBranchSwitchActivity == activity && self.isCurrentSession(activity.session)
    }

    func endSessionBranchSwitchActivity(_ activity: SessionBranchSwitchActivity) {
        guard self.isCurrentSessionBranchSwitchActivity(activity) else { return }
        self.sessionBranchSwitchActivity = nil
        self.flushOutboxIfNeeded()
    }

    func reconcileSessionBranchChange(
        _ activity: SessionBranchSwitchActivity,
        confirmedLeafEntryID: String? = nil,
        confirmFromBranchRefresh: Bool = false) async
    {
        var stateApplied = true
        if let confirmedLeafEntryID {
            stateApplied = await self.confirmOutboxBranchChange(
                activity.session,
                activeLeafEntryID: confirmedLeafEntryID)
            if !stateApplied {
                await self.recoverOutboxAfterSessionMutationRefreshFailure(
                    activity.session,
                    branchingUnsupported: false)
            }
        } else if confirmFromBranchRefresh {
            stateApplied = await self.refreshSessionBranches(confirmingBranchChange: true)
        }
        guard self.isCurrentSessionBranchSwitchActivity(activity) else { return }
        if stateApplied {
            for _ in 0..<2 {
                stateApplied = await self.refreshHistoryAfterRun(
                    historyRequest: self.beginHistoryRequest(for: activity.session)).applied
                guard self.isCurrentSessionBranchSwitchActivity(activity) else { return }
                if stateApplied { break }
            }
        }
        if stateApplied, !confirmFromBranchRefresh {
            stateApplied = await self.refreshSessionBranches()
        }
        guard self.isCurrentSessionBranchSwitchActivity(activity) else { return }
        guard stateApplied else {
            // After the server-side branch changes, never keep partially consistent local state.
            // Either install the new state completely or reload the session from scratch.
            self.advanceSessionGeneration()
            self.clearSessionOwnedState()
            self.startBootstrap(paintCachedTranscript: false)
            return
        }
        self.errorText = nil
    }

    private func isCurrentBootstrap(_ context: BootstrapContext) -> Bool {
        self.bootstrapGeneration == context.id && self.isCurrentSession(context.session)
    }

    private func startBootstrap(
        sessionKey requestedSessionKey: String? = nil,
        paintCachedTranscript: Bool = true)
    {
        let sessionKey = requestedSessionKey ?? self.sessionKey
        guard !self.isTransportDetached, sessionKey == self.sessionKey else { return }
        if self.swarmSessionKey != sessionKey {
            self.swarmEnabled = false
            self.resetSwarmProgress()
        }
        self.unreadPatchGuard.activate(key: self.sessionMutationIdentity(for: sessionKey))
        self.bootstrapGeneration &+= 1
        self.bootstrapTask?.cancel()
        self.isLoading = true
        self.errorText = nil
        self.invalidateSessionMetadataReadiness()
        self.invalidateProgressCardTarget()
        self.invalidateOutboxBranchReconciliation()
        self.healthOK = false
        clearPendingRuns(reason: nil)
        self.pendingToolCallsById = [:]
        self.updateStreamingAssistantText(nil)
        self.updateActiveSessionRunWithoutChatSnapshot(false)
        self.sessionId = nil
        let historyRequest = self.beginHistoryRequest(captureLatestUserTurn: requestedSessionKey == nil)
        let context = BootstrapContext(
            id: bootstrapGeneration,
            historyRequest: historyRequest)
        let captureTask = Task { [weak self] in
            await self?.captureOutboxBranchState(for: context.session)
        }
        self.bootstrapOutboxBranchStateCapture = (
            generation: context.id,
            session: context.session,
            task: captureTask)
        self.pauseOutboxBranchScope(context.session)
        if paintCachedTranscript {
            paintFromCacheIfNeeded(session: context.session)
        }
        restoreOutboxMessages(session: context.session)
        self.bootstrapTask = Task { [weak self] in
            guard let self else { return }
            await self.bootstrap(context: context)
        }
    }

    private func bootstrap(context: BootstrapContext) async {
        guard self.isCurrentBootstrap(context) else { return }
        defer {
            if self.isCurrentBootstrap(context) {
                self.isLoading = false
            }
        }
        do {
            guard let capture = self.bootstrapOutboxBranchStateCapture,
                  capture.generation == context.id
            else { return }
            let preBootstrapBranchState = await capture.task.value
            guard self.isCurrentBootstrap(context) else { return }
            async let branchRefresh = self.refreshSessionBranches(
                for: context.session,
                preBootstrapBranchState: preBootstrapBranchState)

            await self.syncActiveSessionSubscription(startingWith: context.session.key)
            guard self.isCurrentBootstrap(context) else { return }

            Task { [weak self] in await self?.refreshQuestions() }
            Task { [weak self] in await self?.refreshSwarmCapability(sessionSnapshot: context.session) }
            Task { [weak self] in await self?.refreshSubagentActivities(sessionSnapshot: context.session) }

            let payload = try await transport.requestHistory(sessionKey: context.session.key)
            guard self.isCurrentBootstrap(context) else { return }
            _ = self.applyHistoryPayload(
                payload,
                for: context.historyRequest,
                preservingOptimisticLocalMessages: false,
                syncThinkingOptions: true)
            _ = await branchRefresh
            guard self.isCurrentBootstrap(context) else { return }
            await pollHealthIfNeeded(
                force: true,
                sessionSnapshot: context.session,
                refreshSessionsOnReconnect: false)
            guard self.isCurrentBootstrap(context) else { return }
            // A sidebar-selected row can sit outside the bootstrap's 50-row refresh.
            // Retain its unread metadata until activation acknowledgement finishes.
            let activationEntry = self.currentSessionEntry()
            await self.fetchSessions(limit: 50, sessionSnapshot: context.session)
            guard self.isCurrentBootstrap(context) else { return }
            await self.markCurrentSessionReadAfterActivation(
                context.session,
                fallbackEntry: activationEntry)
            guard self.isCurrentBootstrap(context) else { return }
            await self.fetchModels(sessionSnapshot: context.session)
            guard self.isCurrentBootstrap(context) else { return }
            // An optional progress fetch may already have reported a required Gateway update.
            if self.errorText != OpenClawChatTransportUpgradeMessage.progressCardAgentScope {
                self.errorText = nil
            }
        } catch {
            guard self.isCurrentBootstrap(context) else { return }
            self.errorText = error.localizedDescription
            chatUILogger.error("bootstrap failed \(error.localizedDescription, privacy: .public)")
        }
    }

    private func syncActiveSessionSubscription(startingWith sessionKey: String) async {
        guard sessionKey == self.sessionKey else { return }
        var target = self.currentSessionSnapshot()
        var transport = self.transport
        while true {
            do {
                // Subscribe requests are gateway side effects. If a stale request finishes
                // after a newer switch, immediately reassert the latest visible session.
                try await transport.setActiveSessionKey(target.key)
            } catch {
                // Best-effort; retry only when navigation chose a different target.
            }
            let current = self.currentSessionSnapshot()
            guard current.key != target.key || current.deliveryAgentID != target.deliveryAgentID else { return }
            target = current
            transport = self.transport
        }
    }

    private func refreshRunStateAfterForeground() async {
        let context = self.beginHistoryRequest()
        self.logDiagnostic(
            "chat.ui foreground refresh sessionKey=\(context.session.key) "
                + "pending=\(self.pendingRunCount)")
        let refresh = await refreshHistoryAfterRun(historyRequest: context)
        guard self.isCurrentSession(context.session) else { return }
        if refresh.applied,
           refresh.runSnapshotApplied,
           context.runOwnershipGeneration == self.runOwnershipGeneration,
           !self.isSending,
           refresh.supportsInFlightRunState,
           !refresh.hasInFlightRun
        {
            if refresh.sessionHasActiveRun,
               Self.hasUnansweredLatestUser(in: self.messages)
            {
                self.pendingToolCallsById = [:]
                self.updateStreamingAssistantText(nil)
                // Keep a known run ID authoritative so its stream and terminal
                // events still route here. Synthesize activity only after the
                // client has no run identity to preserve.
                self.updateActiveSessionRunWithoutChatSnapshot(self.pendingRuns.isEmpty)
            } else {
                self.updateActiveSessionRunWithoutChatSnapshot(false)
                clearPendingRuns(
                    reason: nil,
                    hapticEvent: assistantHapticEventAfterLatestUser())
                self.pendingToolCallsById = [:]
                self.updateStreamingAssistantText(nil)
            }
        }
        await pollHealthIfNeeded(force: true, sessionSnapshot: context.session)
    }

    private func performAbort() async {
        guard !self.pendingRuns.isEmpty else { return }
        guard !self.isAborting else { return }
        self.isAborting = true
        defer { self.isAborting = false }

        let runIds = Array(pendingRuns)
        let sessionKey = self.sessionKey
        let transport = self.transport
        for runId in runIds {
            do {
                try await transport.abortRun(sessionKey: sessionKey, runId: runId)
            } catch {
                // Best-effort.
            }
        }
    }

    func fetchSessions(limit: Int?, sessionSnapshot: SessionSnapshot? = nil) async {
        self.nextSessionsFetchRequestID &+= 1
        let sessionsFetchRequestID = self.nextSessionsFetchRequestID
        let session = sessionSnapshot ?? self.currentSessionSnapshot()
        let target = modelPatchTarget(
            sessionKey: session.key,
            canonicalSessionKey: self.isCurrentSession(session) ? currentSessionEntry()?.key : nil,
            agentID: session.deliveryAgentID,
            sessionRoutingContract: session.sessionRoutingContract)
        var overlappingSuccessfulSettingsPatchRequestID: UInt64?
        // Request IDs start at one, so zero represents no earlier success.
        var pendingSettingsPatchOverlapBaseline: UInt64?
        while true {
            await self.waitForPendingSessionSettings(for: target)
            if let pendingBaseline = pendingSettingsPatchOverlapBaseline {
                let completedRequestID = self.lastSuccessfulSettingsPatchRequestIDsByTarget[target] ?? 0
                if completedRequestID != pendingBaseline {
                    overlappingSuccessfulSettingsPatchRequestID = completedRequestID
                }
                pendingSettingsPatchOverlapBaseline = nil
            }
            if let sessionSnapshot, !self.isCurrentSession(sessionSnapshot) {
                return
            }
            let metadataGeneration = self.sessionMetadataGeneration
            let settingsPatchRevision = self.settingsPatchRevisionsByTarget[target, default: 0]
            let successfulSettingsPatchRequestID = self.lastSuccessfulSettingsPatchRequestIDsByTarget[target]
            let res: OpenClawChatSessionsListResponse
            do {
                res = try await self.transport.listSessions(
                    limit: limit, search: nil, archived: false, agentID: session.deliveryAgentID)
            } catch {
                if self.outbox != nil, self.healthOK, !self.hasCurrentSessionMetadata {
                    applyTransportHealth(false)
                }
                return
            }
            if let sessionSnapshot, !self.isCurrentSession(sessionSnapshot) {
                return
            }
            guard sessionsFetchRequestID > self.latestAppliedSessionsFetchRequestID else { return }
            // A list that straddles a patch or reconnect is stale. Retry in this
            // owner so bootstrap cannot discard its only authoritative refresh.
            guard metadataGeneration == self.sessionMetadataGeneration else {
                overlappingSuccessfulSettingsPatchRequestID = nil
                pendingSettingsPatchOverlapBaseline = nil
                continue
            }
            guard settingsPatchRevision == self.settingsPatchRevisionsByTarget[target, default: 0],
                  self.inFlightSettingsPatchCountsByTarget[target] == nil
            else {
                let completedRequestID = self.lastSuccessfulSettingsPatchRequestIDsByTarget[target]
                if let completedRequestID,
                   completedRequestID != successfulSettingsPatchRequestID
                {
                    overlappingSuccessfulSettingsPatchRequestID = completedRequestID
                }
                if self.inFlightSettingsPatchCountsByTarget[target] != nil {
                    pendingSettingsPatchOverlapBaseline = completedRequestID ?? 0
                }
                continue
            }
            self.latestAppliedSessionsFetchRequestID = sessionsFetchRequestID
            let organized = OpenClawChatSessionListOrganizer.organize(res.sessions)
            for session in organized {
                self.unreadPatchGuard.observe(
                    key: self.sessionMutationIdentity(
                        for: session.key,
                        listedKey: session.key,
                        agentID: session.agentId),
                    unread: session.unread)
            }
            self.sessions = self.applyingLocalUnreadOverrides(to: organized)
            self.sessionDefaults = res.defaults
            self.restoreOverlappingSettingsPatch(
                requestID: overlappingSuccessfulSettingsPatchRequestID,
                target: target)
            self.hasAppliedLiveSessions = true
            self.syncSelectedModel()
            syncThinkingLevelOptions()
            persistSessionsToCache(organized, agentID: session.deliveryAgentID)
            self.readySessionMetadataGeneration = metadataGeneration
            if self.healthOK {
                reconcilePendingOutboxBranchScopes()
            }
            return
        }
    }

    private func restoreOverlappingSettingsPatch(requestID: UInt64?, target: ModelPatchTarget) {
        guard let requestID,
              self.lastSuccessfulSettingsPatchRequestIDsByTarget[target] == requestID
        else { return }

        // A post-patch list retry may still carry the pre-patch row. Preserve
        // only the route whose patch overlapped this fetch.
        let patchResult = self.lastSuccessfulSettingsPatchResultsByTarget[target]
        let resultKey = patchResult?.key ?? target.canonicalSessionKey
        if let selectionID = self.lastSuccessfulModelSelectionIDsByTarget[target] {
            self.applySuccessfulModelSelection(
                selectionID,
                target: target,
                sessionEntryKey: resultKey,
                syncSelection: false,
                patchResult: patchResult)
        } else if let thinkingLevel = patchResult?.thinkingLevel,
                  self.lastSuccessfulThinkingOverrideClearedByTarget[target] != true
        {
            self.updateCurrentSessionThinkingLevel(thinkingLevel, sessionKey: resultKey)
        }
        if self.lastSuccessfulThinkingOverrideClearedByTarget[target] == true {
            self.updateCurrentSessionThinkingLevel(nil, sessionKey: resultKey)
        }
        if let patchResult {
            self.applyModelControlPatchResult(
                patchResult,
                sessionKey: resultKey,
                fastOverrideCleared: self.lastSuccessfulFastOverrideClearedByTarget[target] == true,
                verboseOverrideCleared: self.lastSuccessfulVerboseOverrideClearedByTarget[target] == true)
        }
    }

    func invalidateSessionMetadataReadiness() {
        self.sessionMetadataGeneration &+= 1
        self.readySessionMetadataGeneration = nil
    }

    var hasCurrentSessionMetadata: Bool {
        self.readySessionMetadataGeneration == self.sessionMetadataGeneration
    }

    private func applySessionSwitch(
        to sessionKey: String,
        intent: SessionSwitchIntent,
        agentID: String? = nil)
    {
        let next = sessionKey.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !next.isEmpty else { return }
        let encodedAgentID = OpenClawChatSessionKey.agentID(from: next)?.lowercased()
        let requestedAgentID = agentID?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
        let nextAgentID = encodedAgentID == nil && requestedAgentID?.isEmpty == false ? requestedAgentID : nil
        if let encodedAgentID, let requestedAgentID, encodedAgentID != requestedAgentID {
            self.errorText = "The selected conversation belongs to another agent. Refresh and try again."
            return
        }
        guard next != self.sessionKey || nextAgentID != self.explicitSessionAgentID else {
            if intent == .externalSync {
                self.deferredExternalSessionKey = nil
            }
            return
        }
        let scopedTransport = nextAgentID.flatMap { self.defaultTransport.scoped(toAgentID: $0) }
        if nextAgentID != nil, scopedTransport == nil {
            self.errorText = "This connection cannot open that agent's conversation. Reconnect and try again."
            return
        }
        if blocksAttachmentOwnerChange {
            switch intent {
            case .externalSync:
                self.deferredExternalSessionKey = next
            case .userInitiated:
                self.errorText = String(
                    localized: "Remove attachments or wait for delivery to resolve before switching chats.")
            }
            return
        }
        self.deferredExternalSessionKey = nil
        self.prepareComposerForSessionSwitch(to: next, agentID: nextAgentID)
        self.advanceSessionGeneration()
        self.clearSessionOwnedState()
        if self.currentSessionSnapshot().deliveryAgentID != (nextAgentID ?? encodedAgentID ?? self.activeAgentId) {
            self.sessions = []
            self.hasAppliedLiveSessions = false
            self.swarmEnabled = false
            self.resetSwarmProgress()
        }
        self.explicitSessionAgentID = nextAgentID
        self.scopedSessionTransport = scopedTransport
        self.sessionKey = next
        self.restoreComposerAfterSessionSwitch()
        if intent == .userInitiated {
            self.onSessionChanged?(next)
        }
        self.startBootstrap(sessionKey: next)
    }

    func applyDeferredExternalStateIfReady() {
        guard !blocksAttachmentOwnerChange else { return }
        if let identity = deferredDeliveryIdentity {
            self.deferredDeliveryIdentity = nil
            self.syncDeliveryIdentity(
                activeAgentId: identity.activeAgentID,
                sessionRoutingContract: identity.sessionRoutingContract)
        }
        guard let sessionKey = deferredExternalSessionKey else { return }
        self.deferredExternalSessionKey = nil
        self.applySessionSwitch(to: sessionKey, intent: .externalSync)
    }

    /// Adopts a freshly created session key: full composer-preserving switch plus
    /// session-owned state reset. Module-internal so the session-actions extension
    /// does not need access to the private switch members.
    func adoptCreatedSession(_ next: String) {
        self.prepareComposerForSessionSwitch(to: next)
        self.advanceSessionGeneration()
        self.clearSessionOwnedState()
        self.explicitSessionAgentID = nil
        self.scopedSessionTransport = nil
        self.sessionKey = next
        self.restoreComposerAfterSessionSwitch()
        self.onSessionChanged?(next)
        self.errorText = nil
        self.startBootstrap()
    }

    /// Clears state owned by the current session/agent before a new identity can consume events.
    func clearSessionOwnedState() {
        self.invalidateComposerCapabilities()
        self.modelSelectionID = Self.defaultModelSelectionID
        self.modelAvailabilityIsSessionScoped = false
        self.modelChoices = []
        self.modelCatalogMessage = nil
        replaceMessages([])
        self.isShowingCachedTranscript = false
        self.hasAppliedLiveHistory = false
        self.pendingLocalUserEchoMessageIDsByRunID.removeAll()
        self.runMessageScopesByRunID.removeAll()
        self.provisionalFinalMessagesByID.removeAll()
        resetOutboxPresentationForSessionSwitch()
        self.sessionId = nil
        self.pendingToolCallsById = [:]
        self.clearSubagentActivities()
        self.updateStreamingAssistantText(nil)
        self.clearProgressCard()
        self.updateActiveSessionRunWithoutChatSnapshot(false)
        self.activeSessionRunIDs = []
        self.liveRunStateByRunID.removeAll()
        resetSlashCommandCatalog()
        self.sessionBranches = []
        self.isLoadingSessionBranches = false
        self.sessionBranchSwitchActivity = nil
        clearPendingRuns(reason: nil)
    }

    func performReset() async {
        let session = self.currentSessionSnapshot()
        self.isLoading = true
        self.errorText = nil

        do {
            try await self.transport.resetSession(sessionKey: session.key)
        } catch {
            guard self.isCurrentSession(session) else { return }
            self.isLoading = false
            self.errorText = error.localizedDescription
            chatUILogger.error("session reset failed \(error.localizedDescription, privacy: .public)")
            return
        }

        guard self.isCurrentSession(session) else { return }
        self.replyTarget = nil
        self.runMessageScopesByRunID.removeAll()
        self.provisionalFinalMessagesByID.removeAll()
        self.startBootstrap()
    }

    func performCompact() async {
        guard !self.isCompacting else { return }
        guard !self.isSending, !hasBlockingRunActivity, !self.isAborting else {
            self.errorText = "Wait for the current response before compacting the thread."
            return
        }
        if let lastCompactAt,
           Date().timeIntervalSince(lastCompactAt) < compactCooldown
        {
            self.errorText = "Please wait before compacting this thread again."
            return
        }

        self.isCompacting = true
        self.isLoading = true
        self.errorText = nil
        defer {
            self.isCompacting = false
        }

        do {
            try await self.transport.compactSession(sessionKey: self.sessionKey)
        } catch {
            self.isLoading = false
            self.errorText = "Unable to compact the thread. Please try again."
            let nsError = error as NSError
            chatUILogger.error(
                "compact failed domain=\(nsError.domain, privacy: .public) code=\(nsError.code, privacy: .public)")
            chatUILogger.error("compact details=\(String(describing: error), privacy: .private)")
            return
        }

        lastCompactAt = Date()
        self.startBootstrap()
    }

    private func reserveModelSelection(_ selectionID: String) -> ModelSelectionRequest? {
        let next = self.normalizedSelectionID(selectionID)
        guard next != self.modelSelectionID else { return nil }

        let session = self.currentSessionSnapshot()
        let sessionEntryKey = currentSessionEntry()?.key
        let target = modelPatchTarget(
            sessionKey: session.key,
            canonicalSessionKey: sessionEntryKey,
            agentID: session.deliveryAgentID,
            sessionRoutingContract: session.sessionRoutingContract)
        let previous = self.modelSelectionID
        let rollbackSelectionID = self.lastSuccessfulModelSelectionIDsByTarget[target] ?? previous
        let previousRequestID = self.latestModelSelectionRequestIDsByTarget[target]
        let requestID = self.reserveSessionSettingsRequest(for: target)
        let nextModelRef = self.modelRef(forSelectionID: next)
        self.latestModelSelectionRequestIDsByTarget[target] = requestID
        self.modelSelectionID = next
        syncThinkingLevelOptions()
        self.errorText = nil
        return ModelSelectionRequest(
            id: requestID,
            target: target,
            session: session,
            sessionEntryKey: sessionEntryKey,
            rollbackSelectionID: rollbackSelectionID,
            previousRequestID: previousRequestID,
            selectionID: next,
            modelRef: nextModelRef)
    }

    private func performSelectModel(
        _ request: ModelSelectionRequest,
        routeLease: OpenClawChatSessionSettingsRouteLease?) async
    {
        do {
            guard let routeLease else { throw OpenClawChatTransportSendError.notDispatched }
            let patchResult = try await routeLease.patchSessionSettings(
                sessionKey: request.target.canonicalSessionKey,
                agentID: request.target.agentID,
                patch: OpenClawChatSessionSettingsPatch(model: .some(request.modelRef)))
            self.lastSuccessfulSettingsPatchRequestIDsByTarget[request.target] = request.id
            guard request.id == self.latestModelSelectionRequestIDsByTarget[request.target] else {
                // Keep older successful patches as rollback state, but do not replay
                // stale UI/session state over a newer queued or completed selection.
                self.recordSuccessfulModelPatch(
                    selectionID: request.selectionID,
                    patchResult: patchResult,
                    target: request.target)
                return
            }
            self.applySuccessfulModelSelection(
                request.selectionID,
                target: request.target,
                sessionEntryKey: patchResult?.key ?? request.sessionEntryKey,
                syncSelection: self.isCurrentSession(request.session),
                patchResult: patchResult)
            self.modelPickerStore.recordRecent(request.selectionID)
            self.modelPickerRecents = self.modelPickerStore.recents
        } catch {
            guard request.id == self.latestModelSelectionRequestIDsByTarget[request.target] else { return }
            let rollbackSelectionID = self.lastSuccessfulModelSelectionIDsByTarget[request.target]
                ?? request.rollbackSelectionID
            if let previousRequestID = request.previousRequestID {
                self.latestModelSelectionRequestIDsByTarget[request.target] = previousRequestID
            } else {
                self.latestModelSelectionRequestIDsByTarget.removeValue(forKey: request.target)
            }
            if self.lastSuccessfulModelSelectionIDsByTarget[request.target] == rollbackSelectionID {
                self.applySuccessfulModelSelection(
                    rollbackSelectionID,
                    target: request.target,
                    sessionEntryKey: request.sessionEntryKey,
                    syncSelection: self.isCurrentSession(request.session),
                    patchResult: self.lastSuccessfulSettingsPatchResultsByTarget[request.target])
            }
            guard self.isCurrentSession(request.session) else { return }
            self.modelSelectionID = rollbackSelectionID
            syncThinkingLevelOptions()
            self.errorText = error.localizedDescription
            chatUILogger.error("sessions.patch(model) failed \(error.localizedDescription, privacy: .public)")
        }
    }

    private func finishSettingsPatchTail(requestID: UInt64, target: ModelPatchTarget) {
        guard self.settingsPatchTailsByTarget[target]?.requestID == requestID else { return }
        self.settingsPatchTailsByTarget.removeValue(forKey: target)
    }

    func reserveSessionSettingsRequest(for target: ModelPatchTarget) -> UInt64 {
        self.nextSessionSettingsRequestID &+= 1
        self.beginSettingsPatch(for: target)
        return self.nextSessionSettingsRequestID
    }

    func enqueueSessionSettingsPatch(
        requestID: UInt64,
        target: ModelPatchTarget,
        operation: @escaping @MainActor (OpenClawChatSessionSettingsRouteLease?) async -> Void)
    {
        let previousPatchTail = self.settingsPatchTailsByTarget[target]
        let previousTail = previousPatchTail?.task
        let previousRouteLeaseTask = previousPatchTail?.routeLeaseTask
        // Task scheduling is not FIFO. Chain lease capture separately so a
        // reconnect cannot give an older mutation a newer route than its successor.
        let routeLeaseTask = Task { [weak self] in
            _ = await previousRouteLeaseTask?.value
            return await self?.transport.acquireSessionSettingsRouteLease()
        }
        let task = Task { [weak self] in
            let routeLease = await routeLeaseTask.value
            await previousTail?.value
            guard let self else { return }
            await operation(routeLease)
            self.endSettingsPatch(for: target)
            self.finishSettingsPatchTail(requestID: requestID, target: target)
        }
        self.settingsPatchTailsByTarget[target] = SettingsPatchTail(
            requestID: requestID,
            routeLeaseTask: routeLeaseTask,
            task: task)
    }

    private func beginSettingsPatch(for target: ModelPatchTarget) {
        self.settingsPatchRevisionsByTarget[target, default: 0] &+= 1
        self.inFlightSettingsPatchCountsByTarget[target, default: 0] += 1
    }

    private func endSettingsPatch(for target: ModelPatchTarget) {
        self.settingsPatchRevisionsByTarget[target, default: 0] &+= 1
        let remaining = max(0, (inFlightSettingsPatchCountsByTarget[target] ?? 0) - 1)
        if remaining == 0 {
            self.inFlightSettingsPatchCountsByTarget.removeValue(forKey: target)
            // Rollback baselines belong to one contiguous settings lane. Once
            // drained, the next authoritative session snapshot owns state.
            self.acceptedSettingsPatchResultsByTarget.removeValue(forKey: target)
            self.acceptedThinkingLevelsByTarget.removeValue(forKey: target)
            self.acceptedPreferredThinkingLevelsByTarget.removeValue(forKey: target)
            self.acceptedExplicitThinkingPreferencesByTarget.removeValue(forKey: target)
            self.acceptedThinkingOverrideClearedByTarget.removeValue(forKey: target)
            self.acceptedVerboseLevelsByTarget.removeValue(forKey: target)
            self.acceptedFastModesByTarget.removeValue(forKey: target)
            self.latestThinkingSelectionRequestIDsByTarget.removeValue(forKey: target)
            let waiters = self.settingsPatchWaitersByTarget.removeValue(forKey: target) ?? []
            for waiter in waiters {
                waiter.resume()
            }
            return
        }
        self.inFlightSettingsPatchCountsByTarget[target] = remaining
    }

    func sessionSettingsPatchTarget(
        in sessionKey: String,
        canonicalSessionKey: String?,
        agentID: String?,
        sessionRoutingContract: String?) -> ModelPatchTarget
    {
        if canonicalSessionKey == nil,
           agentID == nil,
           sessionRoutingContract == nil,
           sessionKey == self.sessionKey
        {
            let session = self.currentSessionSnapshot()
            return modelPatchTarget(
                sessionKey: session.key,
                canonicalSessionKey: currentSessionEntry()?.key,
                agentID: session.deliveryAgentID,
                sessionRoutingContract: session.sessionRoutingContract)
        }
        return modelPatchTarget(
            sessionKey: sessionKey,
            canonicalSessionKey: canonicalSessionKey,
            agentID: agentID,
            sessionRoutingContract: sessionRoutingContract)
    }

    func waitForPendingSessionSettings(for target: ModelPatchTarget) async {
        guard (self.inFlightSettingsPatchCountsByTarget[target] ?? 0) > 0 else { return }
        await withCheckedContinuation { continuation in
            self.settingsPatchWaitersByTarget[target, default: []].append(continuation)
        }
    }

    func syncSelectedModel() {
        let currentSession = currentSessionEntry()
        let target = currentModelPatchTarget()
        let explicitModelID = self.normalizedModelSelectionID(
            currentSession?.model,
            provider: currentSession?.modelProvider)
        let defaultModelID = self.normalizedModelSelectionID(
            self.sessionDefaults?.model,
            provider: self.sessionDefaults?.modelProvider)
        if self.lastSuccessfulModelSelectionIDsByTarget[target] == Self.defaultModelSelectionID,
           explicitModelID == defaultModelID
        {
            self.modelSelectionID = Self.defaultModelSelectionID
            return
        }
        if let explicitModelID {
            self.lastSuccessfulModelSelectionIDsByTarget[target] = explicitModelID
            self.modelSelectionID = explicitModelID
            return
        }
        self.lastSuccessfulModelSelectionIDsByTarget[target] = Self.defaultModelSelectionID
        self.modelSelectionID = Self.defaultModelSelectionID
    }

    private func normalizedSelectionID(_ selectionID: String) -> String {
        let trimmed = selectionID.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmed.isEmpty else { return Self.defaultModelSelectionID }
        return trimmed
    }

    private func normalizedModelSelectionID(_ modelID: String?, provider: String? = nil) -> String? {
        guard let modelID else { return nil }
        let trimmed = modelID.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmed.isEmpty else { return nil }
        if let provider = Self.normalizedProvider(provider) {
            let providerQualified = Self.providerQualifiedModelSelectionID(modelID: trimmed, provider: provider)
            if let match = modelChoices.first(where: {
                $0.selectionID == providerQualified ||
                    ($0.modelID == trimmed && Self.normalizedProvider($0.provider) == provider)
            }) {
                return match.selectionID
            }
            return providerQualified
        }
        if self.modelChoices.contains(where: { $0.selectionID == trimmed }) {
            return trimmed
        }
        let matches = self.modelChoices.filter { $0.modelID == trimmed || $0.selectionID == trimmed }
        if matches.count == 1 {
            return matches[0].selectionID
        }
        return trimmed
    }

    private func modelRef(forSelectionID selectionID: String) -> String? {
        let normalized = self.normalizedSelectionID(selectionID)
        if normalized == Self.defaultModelSelectionID {
            return nil
        }
        return normalized
    }

    private func modelLabel(for modelID: String) -> String {
        self.modelChoices.first(where: { $0.selectionID == modelID || $0.modelID == modelID })?.displayLabel ??
            modelID
    }

    private func applySuccessfulModelSelection(
        _ selectionID: String,
        target: ModelPatchTarget,
        sessionEntryKey: String?,
        syncSelection: Bool,
        patchResult: OpenClawChatModelPatchResult? = nil)
    {
        self.recordSuccessfulModelPatch(
            selectionID: selectionID,
            patchResult: patchResult,
            target: target)
        if target.canonicalSessionKey.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() == "global",
           let targetAgentID = target.agentID,
           targetAgentID != activeAgentId
        {
            return
        }
        let resolved: (modelID: String?, modelProvider: String?) = if selectionID == Self.defaultModelSelectionID {
            (modelID: nil, modelProvider: nil)
        } else if let model = patchResult?.model {
            (modelID: model, modelProvider: patchResult?.modelProvider)
        } else {
            self.resolvedSessionModelIdentity(forSelectionID: selectionID)
        }
        let modelStateKey = sessionEntryKey ?? target.canonicalSessionKey
        updateCurrentSessionModel(
            modelID: resolved.modelID,
            modelProvider: resolved.modelProvider,
            sessionKey: modelStateKey,
            syncSelection: syncSelection)
        if let thinkingLevels = patchResult?.thinkingLevels {
            updateCurrentSessionThinkingLevels(thinkingLevels, sessionKey: modelStateKey)
        }
        if syncSelection,
           !self.prefersExplicitThinkingLevel,
           Self.normalizedThinkingLevel(self.preferredThinkingLevel) != "ultra",
           let thinkingLevel = Self.normalizedThinkingLevel(patchResult?.thinkingLevel)
        {
            self.preferredThinkingLevel = thinkingLevel
        }
        if let thinkingLevel = Self.normalizedThinkingLevel(patchResult?.thinkingLevel) {
            updateCurrentSessionThinkingLevel(thinkingLevel, sessionKey: modelStateKey)
        }
        if syncSelection {
            syncThinkingLevelOptions()
        }
    }

    private func recordSuccessfulModelPatch(
        selectionID: String,
        patchResult: OpenClawChatModelPatchResult?,
        target: ModelPatchTarget)
    {
        self.lastSuccessfulModelSelectionIDsByTarget[target] = selectionID
        self.lastSuccessfulSettingsPatchResultsByTarget[target] = patchResult
        if let thinkingLevel = Self.normalizedThinkingLevel(patchResult?.thinkingLevel) {
            self.acceptedThinkingLevelsByTarget[target] = thinkingLevel
            if self.acceptedExplicitThinkingPreferencesByTarget[target] == false {
                self.acceptedPreferredThinkingLevelsByTarget[target] = thinkingLevel
                self.recordAuthoritativeInheritedThinkingPreference(thinkingLevel)
            }
        }
        if let patchResult {
            let previous = self.acceptedSettingsPatchResultsByTarget[target]
            self.acceptedSettingsPatchResultsByTarget[target] = OpenClawChatModelPatchResult(
                key: patchResult.key ?? previous?.key,
                modelProvider: patchResult.modelProvider ?? previous?.modelProvider,
                model: patchResult.model ?? previous?.model,
                thinkingLevel: patchResult.thinkingLevel ?? previous?.thinkingLevel,
                thinkingLevels: patchResult.thinkingLevels ?? previous?.thinkingLevels,
                fastMode: patchResult.fastMode ?? previous?.fastMode,
                effectiveFastMode: patchResult.effectiveFastMode ?? previous?.effectiveFastMode,
                verboseLevel: patchResult.verboseLevel ?? previous?.verboseLevel)
        }
        self.completedModelPatchTargets.insert(target)
    }

    private func resolvedSessionModelIdentity(forSelectionID selectionID: String)
        -> (modelID: String?, modelProvider: String?)
    {
        guard let modelRef = modelRef(forSelectionID: selectionID) else {
            return (nil, nil)
        }
        if let choice = modelChoices.first(where: { $0.selectionID == modelRef }) {
            return (choice.modelID, Self.normalizedProvider(choice.provider))
        }
        return (modelRef, nil)
    }
}