Spaces:
Runtime error

File size: 23,627 Bytes
71c0723
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
streamlit_app.py โ€” Vidya V3 Real-Time AI Tutor โ€” Streamlit UI

Run: streamlit run streamlit_app.py

Features:
- Full chat interface with Vidya V3
- Live signal scorecard with bar charts
- Mastery level tracker
- Phase history timeline
- ICP + session config panel
- Conversation history viewer
- Session logs browser
"""

import streamlit as st
import json
import sys
import os
from pathlib import Path

sys.path.insert(0, os.path.dirname(__file__))

# โ”€โ”€ Page config โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
st.set_page_config(
    page_title="Vidya V3 โ€” AI Tutor",
    page_icon="๐ŸŽ“",
    layout="wide",
    initial_sidebar_state="expanded",
)

# โ”€โ”€ Custom CSS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&family=DM+Sans:wght@300;400;500;600&display=swap');

:root {
    --bg:        #0F0F13;
    --bg2:       #16161C;
    --bg3:       #1E1E27;
    --border:    #2A2A38;
    --text:      #E8E8F0;
    --muted:     #6B6B85;
    --accent:    #7C6FF7;
    --green:     #3DD68C;
    --amber:     #F5A623;
    --red:       #FF5C5C;
    --blue:      #4EADFF;
    --model-c:   #4EADFF;
    --coach-c:   #3DD68C;
    --scaffold-c:#F5A623;
    --fade-c:    #B57BFF;
}

html, body, [data-testid="stApp"] {
    background-color: var(--bg) !important;
    font-family: 'DM Sans', sans-serif;
    color: var(--text);
}

[data-testid="stSidebar"] {
    background-color: var(--bg2) !important;
    border-right: 1px solid var(--border);
}

/* Hide streamlit chrome */
#MainMenu, footer, header { visibility: hidden; }
[data-testid="stToolbar"] { display: none; }

/* Cards */
.v-card {
    background: var(--bg2);
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 16px 20px;
    margin-bottom: 12px;
}

/* Chat bubbles */
.chat-user {
    display: flex;
    justify-content: flex-end;
    margin: 8px 0;
}
.chat-user .bubble {
    background: var(--accent);
    color: white;
    padding: 10px 16px;
    border-radius: 18px 18px 4px 18px;
    max-width: 72%;
    font-size: 14px;
    line-height: 1.6;
}
.chat-tutor {
    display: flex;
    justify-content: flex-start;
    margin: 8px 0;
    gap: 10px;
    align-items: flex-start;
}
.chat-tutor .avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    flex-shrink: 0;
    margin-top: 4px;
}
.chat-tutor .bubble {
    background: var(--bg3);
    border: 1px solid var(--border);
    padding: 10px 16px;
    border-radius: 18px 18px 18px 4px;
    max-width: 72%;
    font-size: 14px;
    line-height: 1.6;
}
.phase-badge {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 99px;
    font-size: 11px;
    font-weight: 600;
    font-family: 'Space Mono', monospace;
    margin-bottom: 4px;
}
.phase-MODEL    { background: rgba(78,173,255,.15); color: var(--model-c); }
.phase-COACH    { background: rgba(61,214,140,.15); color: var(--coach-c); }
.phase-SCAFFOLD { background: rgba(245,166,35,.15);  color: var(--scaffold-c); }
.phase-FADE     { background: rgba(181,123,255,.15); color: var(--fade-c); }

.suggestion {
    font-size: 12px;
    color: var(--accent);
    margin-top: 6px;
    font-style: italic;
}

/* Signal bars */
.signal-row {
    display: grid;
    grid-template-columns: 110px 1fr 48px;
    align-items: center;
    gap: 8px;
    margin: 5px 0;
}
.signal-label { font-size: 12px; color: var(--muted); }
.signal-bar-track {
    height: 6px;
    background: var(--bg3);
    border-radius: 99px;
    overflow: hidden;
    position: relative;
}
.signal-bar-fill {
    height: 100%;
    border-radius: 99px;
    transition: width .4s ease;
}
.signal-val { font-size: 11px; text-align: right; font-family: 'Space Mono', monospace; }

/* Mastery bar */
.mastery-track {
    height: 10px;
    background: var(--bg3);
    border-radius: 99px;
    overflow: hidden;
    margin: 6px 0;
}
.mastery-fill {
    height: 100%;
    background: linear-gradient(90deg, var(--accent), var(--green));
    border-radius: 99px;
    transition: width .5s ease;
}

/* Section header */
.sec-header {
    font-family: 'Space Mono', monospace;
    font-size: 11px;
    font-weight: 700;
    color: var(--muted);
    text-transform: uppercase;
    letter-spacing: .08em;
    margin-bottom: 10px;
}

/* Input area */
.stTextInput input, .stSelectbox select, [data-baseweb="select"] {
    background: var(--bg3) !important;
    border-color: var(--border) !important;
    color: var(--text) !important;
    border-radius: 8px !important;
}

/* Buttons */
.stButton button {
    background: var(--accent) !important;
    color: white !important;
    border: none !important;
    border-radius: 8px !important;
    font-family: 'DM Sans', sans-serif !important;
    font-weight: 500 !important;
}
.stButton button:hover {
    background: #6B5FD9 !important;
}

/* Metrics */
.metric-box {
    background: var(--bg3);
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 12px 16px;
    text-align: center;
}
.metric-val {
    font-family: 'Space Mono', monospace;
    font-size: 22px;
    font-weight: 700;
    color: var(--text);
}
.metric-label {
    font-size: 11px;
    color: var(--muted);
    text-transform: uppercase;
    letter-spacing: .06em;
    margin-top: 2px;
}

/* Phase timeline */
.timeline-item {
    display: flex;
    gap: 10px;
    align-items: center;
    padding: 5px 0;
    font-size: 12px;
    border-bottom: 1px solid var(--border);
}
.timeline-item:last-child { border-bottom: none; }
.timeline-turn {
    width: 28px;
    font-family: 'Space Mono', monospace;
    color: var(--muted);
    flex-shrink: 0;
}

/* Scrollable chat area */
.chat-scroll {
    max-height: 520px;
    overflow-y: auto;
    padding-right: 4px;
}

/* Slider */
[data-testid="stSlider"] {
    color: var(--accent) !important;
}

/* Divider */
hr { border-color: var(--border) !important; }

</style>
""", unsafe_allow_html=True)


