localgpt-server 0.3.6

LocalGPT HTTP server and Telegram bot
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
const API = '/api';
let sessionId = null;
let isStreaming = false;
let abortController = null;
let statusPollInterval = null;
let logsAutoRefreshInterval = null;

// Initialize on DOM load
document.addEventListener('DOMContentLoaded', () => {
    loadSessions();
    setupEventListeners();
    showEmptyState();
    loadStatus();
    startStatusPolling();
});

function setupEventListeners() {
    document.getElementById('send').onclick = sendMessage;
    document.getElementById('new-session').onclick = newSession;

    const input = document.getElementById('input');
    input.onkeydown = (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    };

    // Auto-resize textarea
    input.oninput = () => {
        input.style.height = 'auto';
        input.style.height = Math.min(input.scrollHeight, 200) + 'px';
    };

    document.getElementById('session-select').onchange = async (e) => {
        if (e.target.value) {
            sessionId = e.target.value;
            clearMessages();
            await loadSessionMessages(sessionId);
        }
    };

    // Status panel toggle
    document.getElementById('status-toggle').onclick = toggleStatusPanel;
    document.getElementById('status-close').onclick = toggleStatusPanel;

    // Logs panel
    document.getElementById('logs-toggle').onclick = toggleLogsPanel;
    document.getElementById('logs-close').onclick = toggleLogsPanel;
    document.getElementById('logs-refresh').onclick = loadDaemonLogs;
    document.getElementById('logs-auto').onchange = (e) => {
        if (e.target.checked) {
            startLogsAutoRefresh();
        } else {
            stopLogsAutoRefresh();
        }
    };

    // Sessions panel
    document.getElementById('sessions-toggle').onclick = toggleSessionsPanel;
    document.getElementById('sessions-close').onclick = toggleSessionsPanel;
    document.getElementById('session-back').onclick = showSessionsList;

    // Settings panel
    document.getElementById('settings-toggle').onclick = toggleSettingsPanel;
    document.getElementById('settings-close').onclick = toggleSettingsPanel;
    document.getElementById('settings-save').onclick = saveSettings;
}

function showEmptyState() {
    const messages = document.getElementById('messages');
    if (messages.children.length === 0) {
        messages.innerHTML = `
            <div class="empty-state">
                <h2>Welcome to LocalGPT</h2>
                <p>Start a conversation by typing a message below.</p>
            </div>
        `;
    }
}

function showFirstRunWelcome() {
    const messages = document.getElementById('messages');
    if (messages.children.length === 0) {
        messages.innerHTML = `
            <div class="empty-state welcome">
                <h1>Welcome to LocalGPT</h1>
                <p>This is your first session. I've set up a fresh workspace for you.</p>
                <h3>Quick Start</h3>
                <ol>
                    <li><strong>Just chat</strong> - I'm ready to help with coding, writing, research, or anything else</li>
                    <li><strong>Your memory files</strong> are in the workspace:
                        <ul>
                            <li><code>MEMORY.md</code> - I'll remember important things here</li>
                            <li><code>SOUL.md</code> - Customize my personality and behavior</li>
                            <li><code>HEARTBEAT.md</code> - Tasks for autonomous mode</li>
                        </ul>
                    </li>
                </ol>
                <h3>Tell Me About Yourself</h3>
                <p>What's your name? What kind of projects do you work on? Any preferences for how I should communicate?</p>
                <p><em>I'll save what I learn to MEMORY.md so I remember it next time.</em></p>
            </div>
        `;
    }
}

function clearEmptyState() {
    const emptyState = document.querySelector('.empty-state');
    if (emptyState) {
        emptyState.remove();
    }
}

async function loadSessions() {
    try {
        const res = await fetch(`${API}/sessions`);
        const data = await res.json();
        const sessions = data.sessions || [];

        const select = document.getElementById('session-select');
        if (sessions.length === 0) {
            select.innerHTML = '<option value="">No sessions</option>';
        } else {
            select.innerHTML = sessions.map(s =>
                `<option value="${s.session_id}">${s.session_id.slice(0, 8)}... (idle ${formatTime(s.idle_seconds)})</option>`
            ).join('');
            sessionId = sessions[0].session_id;
        }
    } catch (err) {
        console.error('Failed to load sessions:', err);
    }
}

