File size: 26,491 Bytes
75ee53d
f84481c
 
5dabf9d
 
bed58cc
 
 
5dabf9d
 
 
 
 
bed58cc
5dabf9d
 
 
 
 
 
 
 
 
75ee53d
 
ed5b8b8
 
 
16676c4
1ce5806
75ee53d
f2ea5fc
0102e34
ed5b8b8
f84481c
 
f2ea5fc
ed5b8b8
 
 
 
 
17cb949
f2ea5fc
5dabf9d
f84481c
 
 
 
 
 
 
 
75ee53d
f84481c
75ee53d
ac8ab2c
 
75ee53d
 
 
 
 
 
f84481c
75ee53d
 
 
 
 
 
 
f2ea5fc
f84481c
 
 
 
 
 
f2ea5fc
 
 
ed5b8b8
f84481c
f2ea5fc
f84481c
 
 
5dabf9d
 
 
 
 
 
ed5b8b8
f2ea5fc
 
 
0102e34
 
 
ed5b8b8
0102e34
ed5b8b8
 
 
17cb949
 
 
 
 
ed5b8b8
 
 
0102e34
 
 
 
ed5b8b8
 
17cb949
 
 
 
 
 
 
 
5dabf9d
 
 
 
 
 
 
 
 
 
 
f84481c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5dabf9d
f84481c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75ee53d
16676c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
440d1f1
 
 
 
 
 
 
 
 
 
16676c4
440d1f1
 
 
ed5b8b8
 
f2ea5fc
 
ed5b8b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bed58cc
 
 
 
 
f84481c
 
 
75ee53d
f2ea5fc
ed5b8b8
 
f84481c
5dabf9d
 
 
 
f2ea5fc
 
ed5b8b8
 
 
 
 
 
 
5dabf9d
 
 
 
 
 
 
 
bed58cc
5dabf9d
 
 
 
 
 
 
 
 
 
bed58cc
5dabf9d
ed5b8b8
 
 
 
f84481c
 
ed5b8b8
 
440d1f1
ed5b8b8
f84481c
16676c4
440d1f1
f84481c
440d1f1
 
 
b70a952
75ee53d
b70a952
ed5b8b8
 
 
f2ea5fc
ed5b8b8
b70a952
 
f84481c
ed5b8b8
f2ea5fc
f84481c
5dabf9d
f84481c
75ee53d
5dabf9d
 
 
 
f2ea5fc
ed5b8b8
 
5dabf9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed5b8b8
bed58cc
5dabf9d
75ee53d
f84481c
4d2289b
75ee53d
440d1f1
 
 
17cb949
16676c4
496a69a
75ee53d
 
 
 
 
 
 
 
 
 
 
 
 
 
17cb949
 
 
 
 
 
 
440d1f1
 
 
 
 
 
 
 
 
 
 
 
 
16676c4
 
 
 
440d1f1
 
 
 
 
 
16676c4
440d1f1
 
 
 
 
 
 
 
 
16676c4
440d1f1
 
 
 
 
 
 
 
75ee53d
 
16676c4
496a69a
75ee53d
5dabf9d
75ee53d
 
089db7b
f84481c
75ee53d
 
 
 
16676c4
 
 
 
75ee53d
 
496a69a
 
 
 
 
75ee53d
496a69a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75ee53d
496a69a
75ee53d
496a69a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75ee53d
 
ed5b8b8
17cb949
caa1385
17cb949
440d1f1
 
17cb949
 
caa1385
 
440d1f1
 
 
 
 
 
caa1385
17cb949
caa1385
 
17cb949
 
 
 
caa1385
 
17cb949
f2ea5fc
17cb949
f2ea5fc
ed5b8b8
 
 
 
 
 
 
b70a952
 
f84481c
 
ed5b8b8
 
 
 
75ee53d
caa1385
 
 
 
 
17cb949
4d2289b
ed5b8b8
 
 
5dabf9d
 
 
 
 
 