# โ”€โ”€ Helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def signal_color(score: float) -> str:
    if score >= 65: return "#FF5C5C" if score >= 80 else "#F5A623"
    if score <= 35: return "#3DD68C"
    return "#6B6B85"

def phase_color(phase: str) -> str:
    return {"MODEL": "#4EADFF", "COACH": "#3DD68C",
            "SCAFFOLD": "#F5A623", "FADE": "#B57BFF"}.get(phase, "#6B6B85")

def phase_emoji(phase: str) -> str:
    return {"MODEL": "๐Ÿ“–", "COACH": "๐Ÿ’ฌ", "SCAFFOLD": "๐Ÿงฉ", "FADE": "๐Ÿš€"}.get(phase, "๐ŸŽ“")

def render_signal_bar(label: str, score: float):
    color = signal_color(score)
    pct   = score
    st.markdown(f"""
    <div class="signal-row">
        <div class="signal-label">{label}</div>
        <div class="signal-bar-track">
            <div class="signal-bar-fill" style="width:{pct}%;background:{color}"></div>
        </div>
        <div class="signal-val" style="color:{color}">{score:.0f}</div>
    </div>
    """, unsafe_allow_html=True)

def render_mastery_bar(mastery: float):
    pct = mastery * 100
    st.markdown(f"""
    <div class="mastery-track">
        <div class="mastery-fill" style="width:{pct}%"></div>
    </div>
    """, unsafe_allow_html=True)


# โ”€โ”€ Session state init โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def init_state():
    defaults = {
        "session":        None,
        "messages":       [],   # [{role, content, phase, mastery, signals, suggestion}]
        "phase_history":  [],   # [(turn, phase)]
        "mastery_history":[],   # [(turn, mastery)]
        "configured":     False,
        "turn_count":     0,
    }
    for k, v in defaults.items():
        if k not in st.session_state:
            st.session_state[k] = v

init_state()


# โ”€โ”€ Sidebar โ€” Session Config โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