function formatTime(seconds) {
    if (seconds < 60) return `${seconds}s`;
    if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
    return `${Math.floor(seconds / 3600)}h`;
}

async function newSession() {
    sessionId = null;
    clearMessages();
    showEmptyState();

    // Update select
    const select = document.getElementById('session-select');
    const newOption = document.createElement('option');
    newOption.value = '';
    newOption.text = 'New session';
    newOption.selected = true;
    select.insertBefore(newOption, select.firstChild);
}

function clearMessages() {
    document.getElementById('messages').innerHTML = '';
}

async function loadSessionMessages(sessionId) {
    try {
        const res = await fetch(`${API}/sessions/${sessionId}/messages`);
        if (!res.ok) {
            if (res.status === 404) {
                // Session not found, show empty state
                showEmptyState();
                return;
            }
            throw new Error(`HTTP ${res.status}`);
        }

        const data = await res.json();

        if (!data.messages || data.messages.length === 0) {
            showEmptyState();
            return;
        }

        // Render each message
        for (const msg of data.messages) {
            if (msg.role === 'system') continue; // Skip system messages

            if (msg.role === 'user') {
                appendMessage('user', msg.content || '');
            } else if (msg.role === 'assistant') {
                const div = appendMessage('assistant', msg.content || '');

                // Render tool calls if present
                if (msg.tool_calls && msg.tool_calls.length > 0) {
                    for (const tc of msg.tool_calls) {
                        const toolDiv = document.createElement('div');
                        toolDiv.className = 'message tool';
                        toolDiv.innerHTML = `<span class="tool-name">[${tc.name}]</span>`;
                        div.after(toolDiv);
                    }
                }
            } else if (msg.role === 'toolResult') {
                const toolDiv = document.createElement('div');
                toolDiv.className = 'message tool';
                const output = msg.content ? msg.content.slice(0, 300) : 'Done';
                toolDiv.innerHTML = `<span class="tool-name">[result]</span><div class="tool-output">${escapeHtml(output)}</div>`;
                document.getElementById('messages').appendChild(toolDiv);
            }
        }

        scrollToBottom();
    } catch (err) {
        console.error('Failed to load session messages:', err);
        showEmptyState();
    }
}

async function sendMessage() {
    if (isStreaming) return;

    const input = document.getElementById('input');
    const message = input.value.trim();
    if (!message) return;

    input.value = '';
    input.style.height = 'auto';
    clearEmptyState();

    // Handle slash commands client-side
    if (message.startsWith('/')) {
        if (handleSlashCommand(message)) return;
    }

    appendMessage('user', message);
    const assistantDiv = appendMessage('assistant', '');
    assistantDiv.classList.add('loading');

    const sendBtn = document.getElementById('send');
    sendBtn.textContent = 'Stop';
    sendBtn.disabled = false;
    sendBtn.onclick = abortStreaming;
    isStreaming = true;
    abortController = new AbortController();

    try {
        const res = await fetch(`${API}/chat/stream`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ message, session_id: sessionId }),
            signal: abortController.signal,
        });

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

        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 lines = buffer.split('\n');
            buffer = lines.pop() || '';

            for (const line of lines) {
                if (!line.startsWith('data: ')) continue;
                const data = line.slice(6);
                if (data === '[DONE]') continue;

                try {
                    const event = JSON.parse(data);
                    handleEvent(event, assistantDiv);
                } catch (e) {
                    // Ignore parse errors for partial data
                }
            }
        }
    } catch (err) {
        assistantDiv.classList.remove('loading');
        if (err.name === 'AbortError') {
            // User cancelled — preserve partial text and mark as aborted
            const current = assistantDiv.textContent || assistantDiv.innerHTML;
            if (current) {
                assistantDiv.innerHTML += '<span class="abort-marker"> [aborted]</span>';
            } else {
                assistantDiv.textContent = '[aborted]';
            }
        } else {
            assistantDiv.classList.add('error');
            assistantDiv.textContent = `Error: ${err.message}`;
        }
    } finally {
        assistantDiv.classList.remove('loading');
        sendBtn.textContent = 'Send';
        sendBtn.disabled = false;
        sendBtn.onclick = sendMessage;
        isStreaming = false;
        abortController = null;
        scrollToBottom();
    }
}