bed58cc
75ee53d
496a69a
 
5dabf9d
75ee53d
5dabf9d
75ee53d
17cb949
b70a952
440d1f1
 
 
 
 
 
 
 
 
ed5b8b8
 
 
 
f84481c
b70a952
 
f84481c
ed5b8b8
17cb949
 
 
 
 
 
 
75ee53d
 
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
"""
app.py โ€” FastAPI entrypoint: WebRTC-first + WebSocket fallback

FIXES APPLIED:
  FIX-SESSION (Issue 1): The voice WS handler now reads user_id from the
    first 'init' JSON message before processing any audio. The browser now
    generates a fresh USER_ID on every page load, so each reload becomes a
    brand-new user and gets a fresh LangGraph thread / DB row.

    Implementation:
      โ€ข user_id is initialised to None inside ws_voice.
      โ€ข The handler waits for any early text messages before processing binary.
      โ€ข On 'init' message, user_id is set and init_ack returned.
      โ€ข All subsequent audio/LLM calls use that session user_id.
      โ€ข If no 'init' is received within 3 s, a random fallback is used
        (prevents hang for non-browser clients).

  FIX-CHAT-INIT (Issue 1): ws_chat also reads the 'init' message so chat
    sessions share the same backend thread as voice sessions for the same
    user.

All performance optimisations (parallel TTS, GPU-batched STT, concurrent
LLM+TTS) preserved.
"""

import asyncio
import json
import os
import re
import struct
import uuid
from contextlib import asynccontextmanager
from pathlib import Path

from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from starlette.websockets import WebSocketState

from core.backend import AIBackend
from services.stt import STTProcessor
from services.streaming import ParallelTTSStreamer
from db_view.dbapi import app as db_api_app

# โ”€โ”€ WebRTC (optional) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
try:
    from services.webrtc_pipeline import WebRTCSession
    WEBRTC_AVAILABLE = True
    print("[APP] WebRTC pipeline available โœ“")
except (ImportError, RuntimeError) as _e:
    WEBRTC_AVAILABLE = False
    print(f"[APP] WebRTC pipeline unavailable ({_e}). WebSocket fallback only.")

# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
#  MODEL ROUTING CONFIG โ€” set exactly ONE to True
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
USE_GEMINI         = True
USE_OLLAMA         = False
USE_LOCAL_FALLBACK = False

_active = sum([USE_GEMINI, USE_OLLAMA, USE_LOCAL_FALLBACK])
if _active != 1:
    raise RuntimeError(
        f"[CONFIG] Exactly one of USE_GEMINI / USE_OLLAMA / USE_LOCAL_FALLBACK "
        f"must be True. Got {_active}."
    )

ai = AIBackend(
    use_gemini=USE_GEMINI,
    use_ollama=USE_OLLAMA,
    use_fallback=USE_LOCAL_FALLBACK,
)

_rtc_sessions: dict[str, "WebRTCSession"] = {}


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
#  LIFESPAN
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

@asynccontextmanager
async def lifespan(app: FastAPI):
    await ai.async_setup()
    print("[APP] AI backend ready โœ“")
    yield
    for session in list(_rtc_sessions.values()):
        await session.close()
    _rtc_sessions.clear()
    conn = getattr(ai, "conn", None)
    if conn:
        try:
            await conn.close()
        except Exception:
            pass


app = FastAPI(lifespan=lifespan)

BASE_DIR = Path(__file__).resolve().parent
FRONTEND_DIR = BASE_DIR / "frontend"

try:
    app.mount("/static", StaticFiles(directory=str(FRONTEND_DIR)), name="static")
except Exception:
    pass

try:
    app.mount("/dbapi", db_api_app)
except Exception:
    pass


@app.get("/")
async def root():
    index_path = FRONTEND_DIR / "index.html"
    if index_path.exists():
        return FileResponse(str(index_path))
    return HTMLResponse("<h2>frontend/index.html not found</h2>", status_code=404)


