File size: 34,111 Bytes
c16538d
bb18161
 
 
04956a8
bb18161
 
 
 
 
 
 
 
 
 
 
 
 
04956a8
 
 
 
 
 
 
 
 
 
 
f11837d
04956a8
 
f11837d
f05d55a
 
 
 
 
 
 
 
 
 
 
 
 
04956a8
bb18161
 
04956a8
 
 
bb18161
04956a8
 
 
 
 
 
 
 
 
 
 
 
51d39d2
bb18161
 
d69031c
 
b66135b
51d39d2
04956a8
 
f11837d
51d39d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04956a8
51d39d2
b66135b
 
 
 
 
 
04956a8
 
bb18161
 
 
04956a8
 
 
bb18161
 
 
51d39d2
bb18161
d69031c
 
 
 
 
04956a8
 
 
 
 
 
 
 
f11837d
f32f88c
04956a8
 
f32f88c
 
 
04956a8
 
bb18161
 
 
 
f11837d
 
 
 
 
 
 
 
 
 
f05d55a
 
f11837d
 
 
 
 
 
119757f
b6b6593
f11837d
 
 
 
 
 
 
 
119757f
d35ba82
f11837d
 
b6b6593
f11837d
 
 
 
b6b6593
f11837d
 
 
b6b6593
f11837d
 
 
 
 
 
b6b6593
f05d55a
f11837d
 
 
f05d55a
 
 
 
 
 
f11837d
 
 
 
f05d55a
 
 
 
 
 
 
 
 
 
f11837d
 
 
 
f05d55a
 
f11837d
f05d55a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f11837d
 
b6b6593
f11837d
 
 
 
 
 
 
 
 
 
 
 
b6b6593
f11837d
 
 
 
 
b6b6593
f11837d
 
 
 
 
 
 
 
 
 
 
 
119757f
d35ba82
f11837d
 
 
 
d35ba82
f11837d
 
 
119757f
d35ba82
f11837d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6b6593
f11837d
 
 
 
 
 
 
b6b6593
f11837d
 
 
 
 
 
 
 
 
 
 
 
b6b6593
f11837d
 
 
 
b6b6593
f11837d
 
b6b6593
f11837d
 
 
 
 
 
b6b6593
f11837d
 
 
b6b6593
f11837d
 
 
b6b6593
f11837d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6b6593
f11837d
 
 
 
f05d55a
f11837d
 
b6b6593
f11837d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f05d55a
f11837d
 
 
 
