File size: 22,744 Bytes
ce2ab3b
 
 
 
2df101a
ce2ab3b
2df101a
93170e8
5aeab82
 
93170e8
 
 
ce2ab3b
 
2df101a
 
 
 
 
 
 
 
 
 
 
 
 
 
7076ebb
ce2ab3b
 
2df101a
 
ce2ab3b
 
2df101a
ce2ab3b
2df101a
 
ce2ab3b
2df101a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce2ab3b
2df101a
 
 
 
 
 
 
 
 
 
 
 
7076ebb
2df101a
 
 
 
 
 
 
 
 
5aeab82
 
 
7076ebb
5aeab82
 
 
 
7076ebb
5aeab82
ce2ab3b
5aeab82
 
 
 
 
7076ebb
 
5aeab82
 
 
 
 
 
 
 
 
 
 
 
 
7076ebb
 
ce2ab3b
2df101a
93170e8
5aeab82
93170e8
 
 
 
 
5aeab82
 
 
 
 
7076ebb
 
5aeab82
93170e8
 
5aeab82
 
 
93170e8
 
 
 
 
 
 
 
5aeab82
 
 
 
 
 
7076ebb
 
5aeab82
 
 
 
 
7076ebb
 
93170e8
 
2df101a
 
 
 
ce2ab3b
 
 
2df101a
 
 
ce2ab3b
2df101a
 
 
 
ce2ab3b
 
 
2df101a
 
 
ce2ab3b
2df101a
 
ce2ab3b
 
2df101a
 
 
 
ce2ab3b
2df101a
 
 
 
 
ce2ab3b
2df101a
 
ce2ab3b
 
 
 
 
 
2df101a
 
ce2ab3b
 
 
 
2df101a
 
 
 
ce2ab3b
 
 
 
 
 
2df101a
ce2ab3b
2df101a
ce2ab3b
 
 
2df101a
 
ce2ab3b
 
 
 
 
 
 
2df101a
 
 
 
 
 
5aeab82
e632d44
 
 
 
 
5aeab82
e632d44
 
5aeab82
e632d44
 
 
 
 
5aeab82
e632d44
 
 
 
5aeab82
e632d44
 
 
 
 
5aeab82
 
e632d44
93170e8
5aeab82
93170e8
5aeab82
 
 
7076ebb
5aeab82
 
 
 
 
 
 
 
 
 
 
 
 
93170e8
 
 
5aeab82
2df101a
 
93170e8
2df101a
 
93170e8
ce2ab3b
 
2df101a
ce2ab3b
 
 
 
 
2df101a
 
 
 
 
 
 
ce2ab3b
 
 
 
 
2df101a
 
ce2ab3b
2df101a
 
ce2ab3b
 
 
2df101a
 
ce2ab3b
 
 
 
 
2df101a
 
ce2ab3b
 
 
 
2df101a
 
ce2ab3b
 
 
 
2df101a
 
 
ce2ab3b
2df101a
 
 
ce2ab3b
 
2df101a
ce2ab3b
 
 
 
 
2df101a
 
 
 
 
 
 
 
 
ce2ab3b
 
 
 
 
 
2df101a
ce2ab3b
2df101a
 
ce2ab3b
 
 
2df101a
ce2ab3b
 
 
93170e8
 
5aeab82
93170e8
 
 
 
 
 
 
ce2ab3b
93170e8
ce2ab3b
 
 
 
 
5aeab82
 
 
 
 
7076ebb
 
 
 
 
5aeab82
 
 
 
 
 
7076ebb
5aeab82
 
 
2df101a
 
ce2ab3b
2df101a
ce2ab3b
 
2df101a
ce2ab3b
 
2df101a
 
 
 
 
ce2ab3b
2df101a
ce2ab3b
2df101a
ce2ab3b
 
2df101a
ce2ab3b
 
 
 
2df101a
ce2ab3b
 
2df101a
 
ce2ab3b
 
2df101a
ce2ab3b
 
 
 
2df101a
ce2ab3b
 
 
2df101a
ce2ab3b
 
2df101a
 
 
 
 
ce2ab3b
2df101a
ce2ab3b
2df101a
ce2ab3b
 
2df101a
 
 
 
 
 
 
 
 
ce2ab3b
 
2df101a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aeab82
2df101a
 
 
 
 
 