@app.get("/db-view")
async def db_view():
    db_index_path = BASE_DIR / "db_view" / "db.html"
    if db_index_path.exists():
        return FileResponse(str(db_index_path))
    return HTMLResponse("<h2>db_view/db.html not found</h2>", status_code=404)


@app.get("/health")
async def health():
    from services.stt import _model_ready, _model_error
    return JSONResponse({
        "status":       "ok",
        "model_ready":  _model_ready.is_set(),
        "model_error":  _model_error,
        "rtc_sessions": len(_rtc_sessions),
    })


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
#  WEBRTC SIGNALING ENDPOINTS
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

@app.post("/rtc/offer")
async def rtc_offer(request: Request):
    if not WEBRTC_AVAILABLE:
        return JSONResponse(
            {"error": "WebRTC unavailable. Use WebSocket fallback at /ws/voice"},
            status_code=503,
        )
    body       = await request.json()
    sdp        = body.get("sdp", "")
    sdp_type   = body.get("type", "offer")
    session_id = body.get("session_id") or uuid.uuid4().hex

    session = _rtc_sessions.get(session_id)
    if session is None:
        session = WebRTCSession(ai_backend=ai)
        _rtc_sessions[session_id] = session
        print(f"[RTC] New session: {session_id} user_id={session.user_id}")

    answer = await session.handle_offer(sdp, sdp_type)
    return JSONResponse({**answer, "session_id": session_id})


@app.post("/rtc/ice")
async def rtc_ice(request: Request):
    if not WEBRTC_AVAILABLE:
        return JSONResponse({"error": "WebRTC unavailable"}, status_code=503)
    body       = await request.json()
    session_id = body.get("session_id", "")
    candidate  = body.get("candidate", {})
    session    = _rtc_sessions.get(session_id)
    if session is None:
        return JSONResponse({"error": "Session not found"}, status_code=404)
    await session.add_ice_candidate(candidate)
    return JSONResponse({"ok": True})


@app.delete("/rtc/session/{session_id}")
async def rtc_close(session_id: str):
    session = _rtc_sessions.pop(session_id, None)
    if session:
        await session.close()
    return JSONResponse({"ok": True})


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
#  WEBSOCKET HELPERS
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

_DIGIT_WORDS = {
    "0": "เฆถเง‚เฆจเงเฆฏ",
    "1": "เฆเฆ•",
    "2": "เฆฆเงเฆ‡",
    "3": "เฆคเฆฟเฆจ",
    "4": "เฆšเฆพเฆฐ",
    "5": "เฆชเฆพเฆเฆš",
    "6": "เฆ›เฆฏเฆผ",
    "7": "เฆธเฆพเฆค",
    "8": "เฆ†เฆŸ",
    "9": "เฆจเฆฏเฆผ",
    "เงฆ": "เฆถเง‚เฆจเงเฆฏ",
    "เงง": "เฆเฆ•",
    "เงจ": "เฆฆเงเฆ‡",
    "เงฉ": "เฆคเฆฟเฆจ",
    "เงช": "เฆšเฆพเฆฐ",
    "เงซ": "เฆชเฆพเฆเฆš",
    "เงฌ": "เฆ›เฆฏเฆผ",
    "เงญ": "เฆธเฆพเฆค",
    "เงฎ": "เฆ†เฆŸ",
    "เงฏ": "เฆจเฆฏเฆผ",
    "ู ": "เฆถเง‚เฆจเงเฆฏ",
    "ูก": "เฆเฆ•",
    "ูข": "เฆฆเงเฆ‡",
    "ูฃ": "เฆคเฆฟเฆจ",
    "ูค": "เฆšเฆพเฆฐ",
    "ูฅ": "เฆชเฆพเฆเฆš",
    "ูฆ": "เฆ›เฆฏเฆผ",
    "ูง": "เฆธเฆพเฆค",
    "ูจ": "เฆ†เฆŸ",
    "ูฉ": "เฆจเฆฏเฆผ",
}