b6b6593
f11837d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6b6593
f11837d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f05d55a
f11837d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f05d55a
f11837d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f05d55a
f11837d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6b6593
f11837d
 
 
 
 
 
 
 
 
 
 
 
 
9db3fad
f05d55a
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" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>AI Developer Hub</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.0.6/purify.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>
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: { extend: { colors: { gray: { 850: '#1f2937', 900: '#111827', 950: '#030712' } } } }
        }
    </script>
    <style>
        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: #374151; border-radius: 4px; }
        ::-webkit-scrollbar-thumb:hover { background: #4b5563; }

        .markdown-body { font-size: 0.95rem; line-height: 1.6; }
        .markdown-body p { margin-bottom: 1rem; }
        .markdown-body p:last-child { margin-bottom: 0; }
        .markdown-body code:not(pre code) { background: #374151; padding: 0.2rem 0.4rem; border-radius: 0.25rem; font-size: 0.85em; }
        .markdown-body pre { background: #1e1e1e; padding: 2.5rem 1rem 1rem 1rem; border-radius: 0.5rem; position: relative; overflow-x: auto; margin-bottom: 1rem; }
        .markdown-body pre code { font-size: 0.85rem; }

        .copy-btn { position: absolute; top: 0.5rem; right: 0.5rem; background: #4b5563; color: #e5e7eb; border: none; padding: 0.25rem 0.75rem; border-radius: 0.375rem; cursor: pointer; font-size: 0.75rem; transition: background 0.2s; }
        .copy-btn:hover { background: #6b7280; }

        .expand-btn { position: absolute; top: 0.5rem; right: 4.5rem; background: #4b5563; color: #e5e7eb; border: none; padding: 0.25rem 0.75rem; border-radius: 0.375rem; cursor: pointer; font-size: 0.75rem; transition: background 0.2s; }
        .expand-btn:hover { background: #6b7280; }

        .markdown-body pre.snippet-collapsed { max-height: 8rem; overflow: hidden !important; }
        .markdown-body pre.snippet-collapsed::after {
            content: "";
            position: absolute;
            bottom: 0; left: 0; right: 0;
            height: 3rem;
            background: linear-gradient(transparent, #1e1e1e);
            pointer-events: none;
        }

        .reasoning-block { border-left: 3px solid #6366f1; padding-left: 1rem; margin-bottom: 1rem; color: #9ca3af; font-size: 0.9em; background: rgba(99, 102, 241, 0.05); padding: 0.75rem; border-radius: 0 0.5rem 0.5rem 0; }
    </style>
</head>
<body class="bg-gray-950 text-gray-200 h-[100dvh] flex font-sans overflow-hidden antialiased">

    <div id="mobile-overlay" class="fixed inset-0 bg-black/60 z-20 hidden lg:hidden transition-opacity" onclick="toggleSidebar()"></div>

    <aside id="sidebar" class="absolute lg:relative z-30 inset-y-0 left-0 w-72 lg:w-64 bg-gray-900 border-r border-gray-800 transform -translate-x-full lg:translate-x-0 transition-transform duration-300 ease-in-out flex flex-col shadow-2xl lg:shadow-none">
        <div class="p-4 border-b border-gray-800 flex justify-between items-center bg-gray-900">
            <h1 class="font-bold text-lg text-white tracking-wide">Dev AI Hub</h1>
            <div class="flex items-center gap-2">
                <button onclick="createNewChat()" class="p-2 text-blue-400 hover:text-blue-300 bg-gray-800 rounded-md transition" title="New Chat">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                </button>
                <button onclick="toggleSidebar()" class="p-2 text-gray-400 hover:text-white lg:hidden">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                </button>
            </div>
        </div>
        <div id="chat-list" class="flex-1 overflow-y-auto p-3 space-y-2"></div>
    </aside>

    <main class="flex-1 flex flex-col h-full w-full bg-gray-950 min-w-0 relative">
        <header class="h-14 min-h-[3.5rem] border-b border-gray-800 flex items-center px-4 lg:px-6 justify-between bg-gray-900/80 backdrop-blur-sm z-10 shrink-0">
            <div class="flex items-center gap-3 overflow-hidden group w-full max-w-[45%]">
                <button onclick="toggleSidebar()" class="lg:hidden p-1 -ml-1 text-gray-400 hover:text-white shrink-0">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path></svg>
                </button>

                <div id="title-display" class="flex items-center gap-2 overflow-hidden w-full">
                    <h2 id="current-chat-title" class="font-semibold text-gray-100 truncate text-sm lg:text-base">Select or create a chat</h2>
                    <button onclick="enableTitleEdit()" id="edit-title-btn" class="hidden text-gray-500 hover:text-blue-400 p-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0" title="Rename Chat">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"></path></svg>
                    </button>
                </div>

                <div id="title-edit" class="hidden items-center gap-2 w-full">
                    <input type="text" id="title-input" class="bg-gray-800 text-sm lg:text-base text-gray-100 border border-blue-500 rounded px-2 py-1 outline-none w-full" />
                    <button onclick="saveTitle()" class="text-blue-400 hover:text-blue-300 p-1 shrink-0 bg-gray-800 rounded">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
                    </button>
                    <button onclick="cancelTitleEdit()" class="text-gray-400 hover:text-red-400 p-1 shrink-0 bg-gray-800 rounded">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                    </button>
                </div>
            </div>

            <div class="flex items-center gap-3 lg:gap-4 shrink-0 pl-2">
                <div class="hidden sm:flex flex-col items-end text-[10px] text-blue-300 bg-blue-900/30 border border-blue-800/50 px-2 py-1 rounded-md font-mono leading-tight">
                    <span class="font-semibold text-[11px]">Total: <span id="token-total">0</span></span>
                    <span class="text-blue-400/70">In: <span id="token-in">0</span> | Out: <span id="token-out">0</span></span>
                </div>

                <select id="model-select" class="bg-gray-800 text-xs lg:text-sm rounded-md border border-gray-700 px-2 py-1.5 outline-none focus:border-blue-500 transition-colors cursor-pointer text-gray-200">
                    <option value="claude">Claude Sonnet 4.6</option>
                    <option value="haiku">Claude Haiku</option>
                    <option value="maverick">Llama 3 Maverick</option>
                </select>
                <button onclick="deleteCurrentChat()" class="text-gray-500 hover:text-red-400 transition-colors p-1" title="Delete Chat">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                </button>
            </div>
        </header>

        <div id="chat-window" class="flex-1 overflow-y-auto p-4 lg:p-6 space-y-6 scroll-smooth"></div>

        <button id="scroll-bottom-btn" onclick="scrollToBottom()" class="hidden absolute bottom-28 right-8 p-2 bg-gray-800/80 hover:bg-gray-700 text-gray-300 hover:text-white rounded-full shadow-lg border border-gray-700 backdrop-blur-sm transition-all z-20">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 14l-7 7m0 0l-7-7m7 7V3"></path></svg>
        </button>

        <div class="p-3 lg:p-4 bg-gray-900 border-t border-gray-800 shrink-0 relative z-30">
            <div class="max-w-4xl mx-auto">
                <div id="image-preview-container" class="flex flex-wrap gap-2 mb-2 hidden px-1"></div>
                <div class="flex items-end gap-2 bg-gray-850 rounded-xl border border-gray-700 p-2 focus-within:border-blue-500 focus-within:ring-1 focus-within:ring-blue-500 transition-all shadow-sm">
                    <label class="cursor-pointer p-2 text-gray-400 hover:text-blue-400 transition shrink-0 rounded-lg hover:bg-gray-800">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                        <input type="file" id="image-input" accept="image/*" multiple class="hidden" onchange="handleImageSelect(event)">
                    </label>
                    <textarea id="message-input" rows="1" class="flex-1 bg-transparent resize-none outline-none text-[15px] p-2 max-h-32 min-h-[40px] text-gray-100 placeholder-gray-500" placeholder="Message the AI..."></textarea>

                    <button onclick="sendMessage()" id="send-btn" class="p-2 text-blue-400 hover:text-blue-300 transition shrink-0 rounded-lg hover:bg-gray-800">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path></svg>
                    </button>
                    <button onclick="stopGeneration()" id="stop-btn" class="hidden p-2 text-red-500 hover:text-red-400 transition shrink-0 rounded-lg hover:bg-gray-800" title="Stop Generation">
                        <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24"><rect x="6" y="6" width="12" height="12" rx="2"></rect></svg>
                    </button>
                </div>
                <div class="text-center mt-2 text-[10px] text-gray-600">Shift + Enter for new line</div>
            </div>
        </div>
    </main>

    <script>
        marked.setOptions({
            highlight: function(code, lang) {
                const language = hljs.getLanguage(lang) ? lang : 'plaintext';
                return hljs.highlight(code, { language }).value;
            }
        });

        // ─── State ────────────────────────────────────────────────────────────────
        let currentChatId   = null;
        let attachedImages  =[];
        let pollingInterval = null;
        let currentTokens   = { total: 0, in: 0, out: 0 };

        // ─── UI Helpers ───────────────────────────────────────────────────────────
        function toggleInputState(isGenerating) {
            document.getElementById('send-btn').classList.toggle('hidden', isGenerating);
            document.getElementById('stop-btn').classList.toggle('hidden', !isGenerating);
        }

        async function stopGeneration() {
            if (!currentChatId) return;
            toggleInputState(false);
            try {
                await fetch(`/api/chats/${currentChatId}/stop`, { method: 'POST' });
            } catch (err) {
                console.error("Failed to send stop signal", err);
            }
        }

        const chatWindow = document.getElementById('chat-window');
        const scrollBtn  = document.getElementById('scroll-bottom-btn');

        chatWindow.addEventListener('scroll', () => {
            const dist = chatWindow.scrollHeight - chatWindow.scrollTop - chatWindow.clientHeight;
            scrollBtn.classList.toggle('hidden', dist <= 100);
        });

        function scrollToBottom() {
            chatWindow.scrollTo({ top: chatWindow.scrollHeight, behavior: 'smooth' });
        }

        function updateTokenDisplay(total, input, output) {
            currentTokens = { total, in: input, out: output };
            document.getElementById('token-total').innerText = (total  || 0).toLocaleString();
            document.getElementById('token-in').innerText   = (input  || 0).toLocaleString();
            document.getElementById('token-out').innerText  = (output || 0).toLocaleString();
        }

        // ─── Copy buttons & snippet collapse ──────────────────────────────────────
        function attachCopyButtons(scope) {
            (scope || document).querySelectorAll('.markdown-body pre').forEach(pre => {
                if (pre.querySelector('.copy-btn')) return;

                const expandBtn = document.createElement('button');
                expandBtn.className = 'expand-btn';
                expandBtn.innerText = 'Expand';
                expandBtn.style.display = 'none';

                const btn = document.createElement('button');
                btn.className  = 'copy-btn';
                btn.innerText  = 'Copy';
                btn.onclick    = () => {
                    const codeBlock = pre.querySelector('code');
                    let text = '';
                    // textContent is used to ensure visibility (like overflow: hidden) doesn't break copied output
                    if (codeBlock) {
                        text = codeBlock.textContent;
                    } else {
                        const clone = pre.cloneNode(true);
                        clone.querySelectorAll('.copy-btn, .expand-btn').forEach(b => b.remove());
                        text = clone.textContent;
                    }
                    navigator.clipboard.writeText(text.trim());
                    btn.innerText = 'Copied!';
                    setTimeout(() => btn.innerText = 'Copy', 2000);
                };
                
                pre.appendChild(expandBtn);
                pre.appendChild(btn);

                // Dynamically apply collapsed state only to snippets that are tall enough
                if (pre.scrollHeight > 160) {
                    pre.classList.add('snippet-collapsed');
                    expandBtn.style.display = 'block';
                    
                    expandBtn.onclick = () => {
                        if (pre.classList.contains('snippet-collapsed')) {
                            pre.classList.remove('snippet-collapsed');
                            expandBtn.innerText = 'Collapse';
                        } else {
                            pre.classList.add('snippet-collapsed');
                            expandBtn.innerText = 'Expand';
                        }
                    };
                }
            });
        }

        // ─── Title editing ────────────────────────────────────────────────────────
        function enableTitleEdit() {
            if (!currentChatId) return;
            document.getElementById('title-display').classList.add('hidden');
            const edit  = document.getElementById('title-edit');
            edit.classList.remove('hidden');
            edit.classList.add('flex');
            const input = document.getElementById('title-input');
            input.value = document.getElementById('current-chat-title').innerText;
            input.focus();
            input.select();
        }

        function cancelTitleEdit() {
            document.getElementById('title-edit').classList.add('hidden');
            document.getElementById('title-edit').classList.remove('flex');
            document.getElementById('title-display').classList.remove('hidden');
        }

        async function saveTitle() {
            if (!currentChatId) return cancelTitleEdit();
            const newTitle = document.getElementById('title-input').value.trim();
            if (!newTitle) return cancelTitleEdit();
            document.getElementById('current-chat-title').innerText = newTitle;
            cancelTitleEdit();
            await fetch(`/api/chats/${currentChatId}/title`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ title: newTitle })
            });
            loadSidebar();
        }

        document.getElementById('title-input').addEventListener('keydown', e => {
            if (e.key === 'Enter')  saveTitle();
            if (e.key === 'Escape') cancelTitleEdit();
        });

        function toggleSidebar() {
            document.getElementById('sidebar').classList.toggle('-translate-x-full');
            document.getElementById('mobile-overlay').classList.toggle('hidden');
        }

        const textarea = document.getElementById('message-input');
        textarea.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = Math.min(this.scrollHeight, 128) + 'px';
        });

        // ─── Sidebar / Chat list ──────────────────────────────────────────────────
        async function loadSidebar() {
            const res   = await fetch('/api/chats');
            const chats = await res.json();
            document.getElementById('chat-list').innerHTML = chats.map(c => `
                <div onclick="selectChat('${c.id}')" class="p-3 rounded-xl cursor-pointer transition border border-transparent ${c.id === currentChatId ? 'bg-gray-800 border-gray-700' : 'hover:bg-gray-800/50'}">
                    <div class="text-sm font-medium truncate text-gray-200">${c.title}</div>
                    <div class="text-[10px] text-gray-500 mt-1 flex justify-between">
                        <span>Total: ${c.totalTokens.toLocaleString()}</span>
                        <span class="opacity-70">↑${(c.outputTokens || 0).toLocaleString()}</span>
                    </div>
                </div>
            `).join('');
        }

        async function createNewChat() {
            const res  = await fetch('/api/chats', { method: 'POST' });
            const chat = await res.json();
            selectChat(chat.id);
            loadSidebar();
            if (window.innerWidth < 1024) toggleSidebar();
        }

        async function deleteCurrentChat() {
            if (!currentChatId) return;
            if (!confirm("Permanently delete this chat?")) return;
            await fetch(`/api/chats/${currentChatId}`, { method: 'DELETE' });
            currentChatId = null;
            document.getElementById('chat-window').innerHTML = '';
            document.getElementById('current-chat-title').innerText = 'Select or create a chat';
            document.getElementById('edit-title-btn').classList.add('hidden');
            updateTokenDisplay(0, 0, 0);
            toggleInputState(false);
            loadSidebar();
        }

        // ─── Select / render chat ─────────────────────────────────────────────────
        async function selectChat(id) {
            currentChatId = id;
            stopPolling();

            const res  = await fetch(`/api/chats/${id}`);
            const chat = await res.json();

            document.getElementById('current-chat-title').innerText = chat.title;
            document.getElementById('edit-title-btn').classList.remove('hidden');
            updateTokenDisplay(chat.totalTokens, chat.inputTokens, chat.outputTokens);
            cancelTitleEdit();
            renderMessages(chat.messages);
            loadSidebar();

            if (window.innerWidth < 1024 && !document.getElementById('sidebar').classList.contains('-translate-x-full')) {
                toggleSidebar();
            }

            toggleInputState(chat.isGenerating);
            if (chat.isGenerating) pollGeneratingChat(id);
        }

        function renderMessages(messages) {
            const isAtBottom = chatWindow.scrollHeight - chatWindow.clientHeight <= chatWindow.scrollTop + 20;

            chatWindow.innerHTML = messages.map(m => {
                let html = '';
                if (m.reasoning) {
                    html += `<div class="reasoning-block"><i>Thinking Process</i><br/>${marked.parse(m.reasoning)}</div>`;
                }
                if (m.content) {
                    html += DOMPurify.sanitize(marked.parse(m.content));
                }
                return `
                    <div class="flex ${m.role === 'user' ? 'justify-end' : 'justify-start'} w-full">
                        <div class="max-w-[95%] lg:max-w-[85%] rounded-2xl p-4 shadow-sm ${m.role === 'user' ? 'bg-blue-600 text-white rounded-br-sm' : 'bg-gray-850 border border-gray-800 text-gray-200 markdown-body rounded-bl-sm'}">
                            ${m.role === 'user' ? `<div class="whitespace-pre-wrap">${m.content}</div>` : html}
                        </div>
                    </div>`;
            }).join('');

            attachCopyButtons();
            if (isAtBottom) scrollToBottom();
        }

        // ─── Polling (for resumed/in-progress sessions) ───────────────────────────
        function stopPolling() {
            if (pollingInterval !== null) {
                clearInterval(pollingInterval);
                pollingInterval = null; 
            }
        }

        function pollGeneratingChat(id) {
            stopPolling();
            pollingInterval = setInterval(async () => {
                const res  = await fetch(`/api/chats/${id}`);
                const chat = await res.json();

                renderMessages(chat.messages);
                updateTokenDisplay(chat.totalTokens, chat.inputTokens, chat.outputTokens);

                const titleEl = document.getElementById('current-chat-title');
                const titleEditHidden = !document.getElementById('title-display').classList.contains('hidden');
                if (titleEditHidden && chat.title !== titleEl.innerText) {
                    titleEl.innerText = chat.title;
                    loadSidebar();
                }

                if (!chat.isGenerating) {
                    stopPolling();  
                    if (currentChatId === id) toggleInputState(false);
                }
            }, 1500);
        }

        // ─── Image attach ─────────────────────────────────────────────────────────
        function handleImageSelect(event) {
            const container = document.getElementById('image-preview-container');
            container.classList.remove('hidden');
            Array.from(event.target.files).forEach(file => {
                const reader = new FileReader();
                reader.onload = e => {
                    attachedImages.push(e.target.result);
                    container.innerHTML += `
                        <div class="relative group">
                            <img src="${e.target.result}" class="h-14 w-14 object-cover rounded-lg border border-gray-600 shadow-sm">
                        </div>`;
                };
                reader.readAsDataURL(file);
            });
        }

        // ─── Send message & stream ────────────────────────────────────────────────
        async function sendMessage() {
            const input = document.getElementById('message-input');
            const text  = input.value.trim();
            if (!text || !currentChatId) return;

            const payload = {
                model:  document.getElementById('model-select').value,
                prompt: text,
                images: attachedImages
            };

            // Optimistic user bubble + spinner
            const container = document.getElementById('chat-window');
            container.innerHTML += `
                <div class="flex justify-end w-full">
                    <div class="max-w-[95%] lg:max-w-[85%] rounded-2xl rounded-br-sm p-4 bg-blue-600 text-white shadow-sm whitespace-pre-wrap">${text}</div>
                </div>
                <div class="flex justify-start w-full" id="temp-ai-wrapper">
                    <div class="max-w-[95%] lg:max-w-[85%] rounded-2xl rounded-bl-sm p-4 bg-gray-850 border border-gray-800 text-gray-200 markdown-body shadow-sm" id="temp-ai-msg">
                        <span class="flex items-center gap-2 text-gray-400">
                            <svg class="animate-spin h-4 w-4" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
                            Thinking...
                        </span>
                    </div>
                </div>`;
            scrollToBottom();

            // Reset input
            input.value = '';
            input.style.height = 'auto';
            attachedImages =[];
            document.getElementById('image-preview-container').innerHTML = '';
            document.getElementById('image-preview-container').classList.add('hidden');

            toggleInputState(true);

            try {
                const response = await fetch(`/api/chats/${currentChatId}/stream`, {
                    method:  'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body:    JSON.stringify(payload)
                });

                if (!response.ok) throw new Error("API stream rejected. Chat might be busy.");

                const reader  = response.body.getReader();
                const decoder = new TextDecoder('utf-8');

                let aiContent  = '';
                let aiReasoning = '';

                let buffer = '';
                const MARKER_LEN = 9; 

                function flushBuffer(final = false) {
                    let progress = true;
                    while (progress) {
                        progress = false;

                        const thinkIdx = buffer.indexOf('__THINK__');
                        const usageIdx = buffer.indexOf('__USAGE__');

                        if (usageIdx !== -1) {
                            if (usageIdx > 0) aiContent += buffer.slice(0, usageIdx);
                            const jsonStr = buffer.slice(usageIdx + MARKER_LEN);
                            try {
                                const usageData = JSON.parse(jsonStr);
                                updateTokenDisplay(
                                    currentTokens.total + usageData.totalTokens,
                                    currentTokens.in    + usageData.inputTokens,
                                    currentTokens.out   + usageData.outputTokens
                                );
                                buffer = '';
                                progress = true;
                            } catch (_) {
                                buffer = buffer.slice(usageIdx);
                            }

                        } else if (thinkIdx !== -1) {
                            if (thinkIdx > 0) {
                                aiContent += buffer.slice(0, thinkIdx);
                                buffer = buffer.slice(thinkIdx);
                            }
                            const afterMarker = buffer.slice(MARKER_LEN);
                            const nextThink   = afterMarker.indexOf('__THINK__');
                            const nextUsage   = afterMarker.indexOf('__USAGE__');
                            const candidates  = [nextThink, nextUsage].filter(x => x !== -1);
                            const nextMarker  = candidates.length ? Math.min(...candidates) : -1;

                            if (nextMarker !== -1) {
                                aiReasoning += afterMarker.slice(0, nextMarker);
                                buffer = afterMarker.slice(nextMarker);
                                progress = true;
                            } else {
                                const safeLen = afterMarker.length - MARKER_LEN;
                                if (safeLen > 0) {
                                    aiReasoning += afterMarker.slice(0, safeLen);
                                    buffer = '__THINK__' + afterMarker.slice(safeLen);
                                }
                            }

                        } else {
                            if (final) {
                                aiContent += buffer;
                                buffer = '';
                                progress = true;
                            } else {
                                const safeLen = buffer.length - MARKER_LEN;
                                if (safeLen > 0) {
                                    aiContent += buffer.slice(0, safeLen);
                                    buffer = buffer.slice(safeLen);
                                    progress = true;
                                }
                            }
                        }
                    }
                }

                while (true) {
                    const { value, done } = await reader.read();

                    if (done) {
                        flushBuffer(true);
                        break;
                    }

                    buffer += decoder.decode(value, { stream: true });
                    flushBuffer(false);

                    // Live render
                    let tempHtml = '';
                    if (aiReasoning) tempHtml += `<div class="reasoning-block"><i>Thinking Process</i><br/>${marked.parse(aiReasoning)}</div>`;
                    if (aiContent)   tempHtml += DOMPurify.sanitize(marked.parse(aiContent));

                    const tempMsg = document.getElementById('temp-ai-msg');
                    if (tempMsg) {
                        tempMsg.innerHTML = tempHtml || "<span class='animate-pulse text-gray-400'>Thinking...</span>";
                    }

                    if (container.scrollHeight - container.scrollTop - container.clientHeight < 100) {
                        scrollToBottom();
                    }
                }

                const tempWrapper = document.getElementById('temp-ai-wrapper');
                if (tempWrapper) {
                    let finalHtml = '';
                    if (aiReasoning) finalHtml += `<div class="reasoning-block"><i>Thinking Process</i><br/>${marked.parse(aiReasoning)}</div>`;
                    if (aiContent)   finalHtml += DOMPurify.sanitize(marked.parse(aiContent));

                    tempWrapper.outerHTML = `
                        <div class="flex justify-start w-full">
                            <div class="max-w-[95%] lg:max-w-[85%] rounded-2xl rounded-bl-sm p-4 bg-gray-850 border border-gray-800 text-gray-200 markdown-body shadow-sm">
                                ${finalHtml || "<span class='text-gray-500'>No response generated.</span>"}
                            </div>
                        </div>`;
                    attachCopyButtons();
                }

                loadSidebar();

            } catch (error) {
                console.error(error);
                const tempMsg = document.getElementById('temp-ai-msg');
                if (tempMsg) {
                    tempMsg.innerHTML = "<span class='text-red-400'>Connection lost or chat busy. Reload to sync.</span>";
                }
            } finally {
                if (pollingInterval === null) toggleInputState(false);
            }
        }

        // ─── Keyboard shortcut ────────────────────────────────────────────────────
        document.getElementById('message-input').addEventListener('keydown', e => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                if (!document.getElementById('send-btn').classList.contains('hidden')) {
                    sendMessage();
                }
            }
        });

        // ─── Boot ─────────────────────────────────────────────────────────────────
        loadSidebar();
    </script>
</body>
</html>