Spaces:
Runtime error

File size: 64,529 Bytes
ed86a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Session runner and event streaming utilities."""

from __future__ import annotations

import asyncio
import json
import os
import threading
import time
from collections import deque
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from uuid import UUID

from sqlalchemy import text
from sqlalchemy.exc import OperationalError

from src.api.supabase_storage import SupabaseStorageManager, is_sb_ref
from src.core.ai_client import (
    SESSION_PROMPT_CONFIG_KEY,
    AIClient,
    get_ai_client_from_env,
    get_effective_session_prompt,
    get_evaluator_client_from_env,
)
from src.core.rag_evaluator import RAGEvaluator
from src.core.test_engine import TestEngine
from src.core.tone_evaluator import ToneEvaluator
from src.core.turn_evaluator import TurnEvaluator
from src.db import BotRepository, PersonaRepository, ScenarioRepository, SessionRepository, get_db
from src.models import SessionStatus
from src.utils.env import env_bool, env_int
from src.utils.logging import get_logger

logger = get_logger(__name__)


class SessionEventBus:
    """In-memory pub/sub for session events."""

    # Terminal statuses that trigger scheduled cleanup of the event history.
    _TERMINAL_STATUSES = frozenset(
        {
            "completed",
            "passed",
            "failed",
            "cancelled",
            "manual_completed",
            "completed_in_scope_pass",
            "completed_in_scope_fail",
            "completed_out_of_scope_fallback_pass",
            "completed_out_of_scope_fallback_fail",
            "completed_mixed",
        }
    )

    def __init__(self) -> None:
        self._subscribers: Dict[str, List[Tuple[asyncio.Queue, asyncio.AbstractEventLoop]]] = {}
        # 2000 default copre ~100 turni × ~15 eventi/turno con margine; trascurabile come RAM.
        replay_limit = os.getenv("SESSION_EVENT_REPLAY_LIMIT", "2000")
        try:
            self._history_limit = max(0, int(replay_limit))
        except ValueError:
            self._history_limit = 2000
        self._history: Dict[str, deque[Dict[str, Any]]] = {}
        self._cleanup_timers: Dict[str, threading.Timer] = {}
        self._lock = threading.Lock()

    async def subscribe(self, session_id: str, replay_last: Optional[int] = None) -> asyncio.Queue:
        queue: asyncio.Queue = asyncio.Queue()
        loop = asyncio.get_running_loop()
        history: List[Dict[str, Any]] = []
        with self._lock:
            self._subscribers.setdefault(session_id, []).append((queue, loop))
            if self._history_limit > 0:
                history = list(self._history.get(session_id, []))

        if replay_last is not None:
            if replay_last <= 0:
                history = []
            else:
                history = history[-replay_last:]
        for event in history:
            queue.put_nowait(dict(event))
        return queue

    def unsubscribe(self, session_id: str, queue: asyncio.Queue) -> None:
        with self._lock:
            subscribers = self._subscribers.get(session_id, [])
            self._subscribers[session_id] = [
                (q, loop) for (q, loop) in subscribers if q is not queue
            ]
            if not self._subscribers[session_id]:
                self._subscribers.pop(session_id, None)

    def publish(self, session_id: str, event: Dict[str, Any]) -> None:
        event_copy = dict(event)
        with self._lock:
            if self._history_limit > 0:
                history = self._history.setdefault(
                    session_id, deque(maxlen=self._history_limit)
                )
                history.append(event_copy)
            subscribers = list(self._subscribers.get(session_id, []))

        for queue, loop in subscribers:
            loop.call_soon_threadsafe(queue.put_nowait, dict(event_copy))

        # On terminal events, schedule cleanup of the in-memory history so
        # long-running processes don't accumulate per-session buffers.
        # The retention window gives reconnecting clients time to fetch the
        # final replay; 0 disables auto-cleanup.
        if event_copy.get("type") == "status" and event_copy.get("status") in self._TERMINAL_STATUSES:
            try:
                retention_sec = int(os.getenv("SESSION_EVENT_RETENTION_SEC", "3600"))
            except (TypeError, ValueError):
                retention_sec = 3600
            if retention_sec > 0:
                self._schedule_history_cleanup(session_id, retention_sec)

    def _schedule_history_cleanup(self, session_id: str, delay_sec: int) -> None:
        """Schedule a one-shot cleanup of this session's event history."""
        with self._lock:
            existing = self._cleanup_timers.pop(session_id, None)
        if existing is not None:
            try:
                existing.cancel()
            except Exception:
                pass

        def _cleanup() -> None:
            with self._lock:
                self._history.pop(session_id, None)
                self._cleanup_timers.pop(session_id, None)
            try:
                logger.info(
                    "session_event_history_cleaned",
                    extra={"session_id": session_id, "delay_sec": delay_sec},
                )
            except Exception:
                pass

        timer = threading.Timer(float(delay_sec), _cleanup)
        timer.daemon = True
        with self._lock:
            self._cleanup_timers[session_id] = timer
        timer.start()

    def get_recent_events(self, session_id: str, limit: int = 200) -> List[Dict[str, Any]]:
        """Return a copy of recent events for a session."""
        bounded_limit = max(0, int(limit or 0))
        with self._lock:
            events = list(self._history.get(session_id, []))
        if bounded_limit == 0:
            return []
        return [dict(item) for item in events[-bounded_limit:]]

    def get_runtime_snapshot(self, session_id: str) -> Dict[str, Any]:
        """Build a lightweight runtime snapshot from replayable events."""
        events = self.get_recent_events(session_id, limit=300)
        if not events:
            return {}

        def _to_iso(ts: Any) -> Optional[str]:
            if ts is None:
                return None
            try:
                numeric = float(ts)
                if numeric > 1_000_000_000_000:
                    numeric = numeric / 1000.0
                return datetime.fromtimestamp(numeric).isoformat()
            except Exception:
                text = str(ts).strip()
                return text or None

        status = None
        current_scenario = None
        current_turn = 0
        last_event_at = None
        last_screenshot = None
        last_logs: List[str] = []

        for event in events:
            last_event_at = _to_iso(event.get("ts")) or last_event_at

            event_type = str(event.get("type") or "").strip().lower()
            if event_type == "status":
                status = str(event.get("status") or "").strip().lower() or status
            elif event_type == "progress":
                scenario_label = str(event.get("scenario") or "").strip()
                persona_label = str(event.get("persona") or "").strip()
                if scenario_label and persona_label:
                    current_scenario = f"{scenario_label} · {persona_label}"
                elif scenario_label:
                    current_scenario = scenario_label
            elif event_type == "chat" and str(event.get("sender") or "").strip().lower() == "bot":
                current_turn += 1
            elif event_type == "screenshot":
                screenshot = str(
                    event.get("url") or event.get("path") or event.get("image") or ""
                ).strip()
                if screenshot:
                    last_screenshot = screenshot
            elif event_type == "log":
                message = str(event.get("message") or "").strip()
                if message:
                    last_logs.append(message)
                    if len(last_logs) > 3:
                        last_logs = last_logs[-3:]

        if status in {"running", "stopping"}:
            if current_scenario:
                live_summary = f"In corso · {current_scenario} · Turno {current_turn}"
            else:
                live_summary = f"In corso · Turno {current_turn}"
        elif status:
            live_summary = f"Stato sessione: {status}"
        else:
            live_summary = "Sessione in inizializzazione"

        return {
            "status": status,
            "current_turn": current_turn,
            "current_scenario": current_scenario,
            "last_event_at": last_event_at,
            "live_summary": live_summary,
            "last_screenshot": last_screenshot,
            "last_logs": last_logs,
        }