def _spoken_digits(chunk: str) -> str:
    digits = [ch for ch in chunk if ch in _DIGIT_WORDS]
    if len(digits) < 10:
        return chunk
    spoken = " ".join(_DIGIT_WORDS[ch] for ch in digits)
    return spoken


def _expand_phone_like_numbers(text: str) -> str:
    if not text:
        return ""

    def repl(match: re.Match[str]) -> str:
        chunk = match.group(0)
        spoken = _spoken_digits(chunk)
        if spoken == chunk:
            return chunk

        prev_char = text[match.start() - 1] if match.start() > 0 else ""
        next_char = text[match.end()] if match.end() < len(text) else ""

        if prev_char and not prev_char.isspace() and prev_char not in "([<{\"'":
            spoken = " " + spoken
        if next_char and not next_char.isspace() and next_char not in ")]>.,!?;:}\"'":
            spoken = spoken + " "
        return spoken

    return re.sub(r"[+\dเงฆ-เงฏู -ูฉ][\dเงฆ-เงฏู -ูฉ\s().\-]{8,}[\dเงฆ-เงฏู -ูฉ]", repl, text)


def _normalize_ai_text(text: str) -> str:
    """
    Apply small UX wording normalizations to assistant-visible text.
    (We still instruct the model via system prompt, but this guarantees output.)
    """
    if not text:
        return ""
    out = text
    out = out.replace("เฆ‰เฆชเฆฒเฆฌเงเฆง", "เฆเฆญเง‡เฆฒเง‡เฆฌเง‡เฆฒ")
    out = out.replace("เฆœเงเฆฌเฆฟ", "เฆ†เฆšเงเฆ›เฆพ")
    out = _expand_phone_like_numbers(out)
    return out


def _ws_open(ws: WebSocket) -> bool:
    return ws.client_state == WebSocketState.CONNECTED


async def _safe_text(ws: WebSocket, payload: dict) -> bool:
    if not _ws_open(ws):
        return False
    try:
        await ws.send_text(json.dumps(payload))
        return True
    except Exception:
        return False


async def _safe_bytes(ws: WebSocket, data: bytes) -> bool:
    if not _ws_open(ws):
        return False
    try:
        await ws.send_bytes(data)
        return True
    except Exception:
        return False


async def _register_user(user_id: str) -> None:
    if user_id:
        await ai.ensure_user_thread(user_id)


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
#  WEBSOCKET โ€” CHAT (text only, streaming tokens)
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

@app.websocket("/ws/chat")
async def ws_chat(ws: WebSocket):
    await ws.accept()
    print("[CHAT] Client connected โœ“")

    # FIX-SESSION: Start with no user_id; wait for 'init' to set it.
    user_id: str = ""

    try:
        while True:
            raw = await ws.receive_text()
            try:
                data = json.loads(raw)
            except json.JSONDecodeError:
                await _safe_text(ws, {"type": "error", "text": "Invalid JSON"})
                continue

            msg_type = data.get("type", "")

            # โ”€โ”€ Init handshake โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
            if msg_type == "init":
                claimed = str(data.get("user_id", "")).strip()[:64]
                if claimed:
                    user_id = claimed
                    print(f"[CHAT] Session restored for user_id={user_id!r}")
                    await _register_user(user_id)
                    await _safe_text(ws, {"type": "init_ack", "user_id": user_id})
                continue

            if msg_type == "ping":
                await _safe_text(ws, {"type": "pong"})
                continue

            # Fall back to user_id in message payload (compatibility)
            if not user_id:
                user_id = str(data.get("user_id", "default_user"))[:64]
                await _register_user(user_id)

            user_query = data.get("user_query", "").strip()
            if not user_query:
                continue

            print(f"[CHAT] user_id={user_id!r} query={user_query!r}")

            try:
                stream = await ai.main(user_id, user_query)
                full_text = ""
                async for token in stream:
                    if token:
                        token = _normalize_ai_text(token)
                        full_text += token
                        await _safe_text(ws, {"type": "llm_token", "token": token})
                # Ensure the final rendered message uses normalized wording.
                if full_text:
                    await _safe_text(ws, {"type": "chat", "text": _normalize_ai_text(full_text)})
            except Exception as exc:
                import traceback; traceback.print_exc()
                await _safe_text(ws, {"type": "error", "text": str(exc)})

            await _safe_text(ws, {"type": "end"})

    except WebSocketDisconnect:
        print("[CHAT] Client disconnected")
    except Exception as exc:
        if "disconnect" not in str(exc).lower():
            print(f"[CHAT] Error: {exc}")


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
#  WEBSOCKET โ€” VOICE (STTโ†’LLMโ†’TTS pipeline over WS)
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