function abortStreaming() {
    if (abortController) {
        abortController.abort();
    }
}

function handleEvent(event, assistantDiv) {
    switch (event.type) {
        case 'session':
            sessionId = event.session_id;
            updateSessionSelect(sessionId);
            break;

        case 'content':
            assistantDiv.textContent += event.delta;
            scrollToBottom();
            break;

        case 'tool_start':
            const toolStartDiv = document.createElement('div');
            toolStartDiv.className = 'message tool';
            toolStartDiv.id = `tool-${event.id}`;
            const toolLabel = event.detail
                ? `[${event.name}: ${escapeHtml(event.detail)}]`
                : `[${event.name}]`;
            toolStartDiv.innerHTML = `<span class="tool-name">${toolLabel}</span> Running...`;
            assistantDiv.after(toolStartDiv);
            scrollToBottom();
            break;

        case 'tool_end':
            const toolEl = document.getElementById(`tool-${event.id}`);
            if (toolEl) {
                const output = event.output ? event.output.slice(0, 300) : 'Done';
                toolEl.innerHTML = `<span class="tool-name">[${event.name}]</span><div class="tool-output">${escapeHtml(output)}</div>`;
            }
            scrollToBottom();
            break;

        case 'error':
            assistantDiv.classList.add('error');
            assistantDiv.textContent = `Error: ${event.message}`;
            break;

        case 'done':
            break;
    }
}

function updateSessionSelect(newSessionId) {
    const select = document.getElementById('session-select');

    // Check if this session already exists
    for (let i = 0; i < select.options.length; i++) {
        if (select.options[i].value === newSessionId) {
            select.selectedIndex = i;
            return;
        }
    }

    // Add new session to select
    const option = document.createElement('option');
    option.value = newSessionId;
    option.text = `${newSessionId.slice(0, 8)}... (new)`;
    option.selected = true;
    select.insertBefore(option, select.firstChild);

    // Remove "New session" placeholder if exists
    for (let i = 0; i < select.options.length; i++) {
        if (select.options[i].value === '') {
            select.remove(i);
            break;
        }
    }
}

function appendMessage(role, content) {
    const div = document.createElement('div');
    div.className = `message ${role}`;
    div.textContent = content;
    document.getElementById('messages').appendChild(div);
    scrollToBottom();
    return div;
}