class SessionRunner:
    """Runs sessions in background threads and emits events."""

    def __init__(self, event_bus: SessionEventBus) -> None:
        self._event_bus = event_bus
        self._threads: Dict[str, threading.Thread] = {}
        self._stop_events: Dict[str, threading.Event] = {}
        self._lock = threading.Lock()

    def start(self, session_id: UUID) -> bool:
        session_key = str(session_id)
        with self._lock:
            existing = self._threads.get(session_key)
            if existing and existing.is_alive():
                return False
            self._stop_events[session_key] = threading.Event()

            thread = threading.Thread(
                target=self._run_session,
                args=(session_key,),
                daemon=True,
            )
            self._threads[session_key] = thread
            thread.start()
            return True

    def stop(self, session_id: UUID) -> bool:
        """Request graceful stop for a running session."""
        session_key = str(session_id)
        with self._lock:
            event = self._stop_events.get(session_key)
            thread = self._threads.get(session_key)
            is_running = bool(thread and thread.is_alive())
            if not event:
                return False
            event.set()

        self._event_bus.publish(session_key, {
            "type": "status",
            "status": "stopping",
            "session_id": session_key,
            "ts": int(time.time() * 1000),
        })
        self._event_bus.publish(session_key, {
            "type": "log",
            "level": "warning",
            "message": "Stop requested. Waiting for current action to finish...",
            "session_id": session_key,
            "ts": int(time.time() * 1000),
        })
        return is_running

    def is_running(self, session_id: UUID | str) -> bool:
        session_key = str(session_id)
        with self._lock:
            thread = self._threads.get(session_key)
            return bool(thread and thread.is_alive())

    def recover_orphan_sessions(self) -> int:
        """Finalize sessions left in RUNNING after a process restart.

        Why this exists:
            Each session runs in a `daemon=True` thread. When the Python
            process is killed (Render redeploy, OOM, manual restart), the
            thread dies but the DB row stays in `running` forever — there's
            no auto-resume. This method runs at lifespan startup to:

              1. Find all sessions with status == RUNNING.
              2. Skip those whose worker thread is still alive in this
                 process (shouldn't happen at boot, but defensive).
              3. For each orphan: mark associated TestResult rows that are
                 still `in_progress` as `failed` with a clear reason, so
                 the UI doesn't show ghost in-flight scenarios.
              4. Mark the TestSession itself as `failed` with
                 `error_message='process_restart_recovered'` and a
                 `metadata.crash_recovery=True` flag.

        Why mark-as-failed instead of resume:
            Resuming a Playwright + AI test session mid-run is brittle —
            we'd need to recreate the browser, the conversation history,
            the AI client mid-token. The chunks committed turn-by-turn
            cover progress; the operator can re-launch the session for
            the remaining scenarios manually. See docs/known-follow-ups.md
            section "Test session recovery — option B (resume)" for the
            future enhancement plan.

        Idempotent: safe to call multiple times. Returns the number of
        sessions finalized.
        """
        recovered = 0
        try:
            db = get_db()
            with db.get_session() as session:
                repo = SessionRepository(session)
                # `list_sessions(status=...)` filter not exposed; pull all
                # then filter — sessions table is bounded, low cost.
                sessions = repo.list_sessions()
                orphan_sessions = [
                    s for s in sessions if s.status == SessionStatus.RUNNING
                ]
                if not orphan_sessions:
                    return 0
                with self._lock:
                    in_flight = set(self._threads.keys())
                for ts in orphan_sessions:
                    sid = str(ts.id)
                    if sid in in_flight and self._threads[sid].is_alive():
                        # Worker still running in THIS process — leave alone.
                        continue
                    # 1) Mark in-progress TestResults as failed.
                    try:
                        results = repo.get_session_results(ts.id)
                    except Exception:
                        results = []
                    failed_results = 0
                    for result in results or []:
                        rstatus = str(getattr(result, "status", "") or "").lower()
                        if rstatus in ("pending", "in_progress", "running"):
                            try:
                                repo.update_result(result.id, {
                                    "status": "failed",
                                    "error_message": "process_restart_recovered",
                                })
                                failed_results += 1
                            except Exception:
                                logger.exception(
                                    "session-recovery: failed to update result",
                                    extra={"session_id": sid, "result_id": str(result.id)},
                                )
                    # 2) Mark the session as failed. Tag the recovery in
                    # `config` (JSON) so the UI / reports can distinguish a
                    # crash-recovered session from a real test failure.
                    # 2026-05-17: aggiunto calcolo verdict dai turn parziali
                    # già persistiti — prima di questo fix le session
                    # crash-recovered dopo container restart (frequente su
                    # HF Space free tier) mostravano AIS "—" nella tabella
                    # anche con N turn validi nel conversation_log. Adesso
                    # l'operatore vede subito i risultati parziali.
                    update_payload: Dict[str, Any] = {
                        "status": SessionStatus.FAILED.value,
                        "error_message": (
                            "process_restart_recovered: la sessione era "
                            "in esecuzione quando il processo è stato "
                            "riavviato. I turni completati prima del "
                            "riavvio sono preservati."
                        ),
                        "completed_at": datetime.now(),
                    }
                    try:
                        verdict_fields = self._compute_verdict_fields_from_logs(
                            repo, sid
                        )
                        if verdict_fields:
                            update_payload.update(verdict_fields)
                    except Exception:
                        logger.exception(
                            "session-recovery: verdict computation failed (best-effort)",
                            extra={"session_id": sid},
                        )
                    try:
                        config = dict(getattr(ts, "config", None) or {})
                        config["crash_recovery"] = True
                        config["recovered_at"] = datetime.now().isoformat()
                        update_payload["config"] = config
                        repo.update_session(ts.id, update_payload)
                        session.commit()
                        logger.info(
                            "session-recovery: marked orphan session as failed",
                            extra={
                                "session_id": sid,
                                "results_failed": failed_results,
                            },
                        )
                        recovered += 1
                    except Exception:
                        session.rollback()
                        logger.exception(
                            "session-recovery: update_session failed",
                            extra={"session_id": sid},
                        )
        except Exception as exc:
            # Most common cause on a fresh install: the test_sessions table
            # doesn't exist yet (init_db hasn't run for some reason). Log
            # at debug + return 0 instead of stack-tracing — startup must
            # not fail just because there are no sessions to recover.
            msg = str(exc).lower()
            if "no such table" in msg or "does not exist" in msg or "undefinedtable" in msg:
                logger.debug(
                    "session-recovery: skipped (tables not ready yet): %s",
                    str(exc)[:200],
                )
            else:
                logger.exception("session-recovery: top-level failure (non-fatal)")
        return recovered

    def _run_session(self, session_id: str) -> None:
        output_root = Path("./output").resolve()
        with self._lock:
            stop_event = self._stop_events.get(session_id)

        def should_stop() -> bool:
            return bool(stop_event and stop_event.is_set())

        def emit(event: Dict[str, Any]) -> None:
            if "ts" not in event:
                event["ts"] = int(time.time() * 1000)
            event.setdefault("session_id", session_id)

            path = event.pop("path", None)
            if path:
                event["url"] = self._to_output_url(output_root, path)

            self._event_bus.publish(session_id, event)

        def _scenario_goal_text(scenario: Any) -> str:
            description = str(getattr(scenario, "description", "") or "").strip()
            if description:
                return description
            success_criteria = getattr(scenario, "success_criteria", None)
            expected_intent = (
                str(getattr(success_criteria, "expected_intent", "") or "").strip()
                if success_criteria
                else ""
            )
            if expected_intent:
                return expected_intent
            return f"Complete scenario '{getattr(scenario, 'name', 'scenario')}'."

        def _build_group_prompt(persona: Any, scenarios: List[Any]) -> str:
            scenario_overview = []
            for idx, scenario in enumerate(list(scenarios or [])[:12], start=1):
                scenario_overview.append(
                    f"{idx}. {getattr(scenario, 'name', f'Scenario {idx}')}: {_scenario_goal_text(scenario)}"
                )
            if len(scenarios or []) > 12:
                scenario_overview.append(
                    f"... plus {len(scenarios) - 12} additional scenario(s) in this run."
                )
            return AIClient.build_persona_system_prompt(
                persona=persona,
                scenario_overview=scenario_overview,
            )

        def log(message: str, level: str = "info") -> None:
            emit({"type": "log", "level": level, "message": message})

        log("Session runner started")

        storage_mgr = SupabaseStorageManager.from_env()
        uploaded_local: Dict[str, str] = {}
        storage_initialized = False

        def _resolve_local_artifact(value: Optional[str]) -> Optional[Path]:
            if not value:
                return None
            raw = str(value).strip()
            if not raw or is_sb_ref(raw) or raw.startswith("http://") or raw.startswith("https://"):
                return None

            # `/output/...` is a URL path. Map back to the local artifact directory.
            if raw.startswith("/output/"):
                candidate = output_root / raw[len("/output/") :]
                if candidate.exists():
                    return candidate

            # If an absolute/relative filesystem path exists, use it directly.
            direct = Path(raw)
            if direct.exists():
                return direct

            # If we have an absolute path that contains `/output/`, map to output_root.
            marker = "/output/"
            idx = raw.find(marker)
            if idx >= 0:
                candidate = output_root / raw[idx + len(marker) :]
                if candidate.exists():
                    return candidate

            return None

        def _persist_artifact(value: Optional[str], result_id: str) -> Optional[str]:
            nonlocal storage_initialized
            if not value:
                return value
            raw = str(value).strip()
            if not raw or is_sb_ref(raw) or not storage_mgr:
                return value

            local_file = _resolve_local_artifact(raw)
            if not local_file:
                return value

            # Live preview is overwritten constantly; don't persist it as evidence.
            if local_file.name.lower().startswith("live."):
                return value

            local_key = str(local_file.resolve())
            if local_key in uploaded_local:
                return uploaded_local[local_key]

            if not storage_initialized:
                try:
                    storage_mgr.ensure_bucket()
                    storage_initialized = True
                except Exception as e:
                    log(f"Supabase Storage not available (screenshots will stay local): {e}", "warning")
                    return value

            object_path = f"sessions/{session_id}/results/{result_id}/{local_file.name}"
            try:
                ref = storage_mgr.upload_file(local_file, object_path)
            except Exception as e:
                log(f"Failed to upload screenshot to Supabase Storage: {e}", "warning")
                return value

            uploaded_local[local_key] = ref
            return ref

        def _persist_result_artifacts(result: Any) -> None:
            if not storage_mgr:
                return

            result_id = str(getattr(result, "id", "")) or "unknown"

            # result.screenshot_urls
            try:
                urls = list(getattr(result, "screenshot_urls", []) or [])
                if urls:
                    result.screenshot_urls = [_persist_artifact(u, result_id) for u in urls if u]
            except Exception:
                pass

            # steps_results[*].screenshot
            try:
                for step in getattr(result, "steps_results", []) or []:
                    if isinstance(step, dict) and step.get("screenshot"):
                        step["screenshot"] = _persist_artifact(step.get("screenshot"), result_id)
            except Exception:
                pass

            # scenario_results[*].turns[*].screenshot
            try:
                scenario_map = getattr(result, "scenario_results", None)
                if isinstance(scenario_map, dict):
                    for scenario in scenario_map.values():
                        turns = scenario.get("turns") if isinstance(scenario, dict) else None
                        if not isinstance(turns, list):
                            continue
                        for turn in turns:
                            if isinstance(turn, dict) and turn.get("screenshot"):
                                turn["screenshot"] = _persist_artifact(turn.get("screenshot"), result_id)
            except Exception:
                pass

            # conversation_log JSON string (optional; keeps traceability consistent)
            try:
                conv = getattr(result, "conversation_log", None)
                if not conv:
                    return
                data = json.loads(conv)
                changed = False
                if isinstance(data, list):
                    for turn in data:
                        if not isinstance(turn, dict) or not turn.get("screenshot"):
                            continue
                        new_val = _persist_artifact(turn.get("screenshot"), result_id)
                        if new_val != turn.get("screenshot"):
                            turn["screenshot"] = new_val
                            changed = True
                if changed:
                    result.conversation_log = json.dumps(data, ensure_ascii=False, default=str)
            except Exception:
                pass

        try:
            # Initialize AI client based on configuration
            try:
                ai_client = get_ai_client_from_env()
                log(f"AI Provider: {os.getenv('AI_PROVIDER', 'kimi')}")
            except ValueError as e:
                log(f"AI configuration error: {e}", "error")
                self._mark_failed(session_id, str(e))
                emit({"type": "status", "status": SessionStatus.FAILED.value})
                return

            is_render = bool(
                os.getenv("RENDER")
                or os.getenv("RENDER_SERVICE_ID")
                or os.getenv("RENDER_EXTERNAL_HOSTNAME")
                or os.getenv("RENDER_INSTANCE_ID")
            )
            headless = env_bool("BROWSER_HEADLESS", default=is_render)
            log(f"Browser: headless={headless}")

            db = get_db()
            with db.get_session() as db_session:
                session_repo = SessionRepository(db_session)
                bot_repo = BotRepository(db_session)
                scenario_repo = ScenarioRepository(db_session)
                persona_repo = PersonaRepository(db_session)

                session = session_repo.get_session(UUID(session_id))
                if not session:
                    log(f"Session not found: {session_id}", "error")
                    return

                # Apply optional per-session model overrides (temperature, max_tokens, top_p).
                try:
                    session_config = getattr(session, "config", None) or {}
                    overrides = (
                        session_config.get("model_overrides")
                        if isinstance(session_config, dict)
                        else None
                    ) or {}
                    if overrides:
                        applied = {}
                        if "temperature" in overrides and overrides["temperature"] is not None:
                            ai_client.temperature = float(overrides["temperature"])
                            applied["temperature"] = ai_client.temperature
                        if "max_tokens" in overrides and overrides["max_tokens"] is not None:
                            ai_client.max_tokens = int(overrides["max_tokens"])
                            applied["max_tokens"] = ai_client.max_tokens
                        if "top_p" in overrides and overrides["top_p"] is not None:
                            setattr(ai_client, "top_p", float(overrides["top_p"]))
                            applied["top_p"] = overrides["top_p"]
                        if applied:
                            log(f"Session model overrides applied: {applied}")
                except Exception as exc:  # pragma: no cover - defensive
                    log(f"Could not apply session model overrides: {exc}", "warning")

                bot = bot_repo.get_by_id(session.bot_id)
                if not bot:
                    log("Bot not found for session", "error")
                    session_repo.update_session(UUID(session_id), {
                        "status": SessionStatus.FAILED.value,
                        "error_message": "Bot not found",
                    })
                    db_session.commit()
                    emit({"type": "status", "status": SessionStatus.FAILED.value})
                    return

                pairs = self._get_session_pairs(db_session, session_id, bot.id, scenario_repo, persona_repo, log)
                if not pairs:
                    log("No scenarios/personas linked to this session.", "error")
                    session_repo.update_session(UUID(session_id), {
                        "status": SessionStatus.FAILED.value,
                        "error_message": "No scenarios/personas linked",
                    })
                    db_session.commit()
                    emit({"type": "status", "status": SessionStatus.FAILED.value})
                    return

                # Backfill session-level prompt for legacy sessions.
                session_config = dict(getattr(session, "config", None) or {})
                if not get_effective_session_prompt(session_config):
                    first_persona = pairs[0][1]
                    scenario_overview: List[str] = []
                    seen_scenarios: List[str] = []
                    seen_ids = set()
                    for scenario, _ in pairs:
                        sid = str(getattr(scenario, "id", "") or "")
                        if sid in seen_ids:
                            continue
                        seen_ids.add(sid)
                        seen_scenarios.append(sid)

                        name = str(getattr(scenario, "name", "Scenario") or "Scenario").strip()
                        goal = str(getattr(scenario, "description", "") or "").strip()
                        if not goal:
                            success_criteria = getattr(scenario, "success_criteria", None)
                            goal = (
                                str(getattr(success_criteria, "expected_intent", "") or "").strip()
                                if success_criteria
                                else ""
                            )
                        if not goal:
                            goal = f"Complete scenario '{name}'."
                        scenario_overview.append(f"{len(scenario_overview)+1}. {name}: {goal}")

                    session_config[SESSION_PROMPT_CONFIG_KEY] = {
                        "generated_prompt": AIClient.build_persona_system_prompt(
                            persona=first_persona,
                            scenario_overview=scenario_overview,
                        ),
                        "generated_at": datetime.now().isoformat(),
                        "persona_id": str(getattr(first_persona, "id", "") or ""),
                        "scenario_ids": seen_scenarios,
                    }
                    updated_session = session_repo.update_session(
                        UUID(session_id),
                        {"config": session_config},
                    )
                    if updated_session:
                        session = updated_session
                    log("Session prompt generated at runtime for this run.")

                total_tests = len(pairs)
                session_repo.update_session(UUID(session_id), {
                    "status": SessionStatus.RUNNING.value,
                    "started_at": datetime.now(),
                    "total_tests": total_tests,
                    "passed": 0,
                    "failed": 0,
                    "messages_sent": 0,
                })
                db_session.commit()

                emit({"type": "status", "status": SessionStatus.RUNNING.value, "total_tests": total_tests})
                log(f"Starting session with {total_tests} test(s).")

                rag_eval = RAGEvaluator(ai_client)
                tone_eval = ToneEvaluator(ai_client)
                # Dialogic per-turn evaluator. Default ON so every turn gets an
                # AIS / intent verdict; disable only for lightweight smoke runs.
                # `LIVE_JUDGE_ENABLED` (post-session branch) vince su
                # `ENABLE_TURN_EVALUATOR` (legacy). Quando il post-session
                # judge è attivo (default su questo branch), il TurnEvaluator
                # inline è disattivato → il judge gira batch a fine sessione
                # via `_run_session_judge_sync`.
                live_judge_raw = os.getenv("LIVE_JUDGE_ENABLED")
                if live_judge_raw is not None:
                    turn_eval_enabled = live_judge_raw.strip().lower() in {"1", "true", "yes", "on"}
                else:
                    turn_eval_enabled = env_bool("ENABLE_TURN_EVALUATOR", True)
                turn_eval = None
                if turn_eval_enabled:
                    try:
                        evaluator_client = get_evaluator_client_from_env()
                    except ValueError as exc:
                        log(f"Evaluator client config error: {exc}", "error")
                        evaluator_client = ai_client
                    is_dedicated = evaluator_client is not ai_client
                    turn_eval = TurnEvaluator(evaluator_client)
                    if is_dedicated:
                        log(
                            f"TurnEvaluator enabled with dedicated judge model "
                            f"({getattr(evaluator_client, 'model', 'unknown')})."
                        )
                    else:
                        log(
                            "TurnEvaluator enabled but reusing the generator AI client "
                            "(no EVALUATOR_* env vars). For higher-quality AIS labels, "
                            "configure a dedicated judge (e.g. EVALUATOR_PROVIDER=anthropic, "
                            "EVALUATOR_MODEL=claude-sonnet-4-6).",
                            "warning",
                        )
                else:
                    log(
                        "TurnEvaluator disabled (ENABLE_TURN_EVALUATOR=false). "
                        "Turns will not carry an AIS verdict.",
                        "warning",
                    )
                base_prompt_override = get_effective_session_prompt(getattr(session, "config", None))
                if base_prompt_override:
                    log("Using session-level AI tester prompt override.")

                output_dir = output_root / session_id
                output_dir.mkdir(parents=True, exist_ok=True)
                
                # Create a callback to save intermediate results
                def save_intermediate_result(result):
                    """Save partial results to database during test execution.

                    Retries solo su OperationalError (connection blip / pool issue).
                    Altre eccezioni si comportano come prima: log + continue.
                    """
                    import logging
                    save_logger = logging.getLogger(__name__)
                    save_logger.info(f"save_intermediate_result called: session_id={result.session_id}, steps={len(result.steps_results) if result.steps_results else 0}")

                    max_retries = max(1, env_int("INTERMEDIATE_SAVE_MAX_RETRIES", 3))
                    base_ms = max(0, env_int("INTERMEDIATE_SAVE_RETRY_BASE_MS", 500))

                    for attempt in range(max_retries):
                        try:
                            db = get_db()
                            with db.get_session() as save_session:
                                save_repo = SessionRepository(save_session)
                                # Light lookup: solo l'id, evita SELECT * con
                                # conversation_log MB-size. Fix egress round 6.
                                existing_id = save_repo.get_result_id_by_session_and_scenario(
                                    result.session_id, result.scenario_id, result.persona_id
                                )
                                if existing_id:
                                    save_logger.info(f"Updating existing result: {existing_id}")
                                    save_repo.update_result(existing_id, {
                                        "conversation_log": result.conversation_log,
                                        "scenario_results": result.scenario_results,
                                        "steps_results": result.steps_results,
                                        "screenshot_urls": result.screenshot_urls,
                                        "total_steps": result.total_steps,
                                        "passed_steps": result.passed_steps,
                                        "failed_steps": result.failed_steps,
                                        "status": "in_progress" if result.status == "pending" else result.status,
                                    })
                                else:
                                    save_logger.info(f"Creating new result for session={result.session_id}")
                                    original_status = result.status
                                    if result.status == "pending":
                                        result.status = "in_progress"
                                    save_repo.add_result(result)
                                    result.status = original_status
                                save_session.commit()
                                save_logger.info(f"Saved intermediate result: {len(result.conversation_log or '')} chars, {len(result.steps_results or [])} steps")
                            return
                        except OperationalError as e:
                            if attempt >= max_retries - 1:
                                save_logger.error(
                                    "intermediate_save_failed_after_retries",
                                    extra={"attempts": attempt + 1, "error": str(e)[:240]},
                                )
                                log(f"Failed to save intermediate result after {attempt + 1} attempts: {e}", "warning")
                                return
                            backoff_sec = (base_ms / 1000.0) * (2 ** attempt)
                            save_logger.warning(
                                "intermediate_save_retry",
                                extra={"attempt": attempt + 1, "backoff_sec": backoff_sec, "error": str(e)[:240]},
                            )
                            time.sleep(backoff_sec)
                        except Exception as e:
                            save_logger.error(f"Failed to save intermediate result: {e}")
                            log(f"Failed to save intermediate result: {e}", "warning")
                            return

                engine = TestEngine(
                    ai_client=ai_client,
                    rag_evaluator=rag_eval,
                    tone_evaluator=tone_eval,
                    turn_evaluator=turn_eval,
                    output_dir=str(output_dir),
                    event_handler=emit,
                    stop_requested=should_stop,
                    save_callback=save_intermediate_result,
                    max_messages=(session.max_turns or session.max_messages),
                    persona_system_prompt_override=base_prompt_override,
                )

                # Group pairs by persona - run all scenarios for each persona in one continuous test
                persona_groups: Dict[str, List] = {}
                for scenario, persona in pairs:
                    persona_key = str(persona.id)
                    if persona_key not in persona_groups:
                        persona_groups[persona_key] = {"persona": persona, "scenarios": []}
                    persona_groups[persona_key]["scenarios"].append(scenario)
                
                passed = 0
                failed = 0
                response_times: List[int] = []
                rag_scores: List[float] = []
                tone_scores: List[float] = []
                outcome_counters: Dict[str, int] = {
                    "in_scope_pass": 0,
                    "in_scope_fail": 0,
                    "out_of_scope_fallback_pass": 0,
                    "out_of_scope_fallback_fail": 0,
                }
                cancelled = False
                session_messages_sent = 0
                
                for persona_key, group in persona_groups.items():
                    if should_stop():
                        cancelled = True
                        log("Stop requested. Cancelling session...", "warning")
                        break
                    
                    persona = group["persona"]
                    scenarios = group["scenarios"]
                    engine.persona_system_prompt_override = (
                        base_prompt_override or _build_group_prompt(persona, scenarios)
                    )
                    
                    log(f"Running {len(scenarios)} scenario(s) as {persona.name}")
                    emit({
                        "type": "progress",
                        "scenario": f"{len(scenarios)} scenarios",
                        "persona": persona.name,
                    })
                    
                    # Run all scenarios in one continuous conversation
                    result = engine.run_multi_scenario_test(
                        bot=bot,
                        scenarios=scenarios,
                        persona=persona,
                        session=session,
                        headless=headless,
                    )
                    session_messages_sent += engine.messages_sent_count

                    # Fast-fail su engine-level error (bug 2026-05-17:
                    # session bloccata "In esecuzione" indefinitamente).
                    # Quando l'engine torna result.status == "error"
                    # (es. browser startup failure permanente perché il
                    # bot URL non risponde, errore Playwright, ecc.), il
                    # result è degenere: scenario_id=None, conversation
                    # vuota, scenario_results_map vuoto. Continuare la
                    # logica downstream comporta query DB con scenario_id
                    # nullo, save_result che può fallire silenziosamente,
                    # e nessuna transizione di stato della session →
                    # rimane "running" finché non interviene
                    # recover_orphan_sessions al prossimo restart del
                    # processo. Solleviamo qui così l'outer `except`
                    # finalizza la session come FAILED con motivo chiaro.
                    if result.status == "error":
                        raise RuntimeError(
                            result.error_message
                            or "Test engine reported error status without detail"
                        )

                    if should_stop():
                        cancelled = True
                    
                    if result.avg_response_time_ms is not None:
                        response_times.append(result.avg_response_time_ms)
                    if result.rag_faithfulness_avg is not None:
                        rag_scores.append(result.rag_faithfulness_avg)
                    if result.tone_match_avg is not None:
                        tone_scores.append(result.tone_match_avg)
                    
                    result_scenario_passed = 0
                    result_scenario_failed = 0
                    scenario_results_map = result.scenario_results or {}

                    for scenario_info in scenario_results_map.values():
                        outcome_type = scenario_info.get("outcome_type")
                        if outcome_type in outcome_counters:
                            outcome_counters[outcome_type] += 1

                        if outcome_type and str(outcome_type).endswith("_pass"):
                            result_scenario_passed += 1
                        elif outcome_type and str(outcome_type).endswith("_fail"):
                            result_scenario_failed += 1
                        elif scenario_info.get("completed"):
                            result_scenario_passed += 1
                        else:
                            result_scenario_failed += 1

                    # Legacy fallback when scenario-level outcomes are not available.
                    if (result_scenario_passed + result_scenario_failed) == 0:
                        if result.status == "passed":
                            result_scenario_passed = 1
                        else:
                            result_scenario_failed = 1

                    passed += result_scenario_passed
                    failed += result_scenario_failed
                    
                    self._normalize_result_paths(output_root, result)
                    _persist_result_artifacts(result)
                    
                    # Check if result already exists (might have been created by save_callback).
                    # Light lookup: solo l'id, evita SELECT * con conversation_log MB-size.
                    existing_id = session_repo.get_result_id_by_session_and_scenario(
                        result.session_id, result.scenario_id, result.persona_id
                    )
                    if existing_id:
                        # Update existing result with final data
                        session_repo.update_result(existing_id, {
                            "status": result.status,
                            "conversation_log": result.conversation_log,
                            "scenario_results": result.scenario_results,
                            "steps_results": result.steps_results,
                            "screenshot_urls": result.screenshot_urls,
                            "total_steps": result.total_steps,
                            "passed_steps": result.passed_steps,
                            "failed_steps": result.failed_steps,
                            "avg_response_time_ms": result.avg_response_time_ms,
                            "rag_faithfulness_avg": result.rag_faithfulness_avg,
                            "tone_match_avg": result.tone_match_avg,
                            "error_message": result.error_message,
                            "completed_at": result.completed_at,
                        })
                    else:
                        # Create new result
                        session_repo.add_result(result)
                    
                    session_repo.update_session(UUID(session_id), {
                        "passed": passed,
                        "failed": failed,
                        "messages_sent": session_messages_sent,
                    })
                    db_session.commit()
                    
                    log(
                        (
                            f"Result: {result.status} | scenarios passed={result_scenario_passed} failed={result_scenario_failed}"
                            + (f" | error={result.error_message}" if result.status == "error" and result.error_message else "")
                        ),
                        "success" if result.status == "passed" else "error",
                    )
                    
                    if cancelled:
                        break
                
                avg_response = int(sum(response_times) / len(response_times)) if response_times else None
                avg_rag = sum(rag_scores) / len(rag_scores) if rag_scores else None
                avg_tone = sum(tone_scores) / len(tone_scores) if tone_scores else None

                if cancelled:
                    # Use MANUAL_COMPLETED instead of CANCELLED to preserve data
                    session_repo.update_session(UUID(session_id), {
                        "status": SessionStatus.MANUAL_COMPLETED.value,
                        "completed_at": datetime.now(),
                        "passed": passed,
                        "failed": failed,
                        "messages_sent": session_messages_sent,
                        "avg_response_time_ms": avg_response,
                        "rag_faithfulness_avg": avg_rag,
                        "tone_match_avg": avg_tone,
                        "error_message": "Stopped manually - partial results saved",
                    })
                    db_session.commit()
                    log("Session stopped manually - partial results saved", "warning")
                    emit({"type": "status", "status": SessionStatus.MANUAL_COMPLETED.value, "passed": passed, "failed": failed})
                else:
                    final_status = self._derive_completed_status(outcome_counters, passed, failed)
                    update_payload: Dict[str, Any] = {
                        "status": final_status,
                        "completed_at": datetime.now(),
                        "passed": passed,
                        "failed": failed,
                        "messages_sent": session_messages_sent,
                        "avg_response_time_ms": avg_response,
                        "rag_faithfulness_avg": avg_rag,
                        "tone_match_avg": avg_tone,
                    }
                    # If the AIS Wilson verdict is enabled, compute it now from
                    # the persisted conversation_log so the session row carries
                    # the modern verdict instead of the legacy goal-based one.
                    # The legacy `status` field stays mapped to a "completed_*"
                    # value (never raw "failed", which the UI shows as
                    # "Errore di esecuzione").
                    try:
                        from src.utils.feature_flags import wilson_session_verdict_enabled
                        from src.core.session_verdict import compute_session_verdict

                        if wilson_session_verdict_enabled():
                            results_for_verdict = session_repo.get_session_results(UUID(session_id))
                            verdict_turns: List[Dict[str, Any]] = []
                            for r in results_for_verdict:
                                raw_log = getattr(r, "conversation_log", None)
                                if not raw_log:
                                    continue
                                try:
                                    entries = json.loads(raw_log) if isinstance(raw_log, str) else raw_log
                                except Exception:
                                    continue
                                if not isinstance(entries, list):
                                    continue
                                for entry in entries:
                                    if isinstance(entry, dict):
                                        verdict_turns.append({
                                            "correctness_label": entry.get("correctness_label"),
                                            "human_override_label": None,
                                            "intent_label": entry.get("intent_label"),
                                        })
                            verdict_obj = compute_session_verdict(verdict_turns)
                            update_payload.update({
                                "verdict_label": verdict_obj["verdict"],
                                "verdict_p_hat": verdict_obj["p_hat"],
                                "verdict_lower_bound": verdict_obj["lower_bound"],
                                "verdict_upper_bound": verdict_obj["upper_bound"],
                                "verdict_threshold": verdict_obj["threshold"],
                                "verdict_n": verdict_obj["n"],
                            })
                            # Map AIS verdict → a "completed_*" status so the
                            # UI never shows "Errore di esecuzione" for a
                            # session that actually executed turns.
                            if verdict_turns:
                                if verdict_obj["verdict"] == "passed":
                                    update_payload["status"] = SessionStatus.COMPLETED_IN_SCOPE_PASS.value
                                elif verdict_obj["verdict"] == "failed":
                                    update_payload["status"] = SessionStatus.COMPLETED_IN_SCOPE_FAIL.value
                                else:
                                    # inconclusive → keep the original
                                    # _derive_completed_status (mixed/etc.)
                                    pass
                            log(
                                f"AIS verdict (Wilson 95% CI): {verdict_obj['verdict']} "
                                f"p_hat={verdict_obj['p_hat']:.2f} n={verdict_obj['n']}"
                            )
                    except Exception as exc:  # pragma: no cover
                        log(f"Could not compute AIS verdict at session end: {exc}", "warning")

                    session_repo.update_session(UUID(session_id), update_payload)
                    db_session.commit()

                    log(f"Session completed with status: {update_payload['status']}", "success")
                    emit({"type": "status", "status": update_payload["status"], "passed": passed, "failed": failed})
        except Exception as exc:
            if should_stop():
                log("Session stopped manually - saving partial results", "warning")
                self._mark_manual_completed(session_id, "Stopped manually - partial results saved")
                emit({"type": "status", "status": SessionStatus.MANUAL_COMPLETED.value})
            else:
                log(f"Session error: {exc}", "error")
                self._mark_failed(session_id, str(exc))
                emit({"type": "status", "status": SessionStatus.FAILED.value})
        finally:
            # Cleanup browser if engine was created
            if 'engine' in locals() and engine.browser:
                engine.browser.cleanup()
            with self._lock:
                self._threads.pop(session_id, None)
                self._stop_events.pop(session_id, None)

    def _compute_verdict_fields_from_logs(
        self,
        session_repo: SessionRepository,
        session_id: str,
    ) -> Dict[str, Any]:
        """Ricalcola i campi verdict (AIS + intent Wilson 95% CI) dai
        conversation_log salvati nei TestResult della sessione.

        Usato sia nel happy path (a fine sessione normale) sia nel
        catch quando la session fallisce a metà — in questo modo la
        tabella sessions mostra valori coerenti col detail anche per
        session uscite in `failed`. Senza questo, `session.verdict_p_hat`
        restava NULL e la tabella mostrava "0% / Inconclusiva" mentre
        il detail ricalcolava al volo da `conversation_log`.

        Ritorna un dict con i campi da merge nell'update_payload, o {}
        se non c'è nulla da calcolare (no results / feature flag off /
        eccezione).
        """
        try:
            from src.utils.feature_flags import wilson_session_verdict_enabled
            from src.core.session_verdict import (
                compute_session_verdict,
                compute_intent_verdict,
            )

            if not wilson_session_verdict_enabled():
                return {}
            results_for_verdict = session_repo.get_session_results(UUID(session_id))
            if not results_for_verdict:
                return {}
            verdict_turns: List[Dict[str, Any]] = []
            for r in results_for_verdict:
                raw_log = getattr(r, "conversation_log", None)
                if not raw_log:
                    continue
                try:
                    entries = json.loads(raw_log) if isinstance(raw_log, str) else raw_log
                except Exception:
                    continue
                if not isinstance(entries, list):
                    continue
                for entry in entries:
                    if isinstance(entry, dict):
                        verdict_turns.append({
                            "correctness_label": entry.get("correctness_label"),
                            "human_override_label": None,
                            "intent_label": entry.get("intent_label"),
                        })
            if not verdict_turns:
                return {}
            verdict_obj = compute_session_verdict(verdict_turns)
            fields: Dict[str, Any] = {
                "verdict_label": verdict_obj["verdict"],
                "verdict_p_hat": verdict_obj["p_hat"],
                "verdict_lower_bound": verdict_obj["lower_bound"],
                "verdict_upper_bound": verdict_obj["upper_bound"],
                "verdict_threshold": verdict_obj["threshold"],
                "verdict_n": verdict_obj["n"],
            }
            # Intent verdict (Wilson sui soli intent_label).
            try:
                intent_obj = compute_intent_verdict(verdict_turns)
                fields.update({
                    "intent_verdict_label": intent_obj["verdict"],
                    "intent_verdict_p_hat": intent_obj["p_hat"],
                    "intent_verdict_lower_bound": intent_obj["lower_bound"],
                    "intent_verdict_upper_bound": intent_obj["upper_bound"],
                    "intent_verdict_threshold": intent_obj["threshold"],
                    "intent_verdict_n": intent_obj["n"],
                })
            except Exception:
                pass  # intent verdict best-effort
            return fields
        except Exception:
            return {}

    def _mark_failed(self, session_id: str, error_message: str) -> None:
        db = get_db()
        with db.get_session() as db_session:
            session_repo = SessionRepository(db_session)
            update_payload: Dict[str, Any] = {
                "status": SessionStatus.FAILED.value,
                "error_message": error_message,
            }
            # Calcola verdict dai turni già salvati PRIMA di marcare failed,
            # così la tabella sessions list mostra valori coerenti col detail
            # anche per session uscite in errore (issue 2 fix 2026-05-14).
            verdict_fields = self._compute_verdict_fields_from_logs(
                session_repo, session_id
            )
            if verdict_fields:
                update_payload.update(verdict_fields)
            session_repo.update_session(UUID(session_id), update_payload)
            db_session.commit()

    def _mark_cancelled(self, session_id: str, message: str) -> None:
        db = get_db()
        with db.get_session() as db_session:
            session_repo = SessionRepository(db_session)
            session_repo.update_session(UUID(session_id), {
                "status": SessionStatus.CANCELLED.value,
                "completed_at": datetime.now(),
                "error_message": message,
            })
            db_session.commit()

    def _derive_completed_status(
        self,
        outcome_counters: Dict[str, int],
        passed: int,
        failed: int,
    ) -> str:
        """Derive final completed status from scenario outcome counters."""
        in_scope_total = outcome_counters.get("in_scope_pass", 0) + outcome_counters.get("in_scope_fail", 0)
        out_scope_total = outcome_counters.get("out_of_scope_fallback_pass", 0) + outcome_counters.get("out_of_scope_fallback_fail", 0)

        if in_scope_total > 0 and out_scope_total > 0:
            return SessionStatus.COMPLETED_MIXED.value

        if in_scope_total > 0:
            return (
                SessionStatus.COMPLETED_IN_SCOPE_PASS.value
                if outcome_counters.get("in_scope_fail", 0) == 0
                else SessionStatus.COMPLETED_IN_SCOPE_FAIL.value
            )

        if out_scope_total > 0:
            return (
                SessionStatus.COMPLETED_OUT_OF_SCOPE_FALLBACK_PASS.value
                if outcome_counters.get("out_of_scope_fallback_fail", 0) == 0
                else SessionStatus.COMPLETED_OUT_OF_SCOPE_FALLBACK_FAIL.value
            )

        # Fallback for legacy sessions where detailed outcome is not available.
        if failed == 0 and passed > 0:
            return SessionStatus.COMPLETED.value
        return SessionStatus.FAILED.value
    
    def _mark_manual_completed(self, session_id: str, message: str) -> None:
        """Mark session as manually stopped but with partial results preserved."""
        db = get_db()
        with db.get_session() as db_session:
            session_repo = SessionRepository(db_session)
            session_repo.update_session(UUID(session_id), {
                "status": SessionStatus.MANUAL_COMPLETED.value,
                "completed_at": datetime.now(),
                "error_message": message,
            })
            db_session.commit()

    def _get_session_pairs(
        self,
        db_session,
        session_id: str,
        bot_id: UUID,
        scenario_repo: ScenarioRepository,
        persona_repo: PersonaRepository,
        log,
    ) -> List[Tuple[Any, Any]]:
        rows = db_session.execute(
            text(
                "SELECT scenario_id, persona_id FROM session_scenario_links WHERE session_id = :sid"
            ),
            {"sid": session_id},
        ).fetchall()

        pairs: List[Tuple[Any, Any]] = []
        seen = set()

        if rows:
            for row in rows:
                scenario_id = row[0]
                persona_id = row[1]
                key = (scenario_id, persona_id)
                if key in seen:
                    continue
                seen.add(key)

                scenario = scenario_repo.get_by_id(UUID(scenario_id))
                persona = persona_repo.get_by_id(UUID(persona_id))
                if scenario and persona:
                    # Validate that scenario belongs to this bot
                    if str(scenario.bot_id) != str(bot_id):
                        log(f"Skipping scenario '{scenario.name}' - belongs to different bot", "warning")
                        continue
                    pairs.append((scenario, persona))
        else:
            scenarios = scenario_repo.list_all(bot_id=bot_id)
            personas = persona_repo.list_all()
            if scenarios and personas:
                log("No explicit session links found. Using all scenarios/personas.", "warning")
                for scenario in scenarios:
                    for persona in personas:
                        pairs.append((scenario, persona))

        return pairs

    @staticmethod
    def _to_output_url(output_root: Path, path: str) -> str:
        try:
            rel = Path(path).resolve().relative_to(output_root)
            return f"/output/{rel.as_posix()}"
        except Exception:
            return path

    def _normalize_result_paths(self, output_root: Path, result) -> None:
        normalized_screens = [self._to_output_url(output_root, p) for p in result.screenshot_urls]
        result.screenshot_urls = normalized_screens

        normalized_steps = []
        for step in result.steps_results:
            step = dict(step)
            screenshot = step.get("screenshot")
            if screenshot:
                step["screenshot"] = self._to_output_url(output_root, screenshot)
            normalized_steps.append(step)
        result.steps_results = normalized_steps

        if result.conversation_log:
            try:
                json.loads(result.conversation_log)
            except Exception:
                pass


session_event_bus = SessionEventBus()
session_runner = SessionRunner(session_event_bus)