Spaces:
Paused

File size: 88,234 Bytes
bc9f3e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

chat.py β€” Chat-turn handlers for the General Chat, RAG Chat, and Vision

Chat tabs, plus the <think>-tag reasoning/answer formatter shared by the

text tabs.

"""

import re
import time
from typing import Optional

from PIL import Image

from ui import i18n
from ui.i18n import LANGUAGES
from backend import knowledge_base as kb
from backend import model_registry as mr
from backend import models
from backend.live_stream import get_bus
from agents import general_agent
from agents import rag_agent
from agents import deep_research_agent
from agents import agent_memory
from agents import agent_streaming
from backend.hardware import DEVICE

# NOTE: agentic memory (agent.memory.steps) lives only in RAM, for as long
# as the cached CodeAgent object for that tab stays alive β€” see
# agent_memory.py's module docstring for why this app deliberately does
# NOT persist it to disk. The "🧠 Conversation Memory" checkbox is marked
# experimental in the UI for the same reason: it resets on a model
# switch, "Clear", or an app restart, and β€” especially with small/local
# models β€” can occasionally produce a confused reply if a step written by
# one model gets replayed against a different one after a mid-conversation
# model switch.

# How many prior user+assistant exchanges to feed back into the *direct*
# (non-agentic) chat paths as short-term conversation memory. Agentic
# paths don't use this β€” they get real memory from smolagents' own
# agent.memory (see general_agent.py / rag_agent.py / agent_memory.py).
#
# This is now the FALLBACK ceiling, used only when the token budget can't
# be determined (see _recent_memory_messages()): when the '🧹 Memory
# Compaction' toggle (Settings) is on and the model's context window is
# known, the direct paths keep as many of the most recent turns as FIT
# the window's token budget instead of always slicing at this fixed count.
DIRECT_CHAT_MEMORY_TURNS = 6

# How many turns of memory an agentic CodeAgent is allowed to keep before
# older turns get dropped (see agent_memory.cap_agent_memory()).
AGENTIC_MEMORY_TURNS = 6

# Deep Research reports are much longer per turn than a normal chat
# answer (and each turn can also include several delegated sub-agent
# calls), so its memory budget is kept smaller than the other agentic
# tabs' default β€” same reasoning as data_analysis.DATA_AGENT_MEMORY_TURNS.
DEEP_RESEARCH_MEMORY_TURNS = 4


def _agent_mechanism_txt(use_tool_calling: bool) -> str:
    """Footer label for the ACTUAL agent mechanism on every agentic tab:

    'tool calling' when the tab runs the default ToolCallingAgent

    (structured tool calls only β€” no Python execution; see

    general_agent.py's note on PythonInterpreterTool), and 'code' when

    'Use native tool calling' is unchecked and the tab runs a CodeAgent

    (every step writes and executes Python). Shared by the General / RAG /

    Deep Research footers so the label stays consistent across tabs."""
    return "tool calling" if use_tool_calling else "code"


# Shared with the Data Analysis footer too (agents/agent_streaming.py
# owns the single implementation β€” see _agent_steps_budget_txt there).
_agent_steps_budget_txt = agent_streaming._agent_steps_budget_txt


def _compaction_status_msg(lang_key: str = "kh") -> str:
    """One-line bilingual status shown when agentic memory compaction fires

    (see agent_memory.compact_agent_memory())."""
    return ("🧹 αž€αŸ†αž–αž»αž„αž”αž„αŸ’αžšαž½αž˜αž’αž„αŸ’αž‚αž…αž„αž…αžΆαŸ†αžŸαž“αŸ’αž‘αž“αžΆβ€¦" if lang_key == "kh"
            else "🧹 Compacting conversation memory…")


def _agent_failure_hint(lang_key: str = "kh",

                        diagnostics: Optional[dict] = None) -> str:
    """Soft guidance footer appended when an agentic run COMPLETED but the

    model still stumbled on repeated errored steps (see agent_streaming's

    fail-fast guard). `diagnostics` is the run's diagnostics snapshot

    carried on the stream's FINAL yield ({total_steps,

    max_consecutive_errors, aborted}) β€” the stream contract now delivers

    it, so this no longer reads back `get_last_run()` after the loop.

    Returns an empty string for clean runs and for runs the fail-fast

    guard ABORTED (the abort message itself already carries the "try a

    larger model" guidance, so this would just duplicate it)."""
    d = diagnostics or {}
    n = d.get("max_consecutive_errors", 0) or 0
    if d.get("aborted") or n < agent_streaming._STUMBLE_HINT_THRESHOLD:
        return ""
    l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
    hint = l.get("agent_stumble_hint", "")
    if not hint:
        return ""
    return "\n\n" + hint.format(n=n)


def _maybe_compact_agent_memory(agent, model_id: str, lang_key: str,

                                tab_key: str = "gen") -> bool:
    """Run the token-budget-aware rolling compaction on an agentic

    CodeAgent before its next run (see agent_memory.compact_agent_memory()).



    Reads the persisted compaction tuning from model_registry: the global

    budget ratio (Settings > Memory Compaction Threshold), and the

    'keep recent turns' setting for `tab_key` ('gen'/'rag'/'dr'/'data') β€”

    the global override, or the per-tab default (General/RAG = 2,

    Deep Research/Data = 1) while the control is on 'Auto'.



    Returns True if memory was compacted β€” callers show a one-line status

    (see _compaction_status_msg()). No-op when conversation memory is off

    or the '🧹 Memory Compaction' toggle (Settings) is disabled."""
    if agent is None:
        return False
    return agent_memory.compact_agent_memory(
        agent,
        model_id=model_id,
        n_ctx=models._llm_n_ctx or mr.get_saved_context_window(),
        keep_recent_turns=mr.get_saved_memory_keep_recent(tab_key),
        budget_ratio=mr.get_saved_memory_compaction_ratio(),
        lang_key=lang_key,
    )


def _speed_seg(elapsed: float, n_tokens: int) -> str:
    """Token-rate segment for the response footer β€” e.g. 'Β· 40 tok/s'.

    Returns an empty string when token count is 0 (the agentic paths can

    estimate but never guarantee an exact count)."""
    if not n_tokens:
        return ""
    tok_per_sec = n_tokens / elapsed if elapsed else 0
    return f" Β· {tok_per_sec:.1f} tok/s"


# Reusable HTML templates for format_llm_response() β€” extracted to
# module-level constants so the same HTML strings aren't built from scratch
# on every single chat turn (see the three branches in
# format_llm_response() below, which each use some combination of these).
_THINK_TPL = (
    '<details class="think-block" {open}>\n'
    '<summary class="think-summary">\n'
    '<span class="think-badge">{summary}</span>\n'
    '<span class="think-hint">(click to toggle)</span>\n'
    '</summary>\n'
    '<div class="think-body">\n{body}\n</div>\n'
    '</details>\n'
)

_ANSWER_TPL = (
    '<div class="final-answer-block">\n'
    '<div class="answer-header-badge">{title}</div>\n'
    '<div class="answer-body">\n{body}\n</div>\n'
    '</div>'
)


def format_llm_response(text: str, lang_key: str = "kh") -> str:
    if not text or not isinstance(text, str):
        return text or ""

    l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
    reasoning_title = l.get("err_reasoning", "🧠 αžŠαŸ†αžŽαžΎαžšαž€αžΆαžšαž‚αž·αž / Reasoning Process")
    answer_title = l.get("err_answer", "✨ αž…αž˜αŸ’αž›αžΎαž™αž…αž»αž„αž€αŸ’αžšαŸ„αž™ / Final Answer")
    no_reasoning = l.get("no_reasoning_text", "αž‚αŸ’αž˜αžΆαž“αž–αŸαžαŸŒαž˜αžΆαž“αž‚αž·αž")
    truncated_notice = l.get("truncated_notice", "⚠️ αž€αžΆαžšαž‚αž·αžαžαŸ’αžšαžΌαžœαž”αžΆαž“αž€αžΆαžαŸ‹αž•αŸ’αžαžΆαž…αŸ‹ (Truncated)")

    thinking = None
    answer = None

    # 1. Match <think>...</think> or <reasoning>...</reasoning> or <thought>...</thought>
    m_tag = re.search(r"<(think|reasoning|thought)>(.*?)</\1>(.*)", text, re.DOTALL | re.IGNORECASE)
    if m_tag:
        thinking = m_tag.group(2).strip()
        answer = m_tag.group(3).strip()
    else:
        # 1b. Match Gemma 4 channel tags: <|channel>thought\n...<channel|>[answer]
        m_gemma = re.search(r"<\|?channel\|?>thought\s*(.*?)(?:<\|?channel\|?>|\Z)(.*)", text, re.DOTALL | re.IGNORECASE)
        if m_gemma and m_gemma.group(1).strip():
            thinking = m_gemma.group(1).strip()
            answer = m_gemma.group(2).strip()
        else:
            # 2. Match " thinking... response..."
            m_resp = re.search(r" thinking(.*?) response(.*)", text, re.DOTALL)
            if m_resp:
                thinking = m_resp.group(1).strip()
                answer = m_resp.group(2).strip()
            else:
                # 3. Unclosed <think> or " thinking"
                m_unclosed = re.search(r"<(think|reasoning|thought)>(.*)", text, re.DOTALL | re.IGNORECASE)
                if m_unclosed:
                    thinking = m_unclosed.group(2).strip()
                    answer = ""
                elif " thinking" in text and " response" not in text:
                    thinking = text.split(" thinking", 1)[1].strip()
                    answer = ""

    if thinking is not None:
        think_html = _THINK_TPL.format(
            open="",
            summary=reasoning_title,
            body=thinking if thinking else no_reasoning,
        )
        if answer:
            answer = agent_streaming._strip_deliberation_preamble(answer)
            ans_html = _ANSWER_TPL.format(
                title=answer_title,
                body=answer,
            )
            return think_html + ans_html
        else:
            ans_html = _ANSWER_TPL.format(
                title=answer_title,
                body=truncated_notice,
            )
            return think_html + ans_html

    return agent_streaming._strip_deliberation_preamble(text)


def _strip_html_tags(text: str) -> str:
    """Remove HTML tags from text, keeping the inner content.



    The single source of truth for tag-stripping, shared by

    _strip_response_html() (recovering plain text for conversation

    memory) and _export_markdown() (cleaning answers for .docx export) β€”

    one regex, one place. Markdown syntax (**bold**, # headings, | tables |)

    is not HTML and is left untouched.



    The regex only strips TAG-SHAPED markup (`<` followed by a letter or

    `/`), so bare comparison operators and math in answers survive: "x < 5"

    and "a < b > c" are never eaten, while `<div class="…">`, `<table>`,

    `<br>`, `</p>` etc. all still match."""
    return re.sub(r"<[a-zA-Z/][^>]*>", "", text)


def _strip_response_html(text: str) -> str:
    """Recover the plain-text answer from a previously HTML-formatted assistant reply."""
    if not text:
        return text
    text = re.sub(r"<details.*?</details>", "", text, flags=re.DOTALL)
    text = re.sub(r"<div class=\"final-answer-block\".*?<div class=\"answer-body\">(.*?)</div>\s*</div>", r"\1", text, flags=re.DOTALL)
    text = re.sub(r"<hr>.*$", "", text, flags=re.DOTALL)
    text = re.sub(r"<b>\U0001F4AC[^<]*</b>\s*", "", text)
    text = _strip_html_tags(text)
    return text.strip()


def _recent_memory_messages(history: list, max_turns: int = DIRECT_CHAT_MEMORY_TURNS,

                            model_id: Optional[str] = None,

                            provider: Optional[str] = None,

                            n_ctx: Optional[int] = None,

                            model_obj=None, reserve_tokens: int = 0) -> list:
    """Build a clean list of prior {"role", "content"} turns from the

    Gradio chatbot history, to hand to models._call_llm() as short-term

    conversation memory for the *direct* (non-agentic) chat paths.



    Strips HTML formatting from assistant replies (see

    _strip_response_html()) so old markup/timing footers don't

    pollute the prompt.



    Keeps the most recent turns that FIT the model's context-window

    token budget (see agent_memory.trim_messages_to_budget()) instead

    of always slicing at a fixed turn count β€” the direct-chat analog

    of the agentic paths' token-budget compaction. `model_id` /

    `provider` / `n_ctx` identify the model the request will actually

    run on (the same values passed to models._call_llm()); `model_obj`

    is the alternative for paths (like Vision) whose model is resolved

    through a different loader. `reserve_tokens` holds room in the

    budget for prompt content added separately from memory (e.g. RAG

    retrieved context). When the budget can't be determined β€”

    remote backend, the '🧹 Memory Compaction' toggle (Settings) off,

    or a window too small to leave generation room β€” this falls back

    to the plain last-`max_turns` slice, exactly as before this change.

    """
    if not history:
        return []
    cleaned = []
    for turn in history:
        role, content = turn.get("role"), turn.get("content")
        if not isinstance(content, str) or not content.strip():
            continue
        if role == "assistant":
            content = _strip_response_html(content)
            if not content:
                continue
        elif role != "user":
            continue
        cleaned.append({"role": role, "content": content})
    fixed = cleaned[-(max_turns * 2):]
    if model_obj is None and model_id is None:
        return fixed
    if not mr.get_saved_memory_compaction_enabled():
        return fixed
    try:
        if model_obj is None:
            model_obj = models.get_llm(model_id, provider=provider, n_ctx=n_ctx)
        if not agent_memory.is_local_backed_model(model_obj):
            return fixed
        window = agent_memory._effective_n_ctx(
            model_obj, n_ctx or models._llm_n_ctx or mr.get_saved_context_window())
        # Generation reserve: the upcoming answer shares the window with
        # whatever memory we keep β€” same math as compact_agent_memory().
        # `reserve_tokens` additionally holds room for prompt content added
        # SEPARATELY from memory (e.g. the RAG path's retrieved context,
        # which goes into the system prompt) so memory can't crowd it out.
        budget = int(window * mr.get_saved_memory_compaction_ratio()) \
            - mr.get_saved_max_new_tokens() - reserve_tokens
        if budget <= 0:
            return fixed
        tokenizer = agent_memory._get_model_tokenizer(model_obj)
        return agent_memory.trim_messages_to_budget(cleaned, budget, tokenizer)
    except Exception:
        # Never let a token-measurement hiccup break the chat loop β€”
        # the fixed-turn slice is a perfectly usable fallback.
        return fixed


def _lang_instruction(lang_key: str) -> str:
    """System-prompt instruction forcing the answer language to match the

    UI language. Uses the strong, explicit shared instruction from

    ui.i18n (a bare 'Answer in Khmer.' is routinely ignored by small

    models and by RAG contexts written in English)."""
    return i18n._output_lang_instruction(lang_key)


def run_timeout_message(lang_key: str) -> str:
    """Bilingual 'Generation timed out' message β€” the text the WS layer

    emits when a chat run exceeds its per-tab Generation Settings

    'Timeout'. Surfaces in the conversation as an assistant bubble."""
    if lang_key == "kh":
        return (
            "⏰ αž’αžŸαŸ‹αž–αŸαž›αž€αŸ†αžŽαžαŸ‹ (timeout) β€” αž€αžΆαžšαž”αž„αŸ’αž€αžΎαžαž…αž˜αŸ’αž›αžΎαž™αž˜αž·αž“αž‘αžΆαž“αŸ‹αž”αžΆαž“αž”αž‰αŸ’αž…αž”αŸ‹ "
            "αž€αŸ’αž“αž»αž„αž–αŸαž›αž€αŸ†αžŽαžαŸ‹αž‘αŸαŸ” αžŸαžΌαž˜αž”αž„αŸ’αž€αžΎαž“ 'Timeout' αž“αŸ…αž€αŸ’αž“αž»αž„ Generation Settings "
            "αž αžΎαž™αž–αŸ’αž™αžΆαž™αžΆαž˜αž˜αŸ’αžαž„αž‘αŸ€αžαŸ”"
        )
    return (
        "⏰ Generation timed out β€” the answer was not finished in time. "
        "Increase the 'Timeout' in Generation Settings and try again."
    )


def chat_general_direct(user_message: str, history: list, model_label: str, use_memory: bool = True, lang_key: str = "kh"):
    """A generator yielding exactly ONE (history, "") tuple β€” the direct

    path has no intermediate agent steps to stream, but is written as a

    generator (rather than a plain function) so chat_general()'s

    `yield from` dispatch works uniformly regardless of which path (direct

    or agentic) it delegates to. See chat_general_agentic() below for the

    path that actually yields multiple times as live agent steps arrive.

    """
    if not user_message.strip():
        yield history, ""
        return
    history = history or []
    history.append({"role": "user", "content": user_message})
    provider = mr.get_saved_provider("gen")
    model_id = mr.resolve_model_id(model_label, provider=provider)
    n_ctx = mr.get_saved_context_window("gen")
    ans = None  # plain-markdown answer β€” the .docx export source (set in the success branch)
    try:
        # Memory: feed back the recent conversation (minus the message we
        # just appended above, which is passed separately as `user`) so
        # follow-ups like "and what about X?" have something to refer to.
        # Skipped entirely when the "🧠 Conversation Memory" checkbox is off.
        memory_messages = _recent_memory_messages(
            history[:-1], model_id=model_id, provider=provider, n_ctx=n_ctx) if use_memory else []

        system = _lang_instruction(lang_key) + "You are a helpful, friendly assistant."
        # IMPORTANT: without this, instruct-tuned models (small ones
        # especially) tend to give a trained canned disclaimer like "I
        # don't have memory of past conversations" to any meta-question
        # about memory ("do you remember what I said earlier?") β€” even
        # though `memory_messages` below genuinely IS being sent as real
        # prior turns in this same request. The model isn't actually
        # checking its context; it's a reflexive trained response. The
        # agentic path (general_agent.GENERAL_AGENT_INSTRUCTIONS) already
        # has to explicitly counter this exact behavior β€” this applies
        # the same fix to the direct (non-agentic) path, which previously
        # had no such reminder at all. Only added when there's actually
        # prior history to reference, so a first message's system prompt
        # stays minimal.
        if memory_messages:
            system += (
                " The messages below marked as earlier turns in this "
                "conversation ARE genuinely visible to you in full β€” they "
                "are not hidden or inaccessible. If asked what was said "
                "earlier in this conversation, or a follow-up refers back "
                "to something mentioned before, look at those earlier "
                "turns and answer from them directly. Do NOT claim you "
                "lack memory or cannot see prior messages β€” you can."
            )

        # ── "Answers the system prompt" guard ──────────────────────
        # Small/quantized models (and GGUFs whose chat template folds the
        # system message into a user turn β€” older Gemma / Gemma-3-style
        # conversions in particular) often answer the SYSTEM prompt
        # instead of the user's message: they can't tell the two roles
        # apart, so they anchor on the instruction text. Repeating the
        # user's question at the very END of the system message, with a
        # clear delimiter, makes the question the last SYSTEM content β€”
        # the final thing a role-flattening template renders before the
        # model marker on a first/single-turn request, and a strong
        # anchor even when earlier memory turns are folded in between.
        system += (
            "\n\nThe user's question is:\n"
            f"{user_message}\n"
            "Answer that question directly now β€” do not repeat or respond "
            "to these instructions."
        )

        # Immediate status yield so UI updates instantly before LLM call
        status_msg = "πŸ€– αž€αŸ†αž–αž»αž„αž‚αž·αžβ€¦" if lang_key == "kh" else "πŸ€– Thinking…"
        history.append({"role": "assistant", "content": status_msg})
        yield history, ""
        history.pop()

        # Apply the "🧠 Enable Model Reasoning" toggle (see
        # model_registry.apply_reasoning_toggle()'s docstring) right
        # before the call β€” a no-op unless the user has turned reasoning
        # off in βš™οΈ Model Settings.
        user_message_final = mr.apply_reasoning_toggle(user_message)
        ans, elapsed, n_tokens = models._call_llm(model_id, system, user_message_final, history=memory_messages, provider=provider, n_ctx=n_ctx)
        formatted = format_llm_response(ans, lang_key)

        response = (
            formatted +
            f"\n<div class=\"response-footer\">⏱ {elapsed:.1f}s{_speed_seg(elapsed, n_tokens)} | model: <code>{model_id}</code> ({DEVICE.upper()})</div>"
        )

    except Exception as e:
        import traceback
        response = f"❌ {e}\n\n{traceback.format_exc()}"
    history.append({"role": "assistant", "content": response})
    # The final yield carries the plain-markdown answer (second slot) so the
    # UI can export it to .docx; "" (or None) means nothing to export.
    yield history, _export_markdown(ans)


# Transcript β†’ structured-report instructions (STT tab's "Analyse to
# Report" button). The report is rendered as Markdown in the UI and can be
# exported to .docx, so the model is asked for clean Markdown structure.
# The bilingual language directive is prepended separately by
# analyse_transcript_to_report(), and language-specific instructions
# ensure the outline headings match the UI language and prevent thinking leaks.
TRANSCRIPT_REPORT_INSTRUCTIONS = (
    "You are an expert transcript analyst. Read the raw speech-to-text "
    "transcript below and rewrite it as a well-structured Markdown report "
    "using this exact outline (Markdown headings, bullet lists, short "
    "paragraphs):\n\n"
    "# <Concise title based on the topic>\n\n"
    "## Summary\nA short paragraph capturing what the transcript is about.\n\n"
    "## Key Points\nBullet list of the main ideas, facts, figures, and "
    "decisions mentioned β€” stay faithful to the transcript, never invent "
    "content.\n\n"
    "## Topics Covered\nBullet list of the themes/sections discussed.\n\n"
    "## Action Items\nBullet list of tasks, requests, or decisions explicitly "
    "mentioned; write \"None mentioned\" if there are none.\n\n"
    "## Cleaned Transcript\nA lightly cleaned version of the raw transcript "
    "(fixed spelling/punctuation, removed filler and repetitions) that "
    "preserves all meaning.\n\n"
    "If the transcript is empty or gibberish, say so briefly instead of "
    "inventing a report.\n\n"
    "The transcript to analyze is in the user message below. Produce the "
    "report from THAT transcript β€” do not respond to these instructions "
    "themselves.\n\n"
    "Do not output internal analysis, planning, translation notes, or thinking β€” "
    "provide ONLY the final structured Markdown report directly."
)

TRANSCRIPT_REPORT_INSTRUCTIONS_KH = (
    "αž’αŸ’αž“αž€αž‚αžΊαž‡αžΆαž’αŸ’αž“αž€αžœαž·αž—αžΆαž‚αž’αžαŸ’αžαž”αž‘αžŸαŸ†αž‘αŸαž„αž‡αŸ†αž“αžΆαž‰αŸ” αž…αžΌαžšαž’αžΆαž“αž’αžαŸ’αžαž”αž‘αžŸαŸ†αž‘αŸαž„ (speech-to-text transcript) αžαžΆαž„αž€αŸ’αžšαŸ„αž˜ "
    "αž αžΎαž™αžšαŸ€αž”αž…αŸ†αžœαžΆαž‘αžΎαž„αžœαž·αž‰αž‡αžΆαžšαž”αžΆαž™αž€αžΆαžšαžŽαŸ Markdown αžŠαŸ‚αž›αž˜αžΆαž“αžšαž…αž“αžΆαžŸαž˜αŸ’αž–αŸαž“αŸ’αž’αžαŸ’αžšαžΉαž˜αžαŸ’αžšαžΌαžœ αž“αž·αž„αž…αŸ’αž”αžΆαžŸαŸ‹αž›αžΆαžŸαŸ‹ "
    "αžαžΆαž˜αž›αŸ†αž“αžΆαŸ†αž‚αŸ’αžšαŸ„αž„αžαžΆαž„αž€αŸ’αžšαŸ„αž˜ (αž…αŸ†αžŽαž„αž‡αžΎαž„ Markdown, αž…αŸ†αžŽαž»αž…αž”αž‰αŸ’αž‡αžΈ, αž“αž·αž„αž€αžαžΆαžαžŽαŸ’αžŒαžαŸ’αž›αžΈαŸ—)αŸ–\n\n"
    "# <αž…αŸ†αžŽαž„αž‡αžΎαž„αžαŸ’αž›αžΈαž•αŸ’αž’αŸ‚αž€αž›αžΎαž”αŸ’αžšαž’αžΆαž“αž”αž‘>\n\n"
    "## αžŸαŸαž…αž€αŸ’αžαžΈαžŸαž„αŸ’αžαŸαž”\nαž€αžαžΆαžαžŽαŸ’αžŒαžαŸ’αž›αžΈαž˜αž½αž™αžŠαŸ‚αž›αž”αž„αŸ’αž αžΆαž‰αž’αŸ†αž–αžΈαžαŸ’αž›αžΉαž˜αžŸαžΆαžšαžšαž½αž˜αž“αŸƒαž’αžαŸ’αžαž”αž‘αžŸαŸ†αž‘αŸαž„αŸ”\n\n"
    "## αž…αŸ†αžŽαž»αž…αžŸαŸ†αžαžΆαž“αŸ‹αŸ—\nαž”αž‰αŸ’αž‡αžΈαž…αŸ†αžŽαž»αž…αŸ—αž“αŸƒαž‚αŸ†αž“αž·αžαž…αž˜αŸ’αž”αž„ αž€αžΆαžšαž–αž·αž αžαž½αž›αŸαž αž“αž·αž„αž€αžΆαžšαžŸαž˜αŸ’αžšαŸαž…αž…αž·αžαŸ’αžαžŠαŸ‚αž›αž”αžΆαž“αž›αžΎαž€αž‘αžΎαž„ β€” "
    "αžαŸ’αžšαžΌαžœαž•αŸ’αž’αŸ‚αž€αž›αžΎαž’αžαŸ’αžαž”αž‘αžŸαŸ†αž‘αŸαž„αž–αž·αžαž”αŸ’αžšαžΆαž€αžŠ αž€αž»αŸ†αž”αž„αŸ’αž€αžΎαžαžαŸ’αž›αžΉαž˜αžŸαžΆαžšαžŠαŸ„αž™αžαŸ’αž›αž½αž“αž―αž„αž‘αžΎαž™αŸ”\n\n"
    "## αž”αŸ’αžšαž’αžΆαž“αž”αž‘αžŠαŸ‚αž›αž”αžΆαž“αž–αž·αž—αžΆαž€αŸ’αžŸαžΆ\nαž”αž‰αŸ’αž‡αžΈαž…αŸ†αžŽαž»αž…αŸ—αž“αŸƒαž”αŸ’αžšαž’αžΆαž“αž”αž‘ αž¬αž•αŸ’αž“αŸ‚αž€αžŠαŸ‚αž›αž”αžΆαž“αž–αž·αž—αžΆαž€αŸ’αžŸαžΆαŸ”\n\n"
    "## αž€αž·αž…αŸ’αž…αž€αžΆαžšαžŠαŸ‚αž›αžαŸ’αžšαžΌαžœαž’αž“αž»αžœαžαŸ’αž\nαž”αž‰αŸ’αž‡αžΈαž…αŸ†αžŽαž»αž…αŸ—αž“αŸƒαž€αž·αž…αŸ’αž…αž€αžΆαžš αžŸαŸ†αžŽαžΎ αž¬αž€αžΆαžšαžŸαž˜αŸ’αžšαŸαž…αž…αž·αžαŸ’αžαžŠαŸ‚αž›αž”αžΆαž“αž”αž‰αŸ’αž‡αžΆαž€αŸ‹αž…αŸ’αž”αžΆαžŸαŸ‹αž›αžΆαžŸαŸ‹ (សរសេរ \"αž˜αž·αž“αž˜αžΆαž“αž”αž‰αŸ’αž‡αžΆαž€αŸ‹αž‘αžΎαž™\" αž”αŸ’αžšαžŸαž·αž“αž”αžΎαž‚αŸ’αž˜αžΆαž“)αŸ”\n\n"
    "## αž’αžαŸ’αžαž”αž‘αžŸαŸ†αž‘αŸαž„αžŠαŸ‚αž›αž”αžΆαž“αž€αŸ‚αžŸαž˜αŸ’αžšαž½αž›\nαž’αžαŸ’αžαž”αž‘αžŸαŸ†αž‘αŸαž„αžŠαžΎαž˜αžŠαŸ‚αž›αž”αžΆαž“αž€αŸ‚αžŸαž˜αŸ’αžšαž½αž›αž’αž€αŸ’αžαžšαžΆαžœαž·αžšαž»αž‘αŸ’αž’ αžŸαž‰αŸ’αž‰αžΆαžœαžŽαŸ’αžŽαž™αž»αžαŸ’αžαž· αž“αž·αž„αž€αžΆαžαŸ‹αž”αž“αŸ’αžαž™αž–αžΆαž€αŸ’αž™αž‡αžΆαž“αŸ‹αž‚αŸ’αž“αžΆαž”αž“αŸ’αžαž·αž…αž”αž“αŸ’αžαž½αž… αž”αŸ‰αž»αž“αŸ’αžαŸ‚αžšαž€αŸ’αžŸαžΆαž’αžαŸ’αžαž“αŸαž™αžŠαžΎαž˜αž‘αžΆαŸ†αž„αžŸαŸ’αžšαž»αž„αŸ”\n\n"
    "αž”αŸ’αžšαžŸαž·αž“αž”αžΎαž’αžαŸ’αžαž”αž‘αžŸαŸ†αž‘αŸαž„αž‘αž‘αŸ αž¬αž‚αŸ’αž˜αžΆαž“αž“αŸαž™ αžŸαžΌαž˜αž”αž‰αŸ’αž‡αžΆαž€αŸ‹αž™αŸ‰αžΆαž„αžαŸ’αž›αžΈαž‡αžΆαž‡αžΆαž„αž€αžΆαžšαž”αž„αŸ’αž€αžΎαžαžšαž”αžΆαž™αž€αžΆαžšαžŽαŸαž€αŸ’αž›αŸ‚αž„αž€αŸ’αž›αžΆαž™αŸ”\n\n"
    "αž’αžαŸ’αžαž”αž‘αžŸαŸ†αž‘αŸαž„αžŠαŸ‚αž›αžαŸ’αžšαžΌαžœαžœαž·αž—αžΆαž‚αž‚αžΊαžŸαŸ’αžαž·αžαž“αŸ…αž€αŸ’αž“αž»αž„αžŸαžΆαžšαžšαž”αžŸαŸ‹αž’αŸ’αž“αž€αž”αŸ’αžšαžΎαžαžΆαž„αž€αŸ’αžšαŸ„αž˜αŸ” "
    "αž€αž»αŸ†αžŸαžšαžŸαŸαžšαž€αžΆαžšαžœαž·αž—αžΆαž‚ (Analysis) αž•αŸ‚αž“αž€αžΆαžš (Planning) αž¬αž€αžΆαžšαž‚αž·αžαžαžΆαž„αž€αŸ’αž“αž»αž„αž‡αžΆαž—αžΆαžŸαžΆαž’αž„αŸ‹αž‚αŸ’αž›αŸαžŸαž‘αžΎαž™ β€” "
    "αž…αžΌαžšαž•αŸ’αžαž›αŸ‹αžαŸ‚αžšαž”αžΆαž™αž€αžΆαžšαžŽαŸ Markdown αžŸαž˜αŸ’αžšαŸαž…αž…αž»αž„αž€αŸ’αžšαŸ„αž™αž‡αžΆαž—αžΆαžŸαžΆαžαŸ’αž˜αŸ‚αžšαžŠαŸ„αž™αž•αŸ’αž‘αžΆαž›αŸ‹αŸ”"
)


def _transcript_report_instructions(lang_key: str) -> str:
    if lang_key == "kh":
        return TRANSCRIPT_REPORT_INSTRUCTIONS_KH
    return TRANSCRIPT_REPORT_INSTRUCTIONS


def analyse_transcript_to_report(transcript, model_label, lang_key="kh",

                                 provider=None):
    """Generator that turns a raw speech-to-text transcript into a

    structured Markdown report using the LLM picked on the STT tab (its

    own provider + model dropdown, saved under the "stt_report" tab key).



    Yields (status, report) tuples: first a short bilingual "thinking"

    status with report="" so the UI can show progress, then the final

    report with status="". An empty/whitespace transcript yields ("", "")

    immediately WITHOUT any LLM call (the UI shows its own bilingual hint

    in that case). The report is plain Markdown β€” suitable for the STT

    tab's Markdown output and for .docx export via

    backend.docx_export.markdown_text_to_docx()."""
    if not transcript or not transcript.strip():
        yield "", ""
        return
    l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
    provider = provider or mr.get_saved_provider("stt_report")
    model_id = mr.resolve_model_id(model_label, provider=provider)
    n_ctx = mr.get_saved_context_window("stt_report")
    try:
        yield l.get("think_stt_analyse", "πŸ€– Thinking…"), ""
        system = _lang_instruction(lang_key) + _transcript_report_instructions(lang_key)
        ans, elapsed, n_tokens = models._call_llm(model_id, system, transcript,
                                        history=[], provider=provider, n_ctx=n_ctx)
        raw_report = (ans or "").strip()
        from agents.agent_streaming import _unwrap_leaked_final_answer
        report = _unwrap_leaked_final_answer(raw_report)
        if isinstance(report, str):
            report = report.strip()
        else:
            report = str(report or "").strip()
        if not report:
            report = (
                "⚠️ αž‚αŸ’αž˜αžΆαž“αžšαž”αžΆαž™αž€αžΆαžšαžŽαŸαžαŸ’αžšαž‘αž”αŸ‹αž˜αž€αžœαž·αž‰αž‘αŸ β€” αžŸαžΌαž˜αž–αŸ’αž™αžΆαž™αžΆαž˜αž˜αŸ’αžαž„αž‘αŸ€αžαŸ”"
                if lang_key == "kh" else
                "⚠️ The model returned an empty report. Please try again."
            )
        yield "", f"{report}\n\n---\n⏱ {elapsed:.1f}s{_speed_seg(elapsed, n_tokens)} | model: `{model_id}` ({DEVICE.upper()})"
    except Exception as e:
        yield "", f"❌ {e}"


def chat_general_agentic(user_message: str, history: list, model_label: str,

                          use_memory: bool = True, lang_key: str = "kh",

                          max_steps: Optional[int] = None,

                          execution_timeout: Optional[int] = None,

                          use_tool_calling: bool = True):
    """Agentic General Chat: a smolagents ToolCallingAgent (or CodeAgent

    when 'Use native tool calling' is unchecked β€” see general_agent.py)

    with the library's own built-in web-search/webpage tools

    (DuckDuckGoSearchTool, VisitWebpageTool), deciding for itself whether

    a question needs a web lookup before answering. Unlike RAG Chat's

    agent, this has no knowledge-base grounding requirement β€” it's meant

    for open-ended questions, not strictly-cited document Q&A.



    A GENERATOR: yields (history, "") once per live agent step as it

    happens (see agent_streaming.stream_agent_steps()), then one final

    time with the polished final answer appended β€” instead of blocking

    silently until the whole run finishes. Mirrors smolagents' own

    GradioUI streaming behaviour, adapted to this app's chat history

    shape/styling (see agent_streaming.py's module docstring).

    """
    if not user_message.strip():
        yield history, ""
        return
    history = history or []
    history.append({"role": "user", "content": user_message})
    # Immediate status yield so UI updates instantly before agent construction / model loading
    status_msg = "πŸŒπŸ€– αž€αŸ†αž–αž»αž„αžšαŸ€αž”αž…αŸ†αž—αŸ’αž“αžΆαž€αŸ‹αž„αžΆαžš AI…" if lang_key == "kh" else "πŸŒπŸ€– Initializing AI agent…"
    history.append({"role": "assistant", "content": status_msg})
    yield history, ""
    history.pop()
    provider = mr.get_saved_provider("gen")
    model_id = mr.resolve_model_id(model_label, provider=provider)
    n_ctx = mr.get_saved_context_window("gen")
    # Persisted step budget (the per-tab "Max Steps" control): the WS
    # payload's explicit value wins; None falls back to the saved budget,
    # else AUTO (model-scaled default inside get_general_agent).
    max_steps = max_steps if max_steps is not None else mr.get_saved_agent_steps("gen")
    # Same auto pattern for the per-step execution timeout (the per-tab
    # "Exec timeout" control): explicit payload wins, else the saved
    # value, else AUTO (the agent factory's default timeout).
    execution_timeout = execution_timeout if execution_timeout is not None else mr.get_saved_execution_timeout("gen")
    export_text = None  # plain-markdown answer for .docx export (set when the run produced one)
    try:
        agent = general_agent.get_general_agent(model_id, max_steps=max_steps, execution_timeout=execution_timeout, use_tool_calling=use_tool_calling, provider=provider, lang_key=lang_key, n_ctx=n_ctx)
        general_agent.reset_tool_usage()
        t0     = time.time()
        # reset=False keeps this CodeAgent's own memory (agent.memory.steps)
        # across turns instead of wiping it every message β€” see
        # https://huggingface.co/docs/smolagents/tutorials/memory. Capped
        # right after so a long conversation doesn't grow the prompt
        # unboundedly turn after turn. When the "🧠 Conversation Memory"
        # checkbox is off, reset=True instead, so every message starts
        # from a clean slate (no memory to cap either).
        #
        # The message is wrapped with a per-task citation reminder (NOT
        # just the raw user_message) because GENERAL_AGENT_INSTRUCTIONS'
        # citation requirement only reaches the model at all if this
        # installed smolagents version's CodeAgent accepts an
        # `instructions=` kwarg (see agents/agent_factory.py's build_smol_agent()) β€”
        # on a version where it doesn't, this per-call reminder is the
        # ONLY place the model ever sees the requirement. Without it, the
        # model never writes a '### References' section, and the
        # "Sources used" block below always ends up empty even after a
        # turn that genuinely searched the web.
        task = general_agent.build_task_with_citation_reminder(user_message, lang_key)
        # See chat_general_direct()'s matching comment β€” a no-op unless
        # the "🧠 Enable Model Reasoning" toggle is off.
        task = mr.apply_reasoning_toggle(task)
        # Live step streaming β€” see agent_streaming.stream_agent_steps()'s
        # docstring for the shared (step_msg, is_final, final_output)
        # generator contract every agentic call site in this app now uses.
        # Token-budget-aware memory compaction (see agent_memory.py): before
        # this run, if the accumulated memory would push the next prompt past
        # the context window, condense the older turns into a rolling summary
        # instead of just dropping them β€” the fixed turn-cap below stays as
        # the post-run safety net. No-op unless conversation memory is on and
        # the '🧹 Memory Compaction' toggle (Settings) is enabled.
        if use_memory and _maybe_compact_agent_memory(agent, model_id, lang_key, tab_key="gen"):
            history.append({"role": "assistant", "content": _compaction_status_msg(lang_key)})
            yield history, ""
            history.pop()
        result = None
        diag = None  # snapshot from the stream's final yield (every stream path ends with one); stays None only if the loop never ran
        for step_msg, is_final, final_output, diag in agent_streaming.stream_agent_steps(agent, task, reset=not use_memory, lang_key=lang_key):
            if not is_final:
                if step_msg is not None:
                    history.append(step_msg)
                    yield history, ""
                continue
            result = final_output
        if use_memory:
            agent_memory.cap_agent_memory(agent, max_turns=AGENTIC_MEMORY_TURNS)
        elapsed = time.time() - t0

        turn_count = sum(1 for s in agent.memory.steps if s.__class__.__name__ == "TaskStep")
        ans = str(result)
        n_tokens = models._estimate_tokens(ans)
        # Only show sources the model actually appears to have USED in
        # its final answer β€” not every link `web_search` happened to
        # return this turn (most search hits are never read or relied on;
        # dumping all of them produced a misleading "sources" list full
        # of irrelevant results, e.g. random weather sites showing up for
        # an unrelated question just because one search query returned
        # them). general_agent.resolve_actually_used_sources() cross-
        # checks the model's own '### References' section against what
        # was really searched/visited this turn, falling back to pages
        # actually opened via visit_webpage (never to the full link dump)
        # if the model's citations don't check out. Its own (unverified)
        # References section is then swapped out for this verified one.
        queries, urls, links = general_agent.get_tool_usage()
        used_sources = general_agent.resolve_actually_used_sources(ans, urls, links)
        ans = general_agent.strip_trailing_references_section(ans)
        if used_sources:
            ans, used_sources = general_agent.renumber_citations(ans, used_sources)
            # Same in-text [URL] / [page-title] -> [N] normalization as the
            # RAG and Deep Research paths: small local models paste the raw
            # source URL or page title into the bracket instead of the bare
            # number. Refs here are renumbered (num, title, url) tuples, so
            # either form resolves to the final number.
            ans = rag_agent.normalize_in_text_citations(ans, used_sources)
            ref_lines = ["**πŸ”— Sources used for this answer:**"]
            for num, title, url in used_sources:
                link_str = f"[{title}]({url})" if title != url else url
                ref_lines.append(f"- [{num}] {link_str}")
            ans += f"\n\n<div class=\"sources-block\">\n\n" + "\n".join(ref_lines) + "\n\n</div>"
        formatted = format_llm_response(ans, lang_key)
        # Surface compaction activity in the footer: how many times the
        # rolling-summary compaction has run in this conversation (see
        # agent_memory.compact_agent_memory()).
        compacted_n = getattr(agent, "_compaction_count", 0) or 0
        memory_txt = "off"
        if use_memory:
            memory_txt = f"on ({turn_count} turn(s))"
            if compacted_n:
                memory_txt = f"on ({turn_count} turn(s), compacted {compacted_n}Γ—)"
        # The effective step budget the agent ACTUALLY ran with (the
        # model-scaled value when the Max Steps control is on auto β€” see
        # _agent_steps_budget_txt) β€” so the footer shows what really ran.
        steps_txt = _agent_steps_budget_txt(agent)
        steps_seg = f"Β· {steps_txt} " if steps_txt else ""
        # The effective per-step execution timeout β€” shown ONLY on the
        # CodeAgent path, since only it has a Python executor (the helper
        # gates on that; see agent_streaming._agent_exec_timeout_txt).
        exec_txt = agent_streaming._agent_exec_timeout_txt(agent)
        exec_seg = f"Β· {exec_txt} " if exec_txt else ""
        response = (
            formatted +
            agent_streaming._agent_abort_html(lang_key, diag) +
            f"\n<div class=\"response-footer\">⏱ {elapsed:.1f}s{_speed_seg(elapsed, n_tokens)} | model: <code>{model_id}</code> "
            f"({DEVICE.upper()}) | agentic Β· web search + {_agent_mechanism_txt(use_tool_calling)} "
            f"{steps_seg}{exec_seg}Β· memory: {memory_txt}</div>" + _agent_failure_hint(lang_key, diag)
        )
        export_text = _export_markdown(ans)
    except Exception as e:
        import traceback
        response = f"❌ {e}\n\n{traceback.format_exc()}"
    yield from _stream_final_text(history, response, export_text)


def chat_general(user_message: str, history: list, model_label: str,

                 use_agentic: bool = False, use_memory: bool = True,

                 lang_key: str = "kh",

                 max_steps: Optional[int] = None,

                 execution_timeout: Optional[int] = None,

                 use_tool_calling: bool = True):
    """General Chat entry point. Dispatches to:



    - use_agentic=False (default, unchanged behaviour): one direct LLM

      call, no tools β€” see chat_general_direct().

    - use_agentic=True: a ToolCallingAgent (CodeAgent when native tool

      calling is unchecked) with web-search/webpage tools decides

      for itself whether to look things up β€” see chat_general_agentic().

      Same reliability caveat as agentic RAG Chat: works best with

      capable models (roughly Gemma-4-E4B and above); small models may never

      call a tool at all.



    `use_memory` controls the "🧠 Conversation Memory" checkbox: whether

    prior turns in this conversation are remembered (direct path) or kept

    in the CodeAgent's own memory (agentic path). Memory is never

    persisted to disk either way β€” see agent_memory.py.



    A GENERATOR (via `yield from`): both branches are generators

    themselves (chat_general_direct() yields once; chat_general_agentic()

    yields once per live agent step β€” see agent_streaming.py), so callers

    (ui.py) always iterate this the same way regardless of which mode is

    selected, rather than needing to special-case "does this return a

    generator or a plain tuple".

    """
    if use_agentic:
        yield from chat_general_agentic(user_message, history, model_label, use_memory, lang_key,
                                         max_steps=max_steps, execution_timeout=execution_timeout,
                                         use_tool_calling=use_tool_calling)
    else:
        yield from chat_general_direct(user_message, history, model_label, use_memory, lang_key)


def _stream_final_text(history: list, response: str, export_text):
    """Yield (history, second) once per chunk of the finished answer,

    accumulating the text into a new assistant message as it goes.



    The second tuple slot β€” the plain-markdown answer for .docx export β€” is

    attached ONLY to the LAST chunk, so the "final yield carries the answer"

    contract is uniform with chat_rag_direct()'s single final yield; every

    intermediate chunk yields "". (The UI handler only reads the last

    value, but a future consumer mid-stream must never see the answer early.)



    When a WS run owns the live bus (get_bus().running), the model's tokens

    were ALREADY streamed into the answer bubble live by the `live` WS

    events β€” re-chunking the finished text here would visibly re-type the

    whole answer on top of the live stream. Skip the pacing and yield the

    complete answer in ONE chunk so the reveal is atomic (and the uniform

    final-yield/export contract still holds)."""
    history.append({"role": "assistant", "content": ""})
    if get_bus().running:
        history[-1]["content"] = response
        yield history, export_text or ""
        return
    chunks = agent_streaming.chunk_final_text(response)
    last_idx = len(chunks) - 1
    acc = ""
    for i, piece in enumerate(chunks):
        acc += piece
        history[-1]["content"] = acc
        yield history, (export_text or "") if i == last_idx else ""


def _export_markdown(ans) -> str:
    """docx-export copy of a chat answer: strip every HTML tag (via the

    shared _strip_html_tags primitive, the same one _strip_response_html

    uses for conversation memory) so the exported .docx gets clean

    markdown instead of divs, classes, or any other HTML a model may emit.



    This covers both the app's own ``<div class="sources-block">…</div>``

    references wrapper AND stray model-emitted markup (`<table>`, `<br>`,

    `<span class="…">`, …). Unlike _strip_response_html, the full bubble

    transforms (details/final-answer-block/<hr> truncation) are NOT

    applied β€” the answer is raw pre-formatting markdown, so a model-emitted

    `<hr>` is a legitimate separator and must not truncate the export.

    Returns "" for None/empty answers (nothing worth exporting)."""
    if not ans:
        return ""
    return _strip_html_tags(str(ans))


# ──────────────────────────────────────────────────────────────────────
# Visual grounding β€” the visual index (byaldi/ColPali page images) wired
# into RAG chat. When the question matches pages in the visual index, the
# answer is produced (direct path) or refined (agentic path) by the RAG
# chat's OWN model (the same model already serving the text answer β€” no
# second VLM loaded into VRAM) looking at BOTH the retrieved text context
# and the actual page images β€” grounded image answers for charts / scans /
# image-heavy PDFs that text extraction misses. Everything degrades
# gracefully: no visual index β†’ [] (a cheap directory check β€” the 2-8 GB
# retriever model is only loaded when an index actually exists), the RAG
# model not being multimodal or load/generation failing β†’ None β†’ the
# text-only LLM path runs exactly as before.
# ──────────────────────────────────────────────────────────────────────


def _visual_grounding_images(question: str, top_k: int = 3) -> list:
    """Page images from the visual index most relevant to `question`, or

    [] when the index is empty / unavailable. The cheap directory check

    runs first β€” kb.visual_retrieve only loads the retriever model when

    an index actually exists. Never raises."""
    import os
    if not os.path.exists(os.path.join(mr.VISUAL_INDEX_DIR, "main")):
        return []
    try:
        return kb.visual_retrieve(question, top_k=top_k)
    except Exception as e:
        print(f"[RAG] visual page retrieval skipped: {e}")
        return []


def _rag_model_can_see_images(model_id, provider=None) -> bool:
    """Cheap, no-load check that the RAG chat's OWN model is multimodal, so

    the grounding pass never loads a second model (or triggers a retriever

    load) just to discover it can't see images. The logic lives in

    model_registry.is_multimodal_model β€” the SINGLE source of truth shared

    with Deep Research's image visualizer β€” this wrapper keeps the chat-path

    name the tests patch."""
    return mr.is_multimodal_model(model_id, provider)


def _vlm_grounded_answer(question: str, images: list, context: str,

                         model_id, provider=None,

                         lang_key: str = "kh", n_ctx=None):
    """Answer `question` with the RAG chat's OWN model β€” the same model

    already serving the text answer, so no second VLM is loaded into VRAM

    (for a GGUF VLM on llama-server the grounding rides the SAME server

    instance, restarted once with the mmproj; for a transformers VLM the

    already-loaded LLM is reused). Grounded in the retrieved text `context`

    AND the retrieved page `images`. Returns None when no images, the RAG

    model isn't multimodal, or load/generation fails β€” the caller falls

    back to the text-only LLM. Never raises."""
    if not images:
        return None
    if not _rag_model_can_see_images(model_id, provider):
        return None
    try:
        mmproj = mr.GGUF_VLM_MMPROJ_MAP.get(model_id)
        ans = models.vlm_answer(question, images, context=context, model_id=model_id,
                                mmproj_path=mmproj, lang_key=lang_key, n_ctx=n_ctx,
                                provider=provider)
        # A failed VLM generation surfaces as a ❌ error string from
        # vlm_answer β€” treat it as unusable so the text-only LLM runs
        # instead of shipping an error bubble as the answer.
        if not ans or str(ans).lstrip().startswith("❌"):
            return None
        return ans
    except Exception as e:
        print(f"[RAG] VLM grounding unavailable β€” falling back to text: {e}")
        return None


def _visual_footer_note(model_id, provider, lang_key, visual_pages,

                        visual_images, vlm_used) -> str:
    """The response-footer's visual-grounding segment (agentic RAG). Three

    states:

      * the grounding pass RAN β†’ ' Β· πŸ–ΌοΈ VLM-grounded (N page image(s))'

      * the AGENT used the visual index (its `visual_retriever` tool pulled

        page images) but the RAG model is TEXT-ONLY β€” the VRAM-saving

        same-model rule skipped the VLM, so say honestly that the pages

        were retrieved but the answer was NOT image-verified.

      * otherwise β†’ '' (nothing visual happened this run).

    """
    if vlm_used:
        n = len(visual_images)
        return (f" Β· πŸ–ΌοΈ VLM-grounded ({n} page image"
                + ("s" if n != 1 else "") + ")")
    n = int(visual_pages or 0)
    if n > 0 and not _rag_model_can_see_images(model_id, provider):
        if lang_key == "kh":
            return (f" Β· πŸ–ΌοΈ αž”αžΆαž“αž‘αžΆαž‰αžšαžΌαž”αž—αžΆαž–αž‘αŸ†αž–αŸαžš {n} β€” αž˜αŸ‰αžΌαžŠαŸ‚αž› RAG αž˜αžΎαž›αžšαžΌαž”αž—αžΆαž–αž˜αž·αž“αž”αžΆαž“ "
                    "(αž…αž˜αŸ’αž›αžΎαž™αž˜αž·αž“αž”αžΆαž“αž•αŸ’αž‘αŸ€αž„αž•αŸ’αž‘αžΆαžαŸ‹αž‡αžΆαž˜αž½αž™αžšαžΌαž”αž—αžΆαž–)")
        return (f" Β· πŸ–ΌοΈ {n} page image" + ("s" if n != 1 else "")
                + " retrieved β€” RAG model is text-only (answer not image-verified)")
    return ""


def chat_rag_direct(user_message: str, history: list, model_label: str, use_memory: bool = True,

                    theme: str = "", subtheme: str = "", lang_key: str = "kh",

                    sources: Optional[list] = None,

                    visual_retrieval: bool = False):
    """Non-agentic RAG: always retrieve context from ChromaDB first (same

    retrieval call the agentic path's `retriever` tool wraps), then hand

    that context straight to the LLM in one direct call β€” no CodeAgent,

    no tool-calling, no code-generation steps to parse.



    This exists because tool-calling reliability depends heavily on the

    underlying model (see rag_agent.py's caveat about Gemma-4-E2B): small

    or older models often never call the retriever tool, call it

    malformed, or burn every retry step failing to parse, and end up

    hallucinating or timing out instead of answering. Retrieval here is

    unconditional and handled entirely by the app, so even a very small

    model just has to read the provided context and answer β€” nothing to

    invoke, nothing to parse.

    """
    if not user_message.strip():
        yield history, ""
        return
    history = history or []
    history.append({"role": "user", "content": user_message})
    provider = mr.get_saved_provider("rag")
    model_id = mr.resolve_model_id(model_label, provider=provider)
    n_ctx = mr.get_saved_context_window("rag")
    ans = None  # plain-markdown answer β€” the .docx export source (set in both success branches)
    try:
        # Immediate status yield so UI updates instantly before retrieval
        status_msg = "πŸ“š αž€αŸ†αž–αž»αž„αž‘αžΆαž‰αž™αž€αž”αžšαž·αž”αž‘β€¦" if lang_key == "kh" else "πŸ“š Retrieving context…"
        history.append({"role": "assistant", "content": status_msg})
        yield history, ""
        history.pop()

        context, sources = kb.retrieve_context(user_message, theme, subtheme, sources=sources)
        # Visual grounding: ALSO retrieve related PAGE IMAGES from the
        # visual index (charts / scans / image-heavy PDFs that text
        # extraction misses). When pages match, the RAG chat's OWN model
        # (no second VLM loaded into VRAM) answers from both the text
        # context and the actual images. Only attempted when the RAG model
        # is itself multimodal β€” a text-only model skips the visual
        # retrieval entirely (no wasted 2-8 GB retriever load).
        visual_images = []
        if visual_retrieval and _rag_model_can_see_images(model_id, provider):
            # The FIRST visual retrieval lazily loads the 2-8 GB retriever
            # model β€” announce that cold load with its own status line so the
            # UI isn't stuck on "Context retrieved. Generating answer…" with
            # no feedback for tens of seconds. When the model is already
            # cached (warm), the bubble is skipped β€” no flicker, and the
            # fast path stays untouched.
            if kb.visual_retriever_needs_load():
                vis_load_status = ("πŸ–ΌοΈ αž€αŸ†αž–αž»αž„αž•αŸ’αž‘αž»αž€αž›αž·αž”αž·αž€αŸ’αžšαž˜αžšαžΌαž”αž—αžΆαž–β€¦" if lang_key == "kh"
                                   else "πŸ–ΌοΈ Loading visual index…")
                history.append({"role": "assistant", "content": vis_load_status})
                yield history, ""
                history.pop()
            visual_images = _visual_grounding_images(user_message)
        if not context and not visual_images:
            ans = rag_agent.nothing_found_message(lang_key)
            formatted = format_llm_response(ans, lang_key)
            response = (
                formatted +
                f"\n\n<hr><sub>model: <code>{model_id}</code> ({DEVICE.upper()}) "
                f"| direct RAG (no relevant context found)</sub>"
            )
        else:
            system = _lang_instruction(lang_key) + (
                "You are a strict retrieval-augmented assistant. Answer the "
                "user's question using ONLY the context below, which was "
                "retrieved from the user's own indexed knowledge base. Never "
                "use your own general knowledge or training data, even if you "
                "believe you know the answer. If the context doesn't contain "
                "the answer, say clearly that the knowledge base doesn't "
                "contain this information β€” do not guess or fill the gap "
                "yourself.\n\n"
                "CITATION REQUIREMENT: each context chunk below is tagged "
                "with its source in brackets, e.g. '[report.pdf]'. Cite "
                "each claim in-text with a bracketed NUMBER (e.g. [1], "
                "[2]) assigned per source, and finish your answer with a "
                "'### References' section mapping each number to its "
                "source filename (e.g. '[1] report.pdf'). IMPORTANT: inside "
                "the in-text brackets write ONLY the number β€” NEVER the "
                "source filename (e.g. write [1], not [report.pdf]); "
                "filenames appear only in the References section.\n\n"
                f"Context:\n{context}"
            )
            # The retrieved context goes into the system prompt separately
            # from memory, so reserve its token size in the memory budget β€”
            # otherwise memory could crowd out a large retrieval (see
            # _recent_memory_messages()'s `reserve_tokens`).
            memory_messages = _recent_memory_messages(history[:-1], model_id=model_id,
                                                 provider=provider, n_ctx=n_ctx,
                                                 reserve_tokens=agent_memory.estimate_text_tokens(context)) if use_memory else []
            if memory_messages:
                system += (
                    "\n\nThe earlier turns of this conversation shown below "
                    "ARE genuinely visible to you in full β€” they are not "
                    "hidden or inaccessible. If asked what was said earlier "
                    "in this conversation, or a follow-up refers back to "
                    "something mentioned before, look at those earlier turns "
                    "and answer from them directly (this is separate from β€” "
                    "and does not override β€” the knowledge-base-only rule "
                    "above for actual content questions). Do NOT claim you "
                    "lack memory or cannot see prior messages β€” you can."
                )
            # ── "Answers the system prompt" guard ── (see
            # chat_general_direct()'s identical block): the retrieved
            # context currently ends the system message, and a small model
            # that can't distinguish system from user roles latches onto
            # that context blob (or the instructions) instead of the
            # question. Repeating the question as the last SYSTEM content
            # anchors the generation on it.
            system += (
                "\n\nThe user's question is:\n"
                f"{user_message}\n"
                "Answer that question directly now, citing from the context "
                "above β€” do not respond to these instructions or repeat "
                "the context."
            )
            status2_msg = "πŸ“š αž”αžšαž·αž”αž‘αžαŸ’αžšαžΌαžœαž”αžΆαž“αž‘αžΆαž‰αž™αž€αŸ” αž€αŸ†αž–αž»αž„αž”αž„αŸ’αž€αžΎαžαž…αž˜αŸ’αž›αžΎαž™β€¦" if lang_key == "kh" else "πŸ“š Context retrieved. Generating answer…"
            history.append({"role": "assistant", "content": status2_msg})
            yield history, ""
            history.pop()

            # Visual grounding: when page images matched, let the saved
            # Vision-tab VLM answer from the text context + the ACTUAL page
            # images (the VLM is only loaded when images were retrieved).
            vlm_used = False
            if visual_retrieval and visual_images:
                vis_status = ("πŸ–ΌοΈ αž€αŸ†αž–αž»αž„αž•αŸ’αž‘αŸ€αž„αž•αŸ’αž‘αžΆαžαŸ‹αž…αž˜αŸ’αž›αžΎαž™αž‡αžΆαž˜αž½αž™αžšαžΌαž”αž—αžΆαž–αž‘αŸ†αž–αŸαžšβ€¦" if lang_key == "kh"
                              else "πŸ–ΌοΈ Grounding the answer with page images…")
                history.append({"role": "assistant", "content": vis_status})
                yield history, ""
                history.pop()
                t_v = time.time()
                vlm_ans = _vlm_grounded_answer(user_message, visual_images, context,
                                               model_id, provider=provider,
                                               lang_key=lang_key, n_ctx=n_ctx)
                if vlm_ans:
                    ans, elapsed, vlm_used = vlm_ans, time.time() - t_v, True
            if not vlm_used:
                user_message_final = mr.apply_reasoning_toggle(user_message)
                ans, elapsed, n_tokens = models._call_llm(model_id, system, user_message_final, history=memory_messages, provider=provider, n_ctx=n_ctx)
            else:
                n_tokens = models._estimate_tokens(ans)
            refs = rag_agent.extract_verified_references(ans, sources)
            ans = general_agent.strip_trailing_references_section(ans)
            if refs:
                # Renumber FIRST so the sequential [N] map is final, then
                # rewrite in-text [filename] / (filename) markers the model
                # pasted verbatim into their verified [N] / (N) form (small
                # GGUFs often ignore the "numbers only" rule). Running the
                # sanitizer BEFORE renumbering would leave parenthesized
                # markers stale whenever the model's own reference numbers
                # were non-sequential β€” renumber_citations only remaps
                # [digits] brackets, never (N) parens.
                used_sources = [(str(n), name, name) for n, name in refs]
                ans, renumbered_refs = general_agent.renumber_citations(ans, used_sources)
                ans = rag_agent.normalize_in_text_citations(
                    ans, [(int(n), name) for n, name, _ in renumbered_refs])
                ref_lines = [f"- [{n}] {name}" for n, name, _ in renumbered_refs]
                ans += f"\n\n<div class=\"sources-block\">\n\n**πŸ“š References:**\n" + "\n".join(ref_lines) + "\n\n</div>"
            formatted = format_llm_response(ans, lang_key)
            _img_txt = "page image" if len(visual_images) == 1 else "page images"
            mode_txt = (f"direct RAG Β· VLM-grounded ({len(visual_images)} {_img_txt})"
                        if vlm_used else "direct RAG")
            response = (
                formatted +
                f"\n<div class=\"response-footer\">⏱ {elapsed:.1f}s{_speed_seg(elapsed, n_tokens)} | model: <code>{model_id}</code> "
                f"({DEVICE.upper()}) | {mode_txt}</div>"
            )
    except Exception as e:
        import traceback
        response = f"❌ {e}\n\n{traceback.format_exc()}"
    history.append({"role": "assistant", "content": response})
    # The final yield carries the plain-markdown answer (second slot) so the
    # UI can export it to .docx; "" (or None) means nothing to export.
    yield history, _export_markdown(ans)


def chat_rag(user_message: str, history: list, model_label: str, use_agentic: bool = True, use_memory: bool = True,

             theme: str = "", subtheme: str = "", max_steps: Optional[int] = None,

             searcher_max_steps: Optional[int] = None,

             execution_timeout: Optional[int] = None,

             lang_key: str = "kh", use_tool_calling: bool = True,

             sources: Optional[list] = None,

             visual_retrieval: bool = False):
    """RAG Chat entry point. `max_steps` / `searcher_max_steps` are the

    agentic-mode step budgets for the manager and its `knowledge_searcher`

    sub-agent respectively (the per-tab AgentControls in the web UI); None

    uses each agent's model-scaled default. `visual_retrieval` (default

    False) toggles the resource-intensive visual path: when OFF, neither the

    page-image retrieval (the agent's `visual_retriever` tool in agentic

    mode, or the direct visual-index query) nor the VLM grounding pass runs

    β€” the RAG chat becomes a pure text-retrieval + text-LLM pipeline."""
    if not use_agentic:
        yield from chat_rag_direct(user_message, history, model_label, use_memory, theme, subtheme, lang_key,
                                   sources=sources, visual_retrieval=visual_retrieval)
        return

    if not user_message.strip():
        yield history, ""
        return
    history = history or []
    history.append({"role": "user", "content": user_message})
    # Immediate status yield so UI updates instantly before agent construction / retrieval
    status_msg = "πŸ“šπŸ€– αž€αŸ†αž–αž»αž„αžšαŸ€αž”αž…αŸ†αž”αŸ’αžšαž–αŸαž“αŸ’αž’ RAG…" if lang_key == "kh" else "πŸ“šπŸ€– Initializing RAG search agent…"
    history.append({"role": "assistant", "content": status_msg})
    yield history, ""
    history.pop()
    provider = mr.get_saved_provider("rag")
    model_id = mr.resolve_model_id(model_label, provider=provider)
    n_ctx = mr.get_saved_context_window("rag")
    # Persisted step budgets (the per-tab "Max Steps" / "Search steps"
    # controls): the WS payload's explicit values win; None falls back to
    # the saved budgets, else AUTO (model-scaled defaults inside
    # get_rag_agent / _build_searcher_agent).
    max_steps = max_steps if max_steps is not None else mr.get_saved_agent_steps("rag")
    searcher_max_steps = searcher_max_steps if searcher_max_steps is not None else mr.get_saved_sub_agent_steps("rag")
    # Per-step code-execution timeout (the RAG "Exec timeout" control in
    # agentic mode): the payload's explicit value wins; None falls back to
    # the saved per-tab value, else AUTO (the agent factory's default).
    execution_timeout = execution_timeout if execution_timeout is not None else mr.get_saved_execution_timeout("rag")
    export_text = None  # plain-markdown answer for .docx export (set when the run produced one)
    try:
        agent = rag_agent.get_rag_agent(model_id, theme, subtheme, max_steps,
                                        searcher_max_steps=searcher_max_steps,
                                        execution_timeout=execution_timeout,
                                        use_tool_calling=use_tool_calling,
                                        provider=provider, n_ctx=n_ctx,
                                        sources=sources,
                                        visual_retrieval=visual_retrieval)
        rag_agent.reset_retriever_stats()
        task = rag_agent.build_strict_task(user_message, lang_key, theme=theme, subtheme=subtheme, sources=sources)
        task = mr.apply_reasoning_toggle(task)

        t0     = time.time()
        # Token-budget-aware memory compaction (see agent_memory.py) β€” same
        # reasoning as chat_general_agentic(); the fixed turn-cap below stays
        # as the post-run safety net.
        if use_memory and _maybe_compact_agent_memory(agent, model_id, lang_key, tab_key="rag"):
            history.append({"role": "assistant", "content": _compaction_status_msg(lang_key)})
            yield history, ""
            history.pop()
        result = None
        diag = None  # snapshot from the stream's final yield (every stream path ends with one); stays None only if the loop never ran
        for step_msg, is_final, final_output, diag in agent_streaming.stream_agent_steps(agent, task, reset=not use_memory, lang_key=lang_key):
            if not is_final:
                if step_msg is not None:
                    history.append(step_msg)
                    yield history, ""
                continue
            result = final_output
        if use_memory:
            agent_memory.cap_agent_memory(agent, max_turns=AGENTIC_MEMORY_TURNS)
        elapsed = time.time() - t0

        call_count = 0  # defined so the footer below never NameErrors on the abort path
        # visual-grounding state (footer + pass): the page images the
        # grounding pass used (visual_images / vlm_used) plus the page-image
        # count the agent's OWN visual_retriever tool pulled this run
        # (visual_pages β€” read from get_visual_retriever_stats below, 0 on
        # the abort/never-searched paths).
        visual_images, vlm_used, visual_pages = [], False, 0
        if diag and diag.get("aborted"):
            # The fail-fast guard aborted this run β€” surface its guidance
            # message instead of the "never searched" verdict (which would
            # wrongly claim the agent never tried).
            ans = str(result)
        else:
            call_count, found_count, sources_used = rag_agent.get_retriever_stats()
            # The visual_retriever tool's OWN stats β€” the aggregate above
            # mixes text + visual + summary tools, so it can't answer "did
            # the agent use the visual index?" (the footer note's trigger).
            _vis_calls, _vis_found, visual_pages = rag_agent.get_visual_retriever_stats()
            # The never-searched / nothing-found verdict is user-facing, so it
            # renders in the UI language (Khmer UI β†’ Khmer message) β€” the
            # hardcoded English constants were why a Khmer UI got an English
            # "I didn't search…" answer.
            if call_count == 0:
                ans = rag_agent.never_searched_message(lang_key)
            elif found_count == 0:
                ans = rag_agent.nothing_found_message(lang_key)
            else:
                ans = str(result)
                # Visual grounding pass: when the visual index has pages
                # relevant to the question (either the ones the agent's OWN
                # `visual_retriever` tool retrieved this run β€” cached β€” or a
                # fresh query), have the SAME model (the RAG chat's own β€” no
                # second VLM in VRAM) verify the agent's draft against the
                # ACTUAL page images. Only attempted when the RAG model is
                # itself multimodal; the stale tool cache is cleared either
                # way.
                visual_images = []
                if visual_retrieval and _rag_model_can_see_images(model_id, provider):
                    visual_images = (kb.consume_visual_tool_hits()
                                     or _visual_grounding_images(user_message))
                else:
                    kb.consume_visual_tool_hits()
                if visual_images:
                    vis_status = ("πŸ–ΌοΈ αž€αŸ†αž–αž»αž„αž•αŸ’αž‘αŸ€αž„αž•αŸ’αž‘αžΆαžαŸ‹αž…αž˜αŸ’αž›αžΎαž™αž‡αžΆαž˜αž½αž™αžšαžΌαž”αž—αžΆαž–αž‘αŸ†αž–αŸαžšβ€¦" if lang_key == "kh"
                                  else "πŸ–ΌοΈ Grounding the answer with page images…")
                    history.append({"role": "assistant", "content": vis_status})
                    yield history, ""
                    history.pop()
                    grounded = _vlm_grounded_answer(
                        user_message,
                        visual_images,
                        context=("A text-search agent drafted this answer from the "
                                 "knowledge base β€” verify it against the page images "
                                 "above and produce the final grounded answer, "
                                 "correcting anything the images contradict:\n\n"
                                 f"{ans}"),
                        model_id=model_id, provider=provider,
                        lang_key=lang_key, n_ctx=n_ctx,
                    )
                    if grounded:
                        ans, vlm_used = grounded, True
            refs = rag_agent.extract_verified_references(ans, sources_used)
            ans = general_agent.strip_trailing_references_section(ans)
            if refs:
                # Same [filename] -> [N] / (filename) -> (N) normalization as
                # the direct path β€” but run AFTER renumbering so the
                # parenthesized markers carry the FINAL sequential numbers
                # (renumber_citations only remaps [digits] brackets, so
                # sanitizing before it would leave (N) parens stale for
                # non-sequential reference numbers).
                used_sources = [(str(n), name, name) for n, name in refs]
                ans, renumbered_refs = general_agent.renumber_citations(ans, used_sources)
                ans = rag_agent.normalize_in_text_citations(
                    ans, [(int(n), name) for n, name, _ in renumbered_refs])
                ref_lines = [f"- [{n}] {name}" for n, name, _ in renumbered_refs]
                ans += f"\n\n<div class=\"sources-block\">\n\n**πŸ“š References:**\n" + "\n".join(ref_lines) + "\n\n</div>"
            export_text = _export_markdown(ans)

        n_tokens = models._estimate_tokens(ans)
        formatted = format_llm_response(ans, lang_key)
        # Surface compaction activity in the footer (see agent_memory.py).
        compacted_n = getattr(agent, "_compaction_count", 0) or 0
        memory_txt = "on" if use_memory else "off"
        if use_memory and compacted_n:
            memory_txt = f"on (compacted {compacted_n}Γ—)"
        # Effective step budget the manager + knowledge_searcher sub-agent
        # actually ran with (model-scaled when the controls are on auto).
        steps_txt = _agent_steps_budget_txt(agent)
        steps_seg = f"Β· {steps_txt} " if steps_txt else ""
        response = (
            formatted +
            agent_streaming._agent_abort_html(lang_key, diag) +
            f"\n<div class=\"response-footer\">⏱ {elapsed:.1f}s{_speed_seg(elapsed, n_tokens)} | model: <code>{model_id}</code> "
            f"({DEVICE.upper()}) | agentic RAG Β· {_agent_mechanism_txt(use_tool_calling)} Β· "
            f"strict grounding (searched {call_count}x) {steps_seg}Β· memory: {memory_txt}"
            + _visual_footer_note(model_id, provider, lang_key, visual_pages,
                                  visual_images, vlm_used)
            + "</div>"
            + _agent_failure_hint(lang_key, diag)
        )
    except Exception as e:
        import traceback
        response = f"❌ {e}\n\n{traceback.format_exc()}"
    yield from _stream_final_text(history, response, export_text)


def chat_vision(user_message: str, uploaded_image, history: list,

                vlm_label: str, use_memory: bool = True,

                lang_key: str = "kh", mmproj_label: str = ""):
    if not user_message.strip() and uploaded_image is None:
        yield history, None, ""
        return
    history = history or []
    history.append({"role": "user", "content": user_message or "(image)"})

    # Immediate status yield so UI updates instantly before VLM processing
    status_msg = "πŸ–ΌοΈ αž€αŸ†αž–αž»αž„αžœαž·αž—αžΆαž‚αžšαžΌαž”αž—αžΆαž–β€¦" if lang_key == "kh" else "πŸ–ΌοΈ Analyzing image…"
    history.append({"role": "assistant", "content": status_msg})
    yield history, None, ""
    history.pop()

    provider = mr.get_saved_provider("vlm")
    vlm_id = mr.resolve_model_id(vlm_label, provider=provider, model_type="vlm")
    n_ctx = mr.get_saved_context_window("vlm")
    ans = None  # plain-markdown answer β€” the .docx export source (set in the success branch)
    mmproj_path = mr.GGUF_VLM_MMPROJ_MAP.get(vlm_id) if not mmproj_label else None
    if mmproj_label and vlm_id:
        candidates = mr.get_mmproj_choices_for_vlm(vlm_id)
        mmproj_path = candidates.get(mmproj_label) or mmproj_path
    try:
        vlm_model, _ = models.get_vlm(vlm_id, mmproj_path=mmproj_path, provider=provider, n_ctx=n_ctx)
        pil_images = []
        if uploaded_image is not None:
            if isinstance(uploaded_image, Image.Image):
                pil_images.append(uploaded_image)
            elif isinstance(uploaded_image, str):
                pil_images.append(Image.open(uploaded_image).convert("RGB"))
        # The Vision tab is FULLY INDEPENDENT of the knowledge base: neither
        # the vector-DB text context (kb.retrieve_context) nor the visual
        # index image retrieval (kb.visual_retrieve) feed the VLM. A model
        # asked to describe an uploaded image used to receive KB chunks /
        # related images alongside it and would answer about that content
        # instead of the image. Only the uploaded image(s) and the
        # conversation-memory window (below) reach the VLM.
        context = ""
        recent = _recent_memory_messages(history[:-1], max_turns=3, model_obj=vlm_model, n_ctx=n_ctx) if use_memory else []
        if recent:
            convo = "\n".join(f"{t['role']}: {t['content']}" for t in recent)
            context = f"Recent conversation:\n{convo}"
        t0  = time.time()
        ans = models.vlm_answer(user_message, pil_images, context=context, model_id=vlm_id, mmproj_path=mmproj_path, lang_key=lang_key, n_ctx=n_ctx)
        elapsed  = time.time() - t0
        n_tokens = models._estimate_tokens(ans)
        formatted = format_llm_response(ans, lang_key)
        response = (
            formatted +
            f"\n<div class=\"response-footer\">⏱ {elapsed:.1f}s{_speed_seg(elapsed, n_tokens)} | VLM: <code>{vlm_id}</code> ({DEVICE.upper()}) | images: {len(pil_images)}</div>"
        )
    except Exception as e:
        import traceback
    for h, exp in _stream_final_text(history, response, _export_markdown(ans)):
        yield h, None, exp


def chat_data(user_message: str, history: list, model_label: str, files: list,

              use_memory: bool = True, lang_key: str = "kh",

              max_steps: Optional[int] = None,

              worker_max_steps: Optional[int] = None,

              execution_timeout: Optional[int] = None):
    """Data Analysis tab β€” the same chat shape as the other tabs: the EDA

    CodeAgent (agents/data_analysis.run_data_analysis) runs against the

    uploaded data files, live agent steps stream as thinking/working

    bubbles, and the final report markdown is the answer bubble (the UI's

    enhance pipeline converts it, exactly like the unwrapped raw-markdown

    answers).



    `files` are temp paths from /api/data/upload; the WS handler deletes

    them after the run. `max_steps` is the manager's step budget and

    `worker_max_steps` the data_worker sub-agent's (both AUTO when None β€”

    the model-scaled defaults apply; a saved per-tab budget is used when

    the payload leaves the field untouched). Yields (history, export) β€”

    export carries the plain report markdown on the final yield only (the

    .docx source)."""
    history = history or []
    # AUTO on the control = the tab's SAVED budget, then the model-scaled
    # default (mirrors the RAG/Deep Research saved-budget plumbing).
    if max_steps is None:
        max_steps = mr.get_saved_agent_steps("data")
    if worker_max_steps is None:
        worker_max_steps = mr.get_saved_sub_agent_steps("data")
    # Same saved-fallback as the other agentic tabs: the payload's explicit
    # per-step code-execution timeout wins; None falls back to the SAVED
    # Data-tab value (the "Exec timeout" preset), else AUTO (the tab's own
    # DATA_EXECUTION_TIMEOUT_DEFAULT inside the worker builder).
    if execution_timeout is None:
        execution_timeout = mr.get_saved_execution_timeout("data")
    # Immediate status yield so the UI updates before agent construction +
    # CSV loading (the run's own first yield comes only once streaming
    # actually starts).
    status_msg = "πŸ“Š αž€αŸ†αž–αž»αž„αžœαž·αž—αžΆαž‚αž‘αž·αž“αŸ’αž“αž“αŸαž™β€¦" if lang_key == "kh" else "πŸ“Š Analyzing data…"
    history.append({"role": "assistant", "content": status_msg})
    yield history, ""
    history.pop()

    from agents import data_analysis  # lazy: heavy pandas/plotly imports

    export_text = ""
    try:
        final = None
        for h, gallery, report_file in data_analysis.run_data_analysis(
            files or [], user_message, model_label, history,
            use_memory=use_memory, lang_key=lang_key,
            max_steps=max_steps, worker_max_steps=worker_max_steps,
            execution_timeout=execution_timeout,
        ):
            if gallery is None:
                # Live agent step β€” the step message the stream appended is
                # this turn's thinking/working bubble.
                yield list(h), ""
            else:
                final = (h, gallery, report_file)
        if final is not None:
            h, _gallery, _report_file = final
            content = (h[-1].get("content") or "") if h else ""
            # Export = the report markdown minus the trailing <hr> footer
            # (and the abort badge on failed runs) β€” the shared tag-strip
            # keeps the .docx clean, never the footer text.
            export_text = _export_markdown(content.split("<hr>")[0])
            yield list(h), export_text
    except Exception as e:  # defensive β€” the WS layer also catches
        history.append({"role": "assistant", "content": f"❌ {e}"})
        yield list(history), ""


def chat_deep_research(user_message: str, history: list, model_label: str, use_memory: bool = True, use_playwright: bool = False, headless: bool = True, manager_max_steps: int = 12, search_max_steps: int = 6, timeout: int = 90, execution_timeout: Optional[int] = None, lang_key: str = "kh", use_tool_calling: bool = True):
    """Deep Research tab"""
    if not user_message.strip():
        yield history, ""
        return
    history = history or []
    history.append({"role": "user", "content": user_message})
    # Immediate status yield so UI updates instantly before agent construction
    status_msg = "πŸ”¬πŸ€– αž€αŸ†αž–αž»αž„αž…αžΆαž”αŸ‹αž•αŸ’αžαžΎαž˜αž€αžΆαžšαžŸαŸ’αžšαžΆαžœαž‡αŸ’αžšαžΆαžœβ€¦" if lang_key == "kh" else "πŸ”¬πŸ€– Starting deep research…"
    history.append({"role": "assistant", "content": status_msg})
    yield history, ""
    history.pop()
    provider = mr.get_saved_provider("dr")
    model_id = mr.resolve_model_id(model_label, provider=provider)
    n_ctx = mr.get_saved_context_window("dr")
    # Persisted step budgets (the per-tab "Manager steps" / "Search steps"
    # controls): the WS payload's explicit values win; None falls back to
    # the saved budgets, else the function's own defaults (12 / 6).
    manager_max_steps = manager_max_steps if manager_max_steps is not None else mr.get_saved_agent_steps("dr")
    search_max_steps = search_max_steps if search_max_steps is not None else mr.get_saved_sub_agent_steps("dr")
    # Per-step code-execution timeout (the DrControls "Exec timeout" field
    # in agentic mode): the payload's explicit value wins; None falls back
    # to the saved per-tab value, else AUTO (the agent factory's default).
    # DISTINCT from the whole-run `timeout` above β€” that one is the run
    # deadline, enforced at the WS stream layer (web_api._run_stream), and
    # is deliberately NOT threaded into the agent builders here (a wall-
    # clock run budget must not double as a per-step executor cap).
    # `timeout` is kept in the signature for backward compatibility with
    # callers that pass it (it no longer affects agent construction).
    execution_timeout = execution_timeout if execution_timeout is not None else mr.get_saved_execution_timeout("dr")
    export_text = None  # plain-markdown answer for .docx export (set when the run produced one)
    try:
        agent = deep_research_agent.get_deep_research_agent(
            model_id, use_playwright, headless, manager_max_steps, search_max_steps,
            execution_timeout, use_tool_calling=use_tool_calling, provider=provider, n_ctx=n_ctx)
        deep_research_agent.reset_tool_usage()
        t0     = time.time()
        # reset=False keeps the manager's own memory (its steps include
        # every call it made to web_search_agent) across turns β€” same
        # smolagents pattern as every other agentic tab. Capped right
        # after so a long research conversation doesn't grow the prompt
        # unboundedly turn after turn.
        #
        # Wrapped with a per-task citation reminder (NOT just the raw
        # user_message) for the same reason as chat_general_agentic()
        # above: DEEP_RESEARCH_INSTRUCTIONS' citation requirement only
        # reaches the manager if this smolagents version's CodeAgent
        # accepts `instructions=` β€” on a version where it doesn't, this
        # is the only place the requirement is ever stated.
        task = deep_research_agent.build_task_with_citation_reminder(user_message, lang_key)
        # See chat_general_direct()'s matching comment β€” a no-op unless
        # the "🧠 Enable Model Reasoning" toggle is off. This is the tab
        # most likely to benefit: a heavy thinking-tuned manager model
        # (e.g. Gemma-4-26B-A4B) burning its whole MAX_NEW_TOKENS budget
        # on internal reasoning is exactly what produces the "Executing
        # parsed code:" steps with an EMPTY body / Out: None seen in
        # practice on this tab.
        task = mr.apply_reasoning_toggle(task)
        # Live step streaming β€” the manager's OWN steps stream (its
        # thought/code, and each call it makes to the `web_search_agent`
        # sub-agent shows up as a tool-call-shaped line with that call's
        # returned text as the "output"). The search sub-agent's own
        # internal steps don't stream separately β€” deep_research_agent.py's
        # managed_agents mechanism runs it as one synchronous Python call
        # from inside the manager's executed code, same as smolagents
        # itself β€” but seeing each delegated sub-question and what it
        # found, live, is already a large improvement over a single
        # "thinking…" line for however many minutes the whole multi-step
        # research run takes (see MANAGER_DEFAULT_MAX_STEPS's comment in
        # deep_research_agent.py).
        # Token-budget-aware memory compaction (see agent_memory.py) β€” same
        # reasoning as chat_general_agentic(); Deep Research turns are the
        # heaviest (manager + sub-agent calls), so it defaults to one recent
        # turn kept verbatim (tunable in Settings) and the fixed turn-cap
        # below stays as the post-run safety net.
        if use_memory and _maybe_compact_agent_memory(agent, model_id, lang_key, tab_key="dr"):
            history.append({"role": "assistant", "content": _compaction_status_msg(lang_key)})
            yield history, ""
            history.pop()
        result = None
        diag = None  # snapshot from the stream's final yield (every stream path ends with one); stays None only if the loop never ran
        for step_msg, is_final, final_output, diag in agent_streaming.stream_agent_steps(agent, task, reset=not use_memory, lang_key=lang_key):
            if not is_final:
                if step_msg is not None:
                    history.append(step_msg)
                    yield history, ""
                continue
            result = final_output
        if use_memory:
            agent_memory.cap_agent_memory(agent, max_turns=DEEP_RESEARCH_MEMORY_TURNS)
        elapsed = time.time() - t0

        turn_count = sum(1 for s in agent.memory.steps if s.__class__.__name__ == "TaskStep")
        ans = str(result)
        n_tokens = models._estimate_tokens(ans)
        # Same verified-sources approach as General Chat's agentic mode β€”
        # reuses general_agent's own citation-checking helpers rather than
        # duplicating that logic, since they're generic string/list
        # functions with no dependency on general_agent's own tool state.
        queries, urls, links = deep_research_agent.get_tool_usage()
        used_sources = general_agent.resolve_actually_used_sources(ans, urls, links)
        ans = general_agent.strip_trailing_references_section(ans)
        if used_sources:
            ans, used_sources = general_agent.renumber_citations(ans, used_sources)
            # Same in-text [URL] / [page-title] -> [N] normalization as the
            # RAG paths: the manager is told to cite with bare numbers, but
            # small local models often paste the whole source URL or page
            # title into the bracket instead. The renumbered refs are
            # (num, title, url) tuples, so a bracket containing EITHER the
            # title OR the URL resolves to the source's final number.
            ans = rag_agent.normalize_in_text_citations(ans, used_sources)
            ref_lines = ["**πŸ”— Sources used for this report:**"]
            for num, title, url in used_sources:
                link_str = f"[{title}]({url})" if title != url else url
                ref_lines.append(f"- [{num}] {link_str}")
            ans += f"\n\n<div class=\"sources-block\">\n\n" + "\n".join(ref_lines) + "\n\n</div>"
        export_text = _export_markdown(ans)
        formatted = format_llm_response(ans, lang_key)
        # Surface compaction activity in the footer (see agent_memory.py).
        compacted_n = getattr(agent, "_compaction_count", 0) or 0
        memory_txt = "off"
        if use_memory:
            memory_txt = f"on ({turn_count} turn(s))"
            if compacted_n:
                memory_txt = f"on ({turn_count} turn(s), compacted {compacted_n}Γ—)"
        # Effective step budgets the manager + web_search_agent sub-agent
        # actually ran with (model-scaled when the controls are on auto).
        steps_txt = _agent_steps_budget_txt(agent)
        steps_seg = f"Β· {steps_txt} " if steps_txt else ""
        response = (
            formatted +
            agent_streaming._agent_abort_html(lang_key, diag) +
            f"\n<div class=\"response-footer\">⏱ {elapsed:.1f}s{_speed_seg(elapsed, n_tokens)} | model: <code>{model_id}</code> "
            f"({DEVICE.upper()}) | deep research Β· {_agent_mechanism_txt(use_tool_calling)} Β· "
            f"manager + web-search sub-agent {steps_seg}Β· memory: {memory_txt}</div>"
            + _agent_failure_hint(lang_key, diag)
        )
    except Exception as e:
        import traceback
        response = f"❌ {e}\n\n{traceback.format_exc()}"
    yield from _stream_final_text(history, response, export_text)