# How long (seconds) to wait for the first 'init' message before using fallback
_INIT_TIMEOUT = 3.0


@app.websocket("/ws/voice")
async def ws_voice(ws: WebSocket):
    await ws.accept()
    print("[VOICE] Client connected")

    # โ”€โ”€ FIX-SESSION: Resolve stable user_id from browser init message โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    # Wait up to _INIT_TIMEOUT seconds for the {'type':'init','user_id':...} msg.
    # This is always the FIRST message sent by script.js on WS open.
    user_id: str = ""
    try:
        first_raw = await asyncio.wait_for(ws.receive(), timeout=_INIT_TIMEOUT)
        if "text" in first_raw and first_raw["text"]:
            try:
                first_msg = json.loads(first_raw["text"])
                if first_msg.get("type") == "init":
                    claimed = str(first_msg.get("user_id", "")).strip()[:64]
                    if claimed:
                        user_id = claimed
            except (json.JSONDecodeError, KeyError):
                pass
    except asyncio.TimeoutError:
        print("[VOICE] No init message within timeout โ€” using fallback user_id")

    if not user_id:
        user_id = f"voice_{uuid.uuid4().hex[:12]}"
        print(f"[VOICE] Fallback user_id={user_id}")
    else:
        print(f"[VOICE] Session user_id={user_id}")

    await _register_user(user_id)
    await _safe_text(ws, {"type": "init_ack", "user_id": user_id})

    stt = STTProcessor()
    _active_streamer: ParallelTTSStreamer | None = None
    _active_task:     asyncio.Task | None        = None
    # Queue supports both audio turns and server-side "speak" turns initiated
    # by the client UI (e.g., brain-mode welcome).
    _utterance_q: asyncio.Queue[object | None] = asyncio.Queue()
    _worker_task: asyncio.Task | None = None
    _turn_id: int = 0
    brain_mode_enabled = False

    async def _cancel_active():
        nonlocal _active_streamer, _active_task
        if _active_streamer is not None:
            await _active_streamer.cancel()
            _active_streamer = None
        if _active_task is not None and not _active_task.done():
            _active_task.cancel()
            try:
                await _active_task
            except (asyncio.CancelledError, Exception):
                pass
            _active_task = None

    async def _drain_utterance_queue():
        while True:
            try:
                _utterance_q.get_nowait()
            except asyncio.QueueEmpty:
                break

    async def _handle_speak(text: str):
        """
        Generate TTS for a given text without running STT.
        Uses the same framed-audio protocol as normal turns and emits `llm_full`
        so the UI can display the spoken text.
        """
        nonlocal _active_streamer

        speak_text = _normalize_ai_text((text or "").strip())
        if not speak_text:
            await _safe_text(ws, {"type": "end"})
            return

        nonlocal _turn_id
        _turn_id += 1
        my_turn = _turn_id

        tts_streamer = ParallelTTSStreamer()
        _active_streamer = tts_streamer
        audio_seq = 0

        async def run_text():
            try:
                await _safe_text(ws, {"type": "llm_full", "text": speak_text, "turn": my_turn})
                await tts_streamer.add_token(speak_text)
            except asyncio.CancelledError:
                raise
            finally:
                await tts_streamer.flush()

        async def run_tts_framed():
            nonlocal audio_seq
            async for chunk in tts_streamer.stream_audio():
                framed = struct.pack(">II", my_turn, audio_seq) + chunk
                if not await _safe_bytes(ws, framed):
                    break
                audio_seq += 1

        await asyncio.gather(run_text(), run_tts_framed(), return_exceptions=True)
        _active_streamer = None
        await _safe_text(ws, {"type": "end"})

    async def _handle_utterance(audio_bytes: bytes):
        nonlocal _active_streamer
        nonlocal _turn_id
        nonlocal brain_mode_enabled

        # โ”€โ”€ STT โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        transcript = await stt.transcribe(audio_bytes)
        if not transcript:
            # Silence / background-noise turns should be ignored silently.
            await _safe_text(ws, {"type": "error", "text": "เฆ•เฆฅเฆพ เฆฌเงเฆเฆคเง‡ เฆชเฆพเฆฐเฆฟเฆจเฆฟ, เฆ†เฆฌเฆพเฆฐ เฆฌเฆฒเงเฆจเฅค"})
            await _safe_text(ws, {"type": "end"})
            return

        print(f"[VOICE] [{user_id}] STT: {transcript}")
        _turn_id += 1
        my_turn = _turn_id

        if not await _safe_text(ws, {"type": "stt", "text": transcript, "turn": my_turn}):
            return

        if brain_mode_enabled:
            # Brain mode prioritizes immediacy. Stream tokens and TTS together.
            tts_streamer = ParallelTTSStreamer()
            _active_streamer = tts_streamer
            audio_seq = 0

            async def run_llm():
                full_text = ""
                try:
                    stream = await ai.main(user_id, transcript)
                    async for token in stream:
                        if not token:
                            continue
                        token = _normalize_ai_text(token)
                        full_text += token
                        if not await _safe_text(ws, {"type": "llm_token", "token": token, "turn": my_turn}):
                            break
                except asyncio.CancelledError:
                    raise
                except Exception as exc:
                    print(f"[VOICE] LLM error: {exc}")
                finally:
                    if full_text:
                        await _safe_text(ws, {"type": "llm_full", "text": _normalize_ai_text(full_text), "turn": my_turn})
                        await tts_streamer.add_token(full_text)
                    await tts_streamer.flush()

            async def run_tts_framed():
                nonlocal audio_seq
                async for chunk in tts_streamer.stream_audio():
                    framed = struct.pack(">II", my_turn, audio_seq) + chunk
                    if not await _safe_bytes(ws, framed):
                        break
                    audio_seq += 1

            await asyncio.gather(run_llm(), run_tts_framed(), return_exceptions=True)
            _active_streamer = None
        else:
            # Normal mode keeps audio silent until the full response is ready.
            audio_seq = 0

            async def run_llm():
                full_text = ""
                try:
                    stream = await ai.main(user_id, transcript)
                    async for token in stream:
                        if not token:
                            continue
                        token = _normalize_ai_text(token)
                        full_text += token
                        if not await _safe_text(ws, {"type": "llm_token", "token": token, "turn": my_turn}):
                            break
                except asyncio.CancelledError:
                    raise
                except Exception as exc:
                    print(f"[VOICE] LLM error: {exc}")
                return full_text

            full_text = await run_llm()
            if full_text:
                await _safe_text(ws, {"type": "llm_full", "text": _normalize_ai_text(full_text), "turn": my_turn})
                tts_streamer = ParallelTTSStreamer()
                _active_streamer = tts_streamer
                await tts_streamer.add_token(full_text)
                await tts_streamer.flush()
                async for chunk in tts_streamer.stream_audio():
                    framed = struct.pack(">II", my_turn, audio_seq) + chunk
                    if not await _safe_bytes(ws, framed):
                        break
                    audio_seq += 1
            _active_streamer = None

        await _safe_text(ws, {"type": "end"})

    async def _utterance_worker():
        nonlocal _active_task
        while True:
            item = await _utterance_q.get()
            if item is None:
                break
            try:
                # Run each utterance as a cancellable task so barge-in can
                # immediately interrupt LLM+TTS mid-turn.
                if isinstance(item, (bytes, bytearray)):
                    _active_task = asyncio.create_task(_handle_utterance(bytes(item)))
                elif isinstance(item, dict) and item.get("type") == "speak":
                    _active_task = asyncio.create_task(_handle_speak(str(item.get("text", ""))))
                else:
                    continue
                await _active_task
            except asyncio.CancelledError:
                # Interruption is normal (client barge-in / cancel).
                pass
            except Exception as exc:
                print(f"[VOICE] Utterance worker error: {exc}")
                await _safe_text(ws, {"type": "error", "text": str(exc)})
                await _safe_text(ws, {"type": "end"})
            finally:
                _active_task = None

    try:
        _worker_task = asyncio.create_task(_utterance_worker())
        while True:
            if not _ws_open(ws):
                break

            try:
                data = await ws.receive()
            except WebSocketDisconnect:
                break
            except Exception as exc:
                if "disconnect" in str(exc).lower():
                    break
                print(f"[VOICE] Receive error: {exc}")
                break

            if "bytes" in data and data["bytes"]:
                audio_bytes = data["bytes"]
                print(f"[VOICE] [{user_id}] Utterance: {len(audio_bytes):,} bytes")
                # If a turn is currently speaking, treat a new utterance as
                # barge-in: cancel current output and drop any queued audio.
                if _active_task is not None and not _active_task.done():
                    await _cancel_active()
                    await _drain_utterance_queue()
                await _utterance_q.put(audio_bytes)

            elif "text" in data and data["text"]:
                try:
                    msg = json.loads(data["text"])
                    t   = msg.get("type", "")
                    if t == "init":
                        # Late re-init (e.g. after reconnect with same WS obj โ€” rare)
                        claimed = str(msg.get("user_id", "")).strip()[:64]
                        if claimed:
                            user_id = claimed
                            await _register_user(user_id)
                        await _safe_text(ws, {"type": "init_ack", "user_id": user_id})
                    elif t in ("brain_mode", "mode"):
                        brain_mode_enabled = bool(msg.get("enabled", False))
                    elif t == "ping":
                        await _safe_text(ws, {"type": "pong"})
                    elif t == "cancel":
                        await _cancel_active()
                        await _drain_utterance_queue()
                        await _safe_text(ws, {"type": "end"})
                    elif t == "speak":
                        # UI-initiated TTS turn (e.g. brain-mode welcome).
                        # Do not block the receive loop; enqueue for worker.
                        speak_text = str(msg.get("text", "")).strip()
                        if speak_text:
                            if _active_task is not None and not _active_task.done():
                                await _cancel_active()
                                await _drain_utterance_queue()
                            await _utterance_q.put({"type": "speak", "text": speak_text})
                except json.JSONDecodeError:
                    pass

    except WebSocketDisconnect:
        pass
    except Exception as exc:
        if "disconnect" not in str(exc).lower():
            print(f"[VOICE] Error: {exc}")
    finally:
        await _utterance_q.put(None)
        if _worker_task is not None and not _worker_task.done():
            _worker_task.cancel()
            try:
                await _worker_task
            except (asyncio.CancelledError, Exception):
                pass
        await _cancel_active()
        print(f"[VOICE] [{user_id}] Handler exiting cleanly.")