with st.sidebar:
    st.markdown("""
    <div style="text-align:center;padding:16px 0 8px">
        <div style="font-family:'Space Mono',monospace;font-size:20px;font-weight:700;color:#7C6FF7">
            VIDYA V3
        </div>
        <div style="font-size:12px;color:#6B6B85;margin-top:2px">Real-Time AI Tutor</div>
    </div>
    """, unsafe_allow_html=True)

    st.markdown("---")
    st.markdown('<div class="sec-header">Session Config</div>', unsafe_allow_html=True)

    skill_topic = st.text_input(
        "Skill Topic",
        value="Python functions",
        placeholder="e.g. Python functions",
        disabled=st.session_state.configured,
    )

    mastery_input = st.slider(
        "Starting Mastery Level",
        0.0, 1.0, 0.2, 0.05,
        disabled=st.session_state.configured,
    )

    icp_type = st.selectbox(
        "ICP Type",
        ["low_wage", "high_wage"],
        format_func=lambda x: {
            "low_wage":  "๐ŸŒฑ Low Wage โ€” Early career / reskilling",
            "high_wage": "๐Ÿš€ High Wage โ€” Professional / aspirational",
        }[x],
        disabled=st.session_state.configured,
    )

    language = st.selectbox(
        "Language",
        ["en", "hi", "mixed"],
        format_func=lambda x: {"en": "๐Ÿ‡ฌ๐Ÿ‡ง English", "hi": "๐Ÿ‡ฎ๐Ÿ‡ณ Hindi/Hinglish", "mixed": "๐Ÿ”€ Mixed"}[x],
        disabled=st.session_state.configured,
    )

    if not st.session_state.configured:
        if st.button("๐Ÿš€ Start Session", use_container_width=True):
            try:
                from src.schemas import SessionConfig
                from src.icp_profiles import mastery_to_phase
                from src.tutor_session import TutorSession

                auto_phase = mastery_to_phase(mastery_input, icp_type)
                config = SessionConfig(
                    skill_topic=skill_topic,
                    mastery_level=mastery_input,
                    icp_type=icp_type,
                    ca_phase=auto_phase,
                    language_preference=language,
                )
                st.session_state.session        = TutorSession(config)
                st.session_state.configured     = True
                st.session_state.phase_history  = [(0, auto_phase)]
                st.session_state.mastery_history= [(0, mastery_input)]
                st.rerun()
            except Exception as e:
                st.error(f"Setup failed: {e}")
    else:
        if st.button("๐Ÿ”„ New Session", use_container_width=True):
            for k in ["session","messages","phase_history","mastery_history","configured","turn_count"]:
                del st.session_state[k]
            st.rerun()

    st.markdown("---")

    # Live signal scorecard
    if st.session_state.configured and st.session_state.session:
        sess = st.session_state.session
        st.markdown('<div class="sec-header">Signal Scorecard</div>', unsafe_allow_html=True)
        scores = sess.scorecard.to_dict()
        for sig in ["confidence", "effort", "confusion", "frustration", "answer_seeking", "off_topic"]:
            render_signal_bar(sig, scores.get(sig, 50))

        st.markdown("---")
        st.markdown('<div class="sec-header">Mastery Level</div>', unsafe_allow_html=True)
        mastery = sess.mastery_level
        render_mastery_bar(mastery)
        col1, col2 = st.columns(2)
        with col1:
            st.markdown(f"""
            <div class="metric-box">
                <div class="metric-val">{mastery:.3f}</div>
                <div class="metric-label">Mastery</div>
            </div>""", unsafe_allow_html=True)
        with col2:
            phase = sess.current_phase
            st.markdown(f"""
            <div class="metric-box">
                <div class="metric-val" style="color:{phase_color(phase)}">{phase}</div>
                <div class="metric-label">Phase</div>
            </div>""", unsafe_allow_html=True)

        # Phase timeline
        if st.session_state.phase_history:
            st.markdown("---")
            st.markdown('<div class="sec-header">Phase Timeline</div>', unsafe_allow_html=True)
            for turn, phase in st.session_state.phase_history[-8:]:
                st.markdown(f"""
                <div class="timeline-item">
                    <div class="timeline-turn">T{turn}</div>
                    <span class="phase-badge phase-{phase}">{phase_emoji(phase)} {phase}</span>
                </div>""", unsafe_allow_html=True)

        # Judge stats
        if hasattr(sess.scorecard, 'stats'):
            st.markdown("---")
            st.caption(f"๐Ÿ” {sess.scorecard.stats()}")


# โ”€โ”€ Main area โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