function scrollToBottom() {
    const container = document.getElementById('chat-container');
    container.scrollTop = container.scrollHeight;
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Slash command handling
function handleSlashCommand(input) {
    const parts = input.split(/\s+/);
    const cmd = parts[0];
    const arg = parts.slice(1).join(' ').trim();

    switch (cmd) {
        case '/new':
            newSession();
            return true;
        case '/help':
            appendSystemMessage(
                'Available commands:\n' +
                '  /new              Start a new session\n' +
                '  /model            Show current model\n' +
                '  /compact          Compact session history\n' +
                '  /sessions         Toggle sessions panel\n' +
                '  /status           Toggle status panel\n' +
                '  /logs             Toggle logs panel\n' +
                '  /clear            Clear chat display\n' +
                '  /help             Show this help text'
            );
            return true;
        case '/sessions':
            toggleSessionsPanel();
            return true;
        case '/status':
            toggleStatusPanel();
            return true;
        case '/logs':
            toggleLogsPanel();
            return true;
        case '/model':
            loadStatus().then(() => {
                const model = document.getElementById('status-model').textContent;
                appendSystemMessage(`Current model: ${model}`);
            });
            return true;
        case '/clear':
            clearMessages();
            showEmptyState();
            return true;
        case '/compact':
            if (!sessionId) {
                appendSystemMessage('No active session to compact.');
                return true;
            }
            fetch(`${API}/sessions/${sessionId}/compact`, { method: 'POST' })
                .then(res => res.json())
                .then(data => {
                    if (data.error) {
                        appendSystemMessage(`Compact failed: ${data.error}`);
                    } else {
                        appendSystemMessage(
                            `Session compacted: ${data.token_count_before || '?'} -> ${data.token_count_after || '?'} tokens`
                        );
                    }
                })
                .catch(err => appendSystemMessage(`Compact failed: ${err.message}`));
            return true;
        default:
            appendSystemMessage(`Unknown command: ${cmd}. Type /help for available commands.`);
            return true;
    }
}

function appendSystemMessage(text) {
    const div = document.createElement('div');
    div.className = 'message system';
    div.style.whiteSpace = 'pre-wrap';
    div.textContent = text;
    document.getElementById('messages').appendChild(div);
    scrollToBottom();
}

// Status panel functions
function toggleStatusPanel() {
    const panel = document.getElementById('status-panel');
    panel.classList.toggle('hidden');
    if (!panel.classList.contains('hidden')) {
        loadStatus();
    }
}

function startStatusPolling() {
    // Poll status every 30 seconds
    statusPollInterval = setInterval(loadStatus, 30000);
}

async function loadStatus() {
    try {
        // Fetch status, heartbeat, and channels in parallel
        const [statusRes, heartbeatRes, channelsRes] = await Promise.all([
            fetch(`${API}/status`),
            fetch(`${API}/heartbeat/status`),
            fetch(`${API}/channels/status`)
        ]);

        const status = await statusRes.json();
        const heartbeat = await heartbeatRes.json();
        const channels = await channelsRes.json();

        updateStatusPanel(status, heartbeat);
        updateChannelsPanel(channels);

        // Show detailed welcome message on first run
        if (status.is_brand_new) {
            showFirstRunWelcome();
        }
    } catch (err) {
        console.error('Failed to load status:', err);
    }
}

function updateChannelsPanel(data) {
    const container = document.getElementById('channels-list');
    if (!container) return;

    if (!data.channels || data.channels.length === 0) {
        container.innerHTML = '<div class="empty-state">No channels connected</div>';
        return;
    }

    const html = data.channels.map(ch => {
        const dotClass = ch.state === 'connected' ? 'dot-green'
            : ch.state === 'degraded' ? 'dot-yellow'
            : 'dot-red';
        const lastActive = ch.last_active
            ? new Date(ch.last_active).toLocaleTimeString()
            : '-';
        return `<div class="channel-item">
            <span class="status-dot ${dotClass}"></span>
            <span class="channel-name">${ch.name}</span>
            <span class="channel-detail">${ch.state} · last: ${lastActive}</span>
        </div>`;
    }).join('');

    container.innerHTML = html;

    // Update summary
    const summary = document.getElementById('channels-summary');
    if (summary) {
        summary.textContent = `${data.summary.connected}/${data.summary.total} connected`;
    }
}

function updateStatusPanel(status, heartbeat) {
    // Update general status
    document.getElementById('status-version').textContent = status.version || '-';
    document.getElementById('status-model').textContent = status.model || '-';
    document.getElementById('status-sessions').textContent = status.active_sessions || '0';

    // Update heartbeat status
    const statusDot = document.getElementById('status-dot');
    const heartbeatStatusEl = document.getElementById('heartbeat-status');
    const heartbeatIntervalEl = document.getElementById('heartbeat-interval');
    const heartbeatLastEl = document.getElementById('heartbeat-last');
    const heartbeatDetailRow = document.getElementById('heartbeat-detail-row');
    const heartbeatDetailEl = document.getElementById('heartbeat-detail');

    heartbeatIntervalEl.textContent = heartbeat.interval || '-';

    if (!heartbeat.enabled) {
        statusDot.className = 'status-dot disabled';
        heartbeatStatusEl.innerHTML = '<span class="heartbeat-badge disabled">Disabled</span>';
        heartbeatLastEl.textContent = '-';
        heartbeatDetailRow.style.display = 'none';
        return;
    }

    if (!heartbeat.last_event) {
        statusDot.className = 'status-dot';
        heartbeatStatusEl.innerHTML = '<span class="heartbeat-badge">No events yet</span>';
        heartbeatLastEl.textContent = '-';
        heartbeatDetailRow.style.display = 'none';
        return;
    }

    const event = heartbeat.last_event;
    const statusClass = event.status;

    statusDot.className = `status-dot ${statusClass}`;
    heartbeatStatusEl.innerHTML = `<span class="heartbeat-badge ${statusClass}">${formatHeartbeatStatus(event.status)}</span>`;

    // Format last run time
    if (event.age_seconds !== undefined) {
        heartbeatLastEl.textContent = `${formatAge(event.age_seconds)} (${event.duration_ms}ms)`;
    } else {
        heartbeatLastEl.textContent = `${event.duration_ms}ms`;
    }

    // Show detail if available
    if (event.reason || event.preview) {
        heartbeatDetailRow.style.display = 'flex';
        const detail = event.reason || (event.preview ? event.preview.slice(0, 100) + '...' : '-');
        heartbeatDetailEl.textContent = detail;
    } else {
        heartbeatDetailRow.style.display = 'none';
    }
}

function formatHeartbeatStatus(status) {
    const labels = {
        'ok': 'OK',
        'sent': 'Sent',
        'skipped': 'Skipped',
        'failed': 'Failed'
    };
    return labels[status] || status;
}

function formatAge(seconds) {
    if (seconds < 60) return `${seconds}s ago`;
    if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
    if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
    return `${Math.floor(seconds / 86400)}d ago`;
}

// Logs panel functions
function toggleLogsPanel() {
    const panel = document.getElementById('logs-panel');
    panel.classList.toggle('hidden');
    if (!panel.classList.contains('hidden')) {
        loadDaemonLogs();
    } else {
        stopLogsAutoRefresh();
        document.getElementById('logs-auto').checked = false;
    }
}

async function loadDaemonLogs() {
    try {
        const res = await fetch(`${API}/logs/daemon?lines=200`);
        const data = await res.json();

        const output = document.getElementById('logs-output');
        output.textContent = data.lines.join('\n') || 'No logs available';

        // Auto-scroll to bottom
        output.scrollTop = output.scrollHeight;
    } catch (err) {
        console.error('Failed to load daemon logs:', err);
        document.getElementById('logs-output').textContent = `Error: ${err.message}`;
    }
}

function startLogsAutoRefresh() {
    if (logsAutoRefreshInterval) return;
    logsAutoRefreshInterval = setInterval(loadDaemonLogs, 3000);
}

function stopLogsAutoRefresh() {
    if (logsAutoRefreshInterval) {
        clearInterval(logsAutoRefreshInterval);
        logsAutoRefreshInterval = null;
    }
}

// Sessions panel functions
function toggleSessionsPanel() {
    const panel = document.getElementById('sessions-panel');
    panel.classList.toggle('hidden');
    if (!panel.classList.contains('hidden')) {
        loadSavedSessions();
    }
}

async function loadSavedSessions() {
    try {
        const res = await fetch(`${API}/saved-sessions`);
        const data = await res.json();

        const listEl = document.getElementById('sessions-list');
        const viewerEl = document.getElementById('session-viewer');

        // Show list, hide viewer
        listEl.style.display = 'block';
        viewerEl.classList.add('hidden');

        if (!data.sessions || data.sessions.length === 0) {
            listEl.innerHTML = '<div class="session-item"><em>No saved sessions</em></div>';
            return;
        }

        listEl.innerHTML = data.sessions.map(s => `
            <div class="session-item" onclick="viewSession('${s.id}')">
                <div class="session-item-id">${s.id.slice(0, 16)}...</div>
                <div class="session-item-meta">${s.created_at} \u2022 ${s.message_count} messages</div>
            </div>
        `).join('');
    } catch (err) {
        console.error('Failed to load saved sessions:', err);
        document.getElementById('sessions-list').innerHTML = `<div class="session-item error">Error: ${err.message}</div>`;
    }
}

async function viewSession(sessionId) {
    try {
        const res = await fetch(`${API}/saved-sessions/${sessionId}`);
        const data = await res.json();

        const listEl = document.getElementById('sessions-list');
        const viewerEl = document.getElementById('session-viewer');
        const messagesEl = document.getElementById('session-messages');

        // Hide list, show viewer
        listEl.style.display = 'none';
        viewerEl.classList.remove('hidden');

        messagesEl.innerHTML = data.messages.map(msg => renderSessionMessage(msg)).join('');
    } catch (err) {
        console.error('Failed to view session:', err);
    }
}

function renderSessionMessage(msg) {
    const roleClass = msg.role === 'user' ? 'user' :
                      msg.role === 'toolResult' ? 'tool' : 'assistant';

    let html = `<div class="message ${roleClass}">`;

    if (msg.content) {
        html += escapeHtml(msg.content);
    }

    // Render tool calls
    if (msg.tool_calls && msg.tool_calls.length > 0) {
        for (const tc of msg.tool_calls) {
            const args = tc.arguments || '{}';
            let formattedArgs;
            try {
                formattedArgs = JSON.stringify(JSON.parse(args), null, 2);
            } catch {
                formattedArgs = args;
            }

            html += `
                <div class="tool-call-block" onclick="this.classList.toggle('expanded')">
                    <div class="tool-call-header">
                        <span>[${tc.name}]</span>
                        <span>\u25BC</span>
                    </div>
                    <div class="tool-call-body">${escapeHtml(formattedArgs)}</div>
                </div>
            `;
        }
    }

    // Tool result indicator
    if (msg.tool_call_id) {
        html = `<div class="message tool"><span class="tool-name">[result]</span> ${escapeHtml(msg.content || '')}`;
    }

    html += '</div>';
    return html;
}

function showSessionsList() {
    const listEl = document.getElementById('sessions-list');
    const viewerEl = document.getElementById('session-viewer');
    listEl.style.display = 'block';
    viewerEl.classList.add('hidden');
}

// ── Settings Panel ──

function toggleSettingsPanel() {
    const panel = document.getElementById('settings-panel');
    panel.classList.toggle('hidden');
    if (!panel.classList.contains('hidden')) {
        loadSettingsValues();
    }
}

async function loadSettingsValues() {
    try {
        const res = await fetch(`${API}/config`);
        const config = await res.json();
        document.getElementById('setting-model').value = config.agent?.default_model || '';
        document.getElementById('setting-port').value = config.server?.port || 31327;
        document.getElementById('setting-heartbeat').value = config.heartbeat?.interval || '30m';
        // Log level not in current config response, set to default
        document.getElementById('setting-log-level').value = 'info';
    } catch (err) {
        console.error('Failed to load settings:', err);
    }
}

async function saveSettings() {
    const fields = document.querySelectorAll('#settings-panel [data-key]');
    const statusEl = document.getElementById('settings-status');
    let saved = 0;

    for (const field of fields) {
        const key = field.dataset.key;
        const value = field.value;
        try {
            const res = await fetch(`${API}/config`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ key, value })
            });
            if (res.ok) saved++;
        } catch (err) {
            console.error(`Failed to save ${key}:`, err);
        }
    }

    statusEl.textContent = `Saved ${saved} setting(s). Restart daemon to apply.`;
    setTimeout(() => { statusEl.textContent = ''; }, 5000);
}