5aeab82
2df101a
 
 
 
 
 
 
 
 
ce2ab3b
2df101a
 
 
ce2ab3b
2df101a
 
5aeab82
2df101a
 
 
 
 
 
 
 
 
 
ce2ab3b
 
2df101a
ce2ab3b
2df101a
 
ce2ab3b
2df101a
 
ce2ab3b
 
 
2df101a
 
 
ce2ab3b
 
2df101a
 
 
 
 
 
ce2ab3b
2df101a
ce2ab3b
 
2df101a
ce2ab3b
 
 
 
2df101a
ce2ab3b
 
 
 
 
 
2df101a
ce2ab3b
 
 
 
2df101a
 
ce2ab3b
 
 
2df101a
 
ce2ab3b
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <title>Abliterated Chat</title>
  <script src="https://telegram.org/js/telegram-web-app.js"></script>

  <!-- Markdown & Syntax Highlighting -->
  <script src="https://cdn.jsdelivr.net/npm/marked@9.0.3/marked.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>

  <style>
    :root {
      --bg:        #0b0b0d;
      --panel:     #141418;
      --panel2:    #1c1c22;
      --border:    #2a2a33;
      --text:      #e8e8ed;
      --muted:     #8a8a94;
      --accent:    #6366f1;
      --user-bg:   #1e1b4b;
      --assist-bg: #1a1a20;
      --danger:    #ef4444;
      --ok:        #22c55e;
      --warn:      #f59e0b;
    }
    * { box-sizing: border-box; margin: 0; padding: 0; -webkit-tap-highlight-color: transparent; }
    html, body { height: 100%; overflow: hidden; width: 100%; }
    body {
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
      background: var(--bg); color: var(--text);
      display: flex; font-size: 14px;
    }

    /* ── Sidebar ── */
    #sidebar {
      width: 240px; flex-shrink: 0;
      background: var(--panel);
      border-right: 1px solid var(--border);
      display: flex; flex-direction: column;
      padding: 12px; gap: 10px;
      transition: transform 0.2s;
    }
    #sidebar.hidden { transform: translateX(-100%); position: absolute; height: 100%; z-index: 10; }
    #sidebar h1 { font-size: 12px; color: var(--muted); font-weight: 600; letter-spacing: 0.5px; padding: 4px; }
    .btn {
      padding: 10px 12px; border-radius: 8px; border: 1px solid var(--border);
      background: var(--panel2); color: var(--text); cursor: pointer;
      font-size: 13px; display: flex; align-items: center; gap: 8px;
      transition: background 0.15s, border-color 0.15s;
    }
    .btn:hover { background: #24242c; border-color: #3a3a45; }
    .btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; font-weight: 500; }
    .btn.primary:hover { background: #4f46e5; }
    .btn:disabled { opacity: 0.5; cursor: not-allowed; }
    #chat-list { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 4px; }
    .chat-item {
      padding: 8px 10px; border-radius: 6px; cursor: pointer;
      font-size: 13px; color: var(--text); display: flex;
      justify-content: space-between; align-items: center; gap: 6px;
    }
    .chat-item:hover { background: var(--panel2); }
    .chat-item.active { background: #1e1b4b; }
    .chat-item .title { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .chat-item .del { color: var(--muted); opacity: 0; font-size: 15px; }
    .chat-item:hover .del { opacity: 1; }
    .chat-item .del:hover { color: var(--danger); }

    /* ── Main ── */
    #main { flex: 1; display: flex; flex-direction: column; min-width: 0; /* CRITICAL FIX */ }
    #header {
      padding: 10px 16px; border-bottom: 1px solid var(--border);
      display: flex; align-items: center; gap: 10px; flex-shrink: 0;
    }
    #menu-btn { background: none; border: none; color: var(--text); font-size: 20px; cursor: pointer; padding: 4px; }
    #header .title { font-weight: 600; font-size: 14px; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    #header .model { font-size: 11px; color: var(--muted); background: var(--panel2); padding: 3px 8px; border-radius: 999px; }

    /* ── Messages ── */
    #messages { 
      flex: 1; 
      overflow-y: auto; 
      overflow-x: hidden; 
      padding: 16px; 
      display: flex; 
      flex-direction: column; 
      gap: 12px; 
      min-width: 0; /* CRITICAL FIX */
    }
    .msg {
      padding: 10px 14px; 
      border-radius: 12px;
      line-height: 1.55; 
      word-wrap: break-word;
      overflow-wrap: break-word;
      min-width: 0; /* CRITICAL FIX: Allows flex child to shrink */
      max-width: 100%;
    }
    .msg.user { 
      align-self: flex-end; 
      background: var(--user-bg); 
      border: 1px solid #3730a3; 
      white-space: pre-wrap; 
      width: fit-content;
      max-width: 85%;
    }
    .msg.assistant { 
      align-self: flex-start; 
      background: var(--assist-bg); 
      border: 1px solid var(--border); 
      width: 100%;
      overflow: hidden; /* CRITICAL FIX: Prevents child from pushing parent out */
    }
    .msg.error { align-self: center; background: #2a1414; border: 1px solid #7f1d1d; color: #fca5a5; font-size: 12px; }

    /* Markdown styles */
    .msg.assistant p { margin-bottom: 8px; }
    .msg.assistant p:last-child { margin-bottom: 0; }
    .msg.assistant h1, .msg.assistant h2, .msg.assistant h3 { margin: 12px 0 6px; font-size: 1.1em; }
    .msg.assistant ul, .msg.assistant ol { margin-left: 20px; margin-bottom: 8px; }

    /* Code block layout */
    .code-block-wrapper { 
      margin: 10px 0; 
      border-radius: 8px;
      border: 1px solid var(--border);
      overflow: hidden; 
      max-width: 100%; /* CRITICAL FIX */
    }
    .code-block-header {
      display: flex; justify-content: space-between; align-items: center;
      background: #1e1e24; padding: 6px 12px;
      font-size: 11px; color: var(--muted); 
      border-bottom: 1px solid var(--border);
    }
    .copy-btn {
      background: #2a2a33; border: 1px solid #3a3a45; color: var(--text);
      border-radius: 4px; padding: 2px 8px; cursor: pointer; font-size: 11px;
      transition: background 0.2s;
    }
    .copy-btn:hover { background: #3a3a45; }
    .copy-btn.copied { background: var(--ok); border-color: var(--ok); color: #000; }
    
    /* Code scrolling */
    .msg.assistant pre {
      margin: 0;
      padding: 12px;
      background: #111115;
      overflow-x: auto; 
      max-width: 100%;
      -webkit-overflow-scrolling: touch;
    }
    .msg.assistant code {
      font-family: "SF Mono", "Fira Code", monospace;
      font-size: 13px;
      white-space: pre; 
      word-break: normal; 
    }

    .msg .cursor {
      display: inline-block; width: 7px; height: 14px;
      background: var(--accent); margin-left: 2px; vertical-align: text-bottom;
      animation: blink 1s steps(2) infinite; border-radius: 1px;
    }
    @keyframes blink { 50% { opacity: 0; } }

    /* ── Composer ── */
    #composer { padding: 10px 16px 14px; border-top: 1px solid var(--border); flex-shrink: 0; }
    #composer-inner { display: flex; gap: 8px; align-items: flex-end; max-width: 820px; margin: 0 auto; }
    #prompt {
      flex: 1; resize: none; border: 1px solid var(--border); border-radius: 10px;
      padding: 10px 12px; font-family: inherit; font-size: 14px; line-height: 1.4;
      background: var(--panel2); color: var(--text);
      min-height: 44px; max-height: 160px; outline: none;
      transition: border-color 0.15s;
    }
    #prompt:focus { border-color: var(--accent); }
    #send-btn, #stop-btn {
      height: 44px; padding: 0 16px; border-radius: 10px; border: none;
      cursor: pointer; font-size: 14px; font-weight: 500; transition: opacity 0.15s;
    }
    #send-btn { background: var(--accent); color: #fff; }
    #stop-btn { background: var(--danger); color: #fff; display: none; }
    #send-btn:disabled { opacity: 0.5; cursor: not-allowed; }

    /* ── Token meter ── */
    #token-meter { max-width: 820px; margin: 8px auto 0; font-size: 11px; color: var(--muted); }
    #token-bar-bg { height: 4px; background: var(--border); border-radius: 2px; overflow: hidden; margin-top: 4px; }
    #token-bar { height: 100%; width: 0%; background: var(--ok); transition: width 0.3s, background 0.3s; }

    /* ── Mobile ── */
    @media (max-width: 640px) {
      #sidebar { position: absolute; height: 100%; z-index: 20; box-shadow: 4px 0 24px rgba(0,0,0,0.5); }
      #sidebar.hidden { transform: translateX(-100%); }
      #menu-btn { display: block; }
    }
    @media (min-width: 641px) {
      #menu-btn { display: none; }
    }
  </style>
</head>
<body>

  <aside id="sidebar">
    <h1>YOUR CHATS</h1>
    <button class="btn primary" id="new-chat-btn">➕ New chat</button>
    <div id="chat-list"></div>
  </aside>

  <main id="main">
    <header id="header">
      <button id="menu-btn" title="Menu">☰</button>
      <span class="title" id="header-title">New chat</span>
      <span class="model" id="model-tag">…</span>
    </header>

    <div id="messages"></div>

    <div id="composer">
      <div id="composer-inner">
        <textarea id="prompt" rows="1" placeholder="Message the model…"></textarea>
        <button id="send-btn">Send</button>
        <button id="stop-btn">Stop</button>
      </div>
      <div id="token-meter">
        <div style="display:flex;justify-content:space-between;">
          <span>📊 Context</span>
          <span id="token-text">0 / 0</span>
        </div>
        <div id="token-bar-bg"><div id="token-bar"></div></div>
      </div>
    </div>
  </main>

  <script>
    const tg = window.Telegram?.WebApp;
    if (tg) { try { tg.ready(); tg.expand(); } catch (e) {} }
    function haptic(kind = "light") {
      try { tg?.HapticFeedback?.impactOccurred(kind); } catch (e) {}
    }

    // ── Markdown Setup ────────────────────────────────────────────────────
    const markedLib = window.marked;
    const hljsLib = window.hljs;

    if (markedLib && hljsLib) {
      const renderer = new markedLib.Renderer();
      
      renderer.code = function (code, language) {
        const validLang = language && hljsLib.getLanguage(language) ? language : 'plaintext';
        let highlighted = code;
        try {
          highlighted = hljsLib.highlight(code, { language: validLang }).value;
        } catch (e) {
          highlighted = code.replace(/[&<>]/g, (m) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[m]));
        }
        
        return `
          <div class="code-block-wrapper">
            <div class="code-block-header">
              <span>${validLang}</span>
              <button class="copy-btn">Copy</button>
            </div>
            <pre><code class="hljs language-${validLang}">${highlighted}</code></pre>
          </div>`;
      };

      markedLib.use({ renderer });
      markedLib.setOptions({ breaks: true, gfm: true });
    }

    // Copy logic using DOM traversal
    document.addEventListener('click', async (e) => {
      if (e.target.classList.contains('copy-btn')) {
        const btn = e.target;
        const codeBlock = btn.closest('.code-block-wrapper').querySelector('code');
        const code = codeBlock.innerText; 
        
        try {
          await navigator.clipboard.writeText(code);
          btn.textContent = 'Copied!';
          btn.classList.add('copied');
          setTimeout(() => {
            btn.textContent = 'Copy';
            btn.classList.remove('copied');
          }, 2000);
        } catch (err) {
          btn.textContent = 'Failed';
          setTimeout(() => { btn.textContent = 'Copy'; }, 2000);
        }
      }
    });

    // ── State & Constants ─────────────────────────────────────────────────
    const STORAGE_KEY = "ablt_v1";
    const ACTIVE_KEY  = "ablt_active_v1";
    const MAX_TOKENS  = 6144;

    const state = {
      sessions: [],
      activeId: null,
      streaming: false,
      abortController: null,
    };

    const $ = (id) => document.getElementById(id);
    const messagesEl = $("messages");
    const chatListEl = $("chat-list");
    const promptEl   = $("prompt");
    const sendBtn    = $("send-btn");
    const stopBtn    = $("stop-btn");
    const tokenBar   = $("token-bar");
    const tokenText  = $("token-text");

    // ── Persistence ───────────────────────────────────────────────────────
    function save() {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(state.sessions));
      localStorage.setItem(ACTIVE_KEY, state.activeId || "");
    }
    function load() {
      try { state.sessions = JSON.parse(localStorage.getItem(STORAGE_KEY) || "[]"); }
      catch { state.sessions = []; }
      state.activeId = localStorage.getItem(ACTIVE_KEY) || null;
      if (!state.sessions.length) createSession();
      else if (!state.sessions.some(s => s.id === state.activeId))
        state.activeId = state.sessions[0].id;
    }

    // ── Sessions ──────────────────────────────────────────────────────────
    const active = () => state.sessions.find(s => s.id === state.activeId) || null;

    function createSession() {
      const id = crypto.randomUUID();
      state.sessions.unshift({ id, title: "New chat", messages: [] });
      state.activeId = id;
      save(); renderSidebar(); renderMessages(); updateMeter();
      if (window.innerWidth > 640) promptEl.focus();
    }
    function switchSession(id) {
      if (state.streaming) return;
      state.activeId = id;
      save(); renderSidebar(); renderMessages(); updateMeter();
      $("sidebar").classList.add("hidden");
    }
    function deleteSession(id) {
      if (state.streaming) return;
      state.sessions = state.sessions.filter(s => s.id !== id);
      if (!state.sessions.length) return createSession();
      if (state.activeId === id) state.activeId = state.sessions[0].id;
      save(); renderSidebar(); renderMessages(); updateMeter();
    }
    function deriveTitle(t) {
      const x = (t || "").trim().replace(/\s+/g, " ");
      return x.length > 36 ? x.slice(0, 36) + "…" : (x || "New chat");
    }

    // ── Rendering ─────────────────────────────────────────────────────────
    function renderSidebar() {
      chatListEl.innerHTML = "";
      state.sessions.forEach(s => {
        const el = document.createElement("div");
        el.className = "chat-item" + (s.id === state.activeId ? " active" : "");
        const title = document.createElement("span");
        title.className = "title";
        title.textContent = s.title;
        const del = document.createElement("span");
        del.className = "del";
        del.textContent = "✕";
        title.onclick = () => switchSession(s.id);
        del.onclick = (e) => { e.stopPropagation(); deleteSession(s.id); };
        el.appendChild(title); el.appendChild(del);
        chatListEl.appendChild(el);
      });
    }

    function renderMessages() {
      messagesEl.innerHTML = "";
      const s = active();
      if (!s) return;
      $("header-title").textContent = s.title;
      s.messages.forEach(m => appendBubble(m.role, m.content));
      messagesEl.scrollTop = messagesEl.scrollHeight;
    }

    function appendBubble(role, content, streaming = false) {
      const el = document.createElement("div");
      el.className = `msg ${role}`;
      el.dataset.streaming = streaming ? "1" : "0";

      if (role === "assistant") {
        el.innerHTML = parseMarkdownSafe(content);
        if (streaming) {
          const c = document.createElement("span");
          c.className = "cursor";
          el.appendChild(c);
        }
      } else {
        el.textContent = content;
      }

      messagesEl.appendChild(el);
      messagesEl.scrollTop = messagesEl.scrollHeight;
      return el;
    }

    // Helper to safely parse markdown during streaming
    function parseMarkdownSafe(text) {
      if (!markedLib) return text;
      
      let safeText = text;
      // Count triple backticks. If odd, it means a block is currently open.
      const backtickMatches = safeText.match(/```/g);
      const backtickCount = backtickMatches ? backtickMatches.length : 0;
      
      if (backtickCount % 2 !== 0) {
        safeText += "\n```";
      }
      
      try {
        return markedLib.parse(safeText);
      } catch (e) {
        return text;
      }
    }

    function updateMeter() {
      const s = active();
      if (!s) return;
      fetch("/api/count_tokens", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ history: s.messages, system_prompt: "" }),
      })
        .then(r => r.json())
        .then(d => {
          const n = d.tokens || 0;
          const max = d.max || MAX_TOKENS;
          const pct = Math.min((n / max) * 100, 100);
          tokenText.textContent = `${n.toLocaleString()} / ${max.toLocaleString()}`;
          tokenBar.style.width = pct + "%";
          tokenBar.style.background = pct < 50 ? "var(--ok)" : pct < 80 ? "var(--warn)" : "var(--danger)";
        })
        .catch(() => {});
    }

    // ── Streaming ─────────────────────────────────────────────────────────
    async function sendMessage() {
      if (state.streaming) return;
      const text = promptEl.value.trim();
      if (!text) return;
      const s = active();
      if (!s) return;

      haptic("light");

      if (s.title === "New chat") {
        s.title = deriveTitle(text);
        $("header-title").textContent = s.title;
        renderSidebar();
      }

      s.messages.push({ role: "user", content: text });
      appendBubble("user", text);
      promptEl.value = "";
      autoResize();

      const bubble = appendBubble("assistant", "", true);
      const priorHistory = s.messages.slice(0, -1);

      state.streaming = true;
      state.abortController = new AbortController();
      sendBtn.disabled = true;
      sendBtn.style.display = "none";
      stopBtn.style.display = "block";

      let finalText = "";
      try {
        const res = await fetch("/api/chat", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            message: text,
            history: priorHistory,
            system_prompt: "",
            max_new_tokens: 256,
            temperature: 0.7,
            top_p: 0.9,
          }),
          signal: state.abortController.signal,
        });

        if (!res.ok) throw new Error(`HTTP ${res.status}`);

        const reader = res.body.getReader();
        const decoder = new TextDecoder();
        let buffer = "";

        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          buffer += decoder.decode(value, { stream: true });

          const parts = buffer.split("\n\n");
          buffer = parts.pop();

          for (const part of parts) {
            if (!part.startsWith("data: ")) continue;
            let data;
            try { data = JSON.parse(part.slice(6)); } catch { continue; }

            if (data.type === "token") {
              finalText = data.content;
              bubble.innerHTML = parseMarkdownSafe(finalText);
              const c = document.createElement("span");
              c.className = "cursor";
              bubble.appendChild(c);
              messagesEl.scrollTop = messagesEl.scrollHeight;
            } else if (data.type === "done") {
              finalText = data.content;
              bubble.innerHTML = markedLib ? markedLib.parse(finalText) : finalText;
              bubble.dataset.streaming = "0";
              s.messages.push({ role: "assistant", content: finalText });
            } else if (data.type === "error") {
              bubble.dataset.streaming = "0";
              bubble.className = "msg error";
              bubble.textContent = `⚠️ ${data.content}`;
            }
          }
        }

        if (finalText && !s.messages.some(m => m.role === "assistant" && m.content === finalText)) {
          s.messages.push({ role: "assistant", content: finalText });
        }
      } catch (err) {
        if (err.name === "AbortError") {
          if (finalText) {
            bubble.innerHTML = markedLib ? markedLib.parse(finalText) : finalText;
            bubble.dataset.streaming = "0";
            s.messages.push({ role: "assistant", content: finalText });
          } else {
            bubble.remove();
          }
        } else {
          bubble.dataset.streaming = "0";
          bubble.className = "msg error";
          bubble.textContent = `⚠️ ${err.message}`;
        }
      } finally {
        state.streaming = false;
        state.abortController = null;
        sendBtn.disabled = false;
        sendBtn.style.display = "block";
        stopBtn.style.display = "none";
        save();
        updateMeter();
        promptEl.focus();
      }
    }

    function stopGeneration() {
      haptic("medium");
      state.abortController?.abort();
    }

    // ── UI wiring ─────────────────────────────────────────────────────────
    $("new-chat-btn").onclick = () => {
      haptic("light");
      if (!state.streaming) createSession();
    };
    $("menu-btn").onclick = () => $("sidebar").classList.toggle("hidden");
    sendBtn.onclick = sendMessage;
    stopBtn.onclick = stopGeneration;

    promptEl.addEventListener("keydown", (e) => {
      if (e.key === "Enter" && !e.shiftKey && window.innerWidth > 640) {
        e.preventDefault();
        sendMessage();
      }
    });
    promptEl.addEventListener("input", autoResize);

    function autoResize() {
      promptEl.style.height = "auto";
      promptEl.style.height = Math.min(promptEl.scrollHeight, 160) + "px";
    }

    // ── Boot ──────────────────────────────────────────────────────────────
    (async function init() {
      load();
      renderSidebar();
      renderMessages();
      updateMeter();
      if (window.innerWidth <= 640) $("sidebar").classList.add("hidden");

      try {
        const h = await (await fetch("/health")).json();
        $("model-tag").textContent = h.model?.split("/").pop() || "model";
      } catch { $("model-tag").textContent = "online"; }
    })();
  </script>
</body>
</html>