if not st.session_state.configured:
    # Welcome screen
    st.markdown("""
    <div style="text-align:center;padding:80px 0 40px">
        <div style="font-size:56px;margin-bottom:16px">๐ŸŽ“</div>
        <div style="font-family:'Space Mono',monospace;font-size:28px;font-weight:700;color:#E8E8F0;margin-bottom:8px">
            VIDYA V3
        </div>
        <div style="font-size:16px;color:#6B6B85;margin-bottom:32px">
            Real-Time AI Tutor ยท Cognitive Apprenticeship ยท Signal-Driven Adaptation
        </div>
    </div>
    """, unsafe_allow_html=True)

    c1, c2, c3 = st.columns(3)
    for col, icon, title, desc in [
        (c1, "๐Ÿ“Š", "Signal Scoring", "6 signals tracked as rolling 0โ€“100 scores across turns"),
        (c2, "๐ŸŽฏ", "ICP Adaptation", "low_wage vs high_wage โ€” different tone, pace, and phase thresholds"),
        (c3, "๐Ÿ”„", "Phase Control", "Mastery level drives phase. Gemini cannot jump ahead of what's earned"),
    ]:
        with col:
            st.markdown(f"""
            <div class="v-card" style="text-align:center">
                <div style="font-size:28px;margin-bottom:8px">{icon}</div>
                <div style="font-weight:600;margin-bottom:4px">{title}</div>
                <div style="font-size:13px;color:#6B6B85">{desc}</div>
            </div>""", unsafe_allow_html=True)

    st.markdown("""
    <div style="text-align:center;margin-top:32px;color:#6B6B85;font-size:13px">
        Configure your session in the sidebar and click <strong style="color:#7C6FF7">Start Session</strong>
    </div>
    """, unsafe_allow_html=True)

else:
    sess = st.session_state.session

    # Header row
    col_h1, col_h2, col_h3, col_h4 = st.columns([3,1,1,1])
    with col_h1:
        st.markdown(f"""
        <div style="padding:4px 0">
            <span style="font-family:'Space Mono',monospace;font-size:14px;color:#7C6FF7;font-weight:700">
                {sess.config.skill_topic.upper()}
            </span>
            <span style="color:#6B6B85;font-size:13px;margin-left:12px">
                {sess.config.icp_type} ยท {sess.config.language_preference}
            </span>
        </div>
        """, unsafe_allow_html=True)
    with col_h2:
        st.markdown(f"""<div class="metric-box">
            <div class="metric-val">{st.session_state.turn_count}</div>
            <div class="metric-label">Turns</div>
        </div>""", unsafe_allow_html=True)
    with col_h3:
        st.markdown(f"""<div class="metric-box">
            <div class="metric-val">{sess.mastery_level:.2f}</div>
            <div class="metric-label">Mastery</div>
        </div>""", unsafe_allow_html=True)
    with col_h4:
        phase = sess.current_phase
        st.markdown(f"""<div class="metric-box">
            <div class="metric-val" style="color:{phase_color(phase)};font-size:16px">
                {phase_emoji(phase)} {phase}
            </div>
            <div class="metric-label">Phase</div>
        </div>""", unsafe_allow_html=True)

    st.markdown("<div style='margin:8px 0'></div>", unsafe_allow_html=True)

    # โ”€โ”€ Chat area โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    chat_container = st.container()

    with chat_container:
        st.markdown('<div class="chat-scroll">', unsafe_allow_html=True)

        if not st.session_state.messages:
            st.markdown("""
            <div style="text-align:center;padding:40px;color:#6B6B85;font-size:14px">
                Session started. Type your first message below.
            </div>""", unsafe_allow_html=True)

        for msg in st.session_state.messages:
            if msg["role"] == "user":
                st.markdown(f"""
                <div class="chat-user">
                    <div class="bubble">{msg["content"]}</div>
                </div>""", unsafe_allow_html=True)
            else:
                phase     = msg.get("phase", "MODEL")
                mastery   = msg.get("mastery", 0.0)
                suggestion= msg.get("suggestion", "")
                st.markdown(f"""
                <div class="chat-tutor">
                    <div class="avatar" style="background:{phase_color(phase)}22;color:{phase_color(phase)}">
                        {phase_emoji(phase)}
                    </div>
                    <div>
                        <div><span class="phase-badge phase-{phase}">{phase}</span>
                        <span style="font-size:11px;color:#6B6B85;margin-left:6px">
                            mastery {mastery:.3f}
                        </span></div>
                        <div class="bubble">{msg["content"]}</div>
                        {f'<div class="suggestion">๐Ÿ’ก {suggestion}</div>' if suggestion else ''}
                    </div>
                </div>""", unsafe_allow_html=True)

        st.markdown('</div>', unsafe_allow_html=True)

    st.markdown("<div style='margin:8px 0'></div>", unsafe_allow_html=True)

    # โ”€โ”€ Input area โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    with st.form("chat_form", clear_on_submit=True):
        col_inp, col_btn = st.columns([5, 1])
        with col_inp:
            user_input = st.text_input(
                "Message",
                placeholder="Type your message here...",
                label_visibility="collapsed",
            )
        with col_btn:
            submitted = st.form_submit_button("Send โ†’", use_container_width=True)

    if submitted and user_input.strip():
        with st.spinner("Vidya is thinking..."):
            try:
                output = sess.process_turn(user_input.strip())
                st.session_state.turn_count += 1
                turn = st.session_state.turn_count

                # Save messages
                st.session_state.messages.append({
                    "role": "user", "content": user_input.strip()
                })
                st.session_state.messages.append({
                    "role":       "assistant",
                    "content":    output["tutor_response"],
                    "phase":      output["updated_ca_phase"],
                    "mastery":    sess.mastery_level,
                    "suggestion": output.get("suggested_next_action", ""),
                    "signals":    output["_debug"]["signal_scores"],
                })

                # Track history
                st.session_state.phase_history.append((turn, output["updated_ca_phase"]))
                st.session_state.mastery_history.append((turn, sess.mastery_level))

                # Show off-topic warning
                if not output.get("on_topic_flag", True):
                    st.warning("โš ๏ธ Off-topic detected โ€” Vidya redirected to the skill topic.")

                st.rerun()

            except Exception as e:
                st.error(f"Error: {e}")

    # โ”€โ”€ Bottom tabs โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    st.markdown("---")
    tab1, tab2, tab3 = st.tabs(["๐Ÿ“ˆ Mastery Chart", "๐Ÿ” Debug Output", "๐Ÿ“‹ Session Log"])

    with tab1:
        if st.session_state.mastery_history:
            import pandas as pd
            df = pd.DataFrame(st.session_state.mastery_history, columns=["Turn", "Mastery"])
            # Add phase boundaries
            st.line_chart(df.set_index("Turn"), color="#7C6FF7", height=200)

            # ICP threshold reference
            icp = sess.config.icp_type
            from src.icp_profiles import get_icp
            profile = get_icp(icp)
            thresholds = profile["phase_thresholds"]
            st.markdown(f"""
            <div style="display:flex;gap:16px;flex-wrap:wrap;margin-top:8px">
                {''.join(f'<span style="font-size:12px;color:{phase_color(p)}">{p}: {lo:.2f}โ€“{hi:.2f}</span>'
                for p, (lo, hi) in thresholds.items())}
            </div>""", unsafe_allow_html=True)
        else:
            st.caption("Start chatting to see mastery chart.")

    with tab2:
        if st.session_state.messages:
            last_tutor = next(
                (m for m in reversed(st.session_state.messages) if m["role"] == "assistant"), None
            )
            if last_tutor and "signals" in last_tutor:
                st.markdown('<div class="sec-header">Last Turn Signal Scores</div>', unsafe_allow_html=True)
                sigs = last_tutor["signals"]
                cols = st.columns(3)
                for i, (sig, val) in enumerate(sigs.items()):
                    with cols[i % 3]:
                        color = signal_color(val)
                        st.markdown(f"""
                        <div class="metric-box" style="margin-bottom:8px">
                            <div class="metric-val" style="color:{color};font-size:18px">{val:.0f}</div>
                            <div class="metric-label">{sig}</div>
                        </div>""", unsafe_allow_html=True)
        else:
            st.caption("Debug info appears after first message.")

    with tab3:
        if st.session_state.messages:
            log_data = {
                "config": sess.config.model_dump(),
                "final_phase": sess.current_phase,
                "final_mastery": round(sess.mastery_level, 3),
                "turns": st.session_state.turn_count,
                "signal_scorecard": sess.scorecard.to_dict(),
                "conversation": [
                    {"role": m["role"], "content": m["content"]}
                    for m in st.session_state.messages
                ],
            }
            st.json(log_data)

            if st.button("๐Ÿ’พ Save Session Log"):
                try:
                    sess.save_log()
                    st.success("Saved to logs/conversations.json")
                except Exception as e:
                    st.error(f"Save failed: {e}")
        else:
            st.caption("Session log appears after first message.")