-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathllama.html
More file actions
715 lines (715 loc) · 36.8 KB
/
llama.html
File metadata and controls
715 lines (715 loc) · 36.8 KB
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
<!DOCTYPE html>
<html lang="en" data-bs-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LlamaHTML </title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github.min.css" id="highlight-theme">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<style>
html, body {
height: 100vh;
overflow: hidden;
}
.app-container {
height: 100vh;
}
.main-content {
height: 100vh;
overflow: hidden;
}
.chat-container {
flex-grow: 1;
overflow-y: auto;
min-height: 0;
}
.chat-input-container {
flex-shrink: 0;
}
.user-message .message-body {
background-color: var(--bs-primary-bg-subtle);
border-color: var(--bs-primary-border-subtle);
}
.message-body pre {
position: relative;
padding-top: 40px;
}
.code-actions {
position: absolute;
top: 8px;
right: 8px;
display: flex;
gap: 8px;
}
.code-action-button {
padding: 4px 8px;
font-size: 12px;
background-color: var(--bs-secondary-bg);
border: 1px solid var(--bs-border-color);
border-radius: 4px;
cursor: pointer;
opacity: 0.8;
transition: all 0.2s ease;
}
.code-action-button:hover {
opacity: 1;
background-color: var(--bs-tertiary-bg);
}
.code-action-button.copied {
background-color: var(--bs-success);
color: white;
}
#chatInput {
resize: none;
}
#sidebar {
transition: transform .3s ease-in-out, width .3s ease-in-out;
}
</style>
</head>
<body>
<div class="app-container d-flex">
<button class="btn btn-light d-md-none m-2 position-fixed" type="button" data-bs-toggle="offcanvas" data-bs-target="#sidebar" aria-controls="sidebar" style="z-index: 1045; top: 0; left: 0;">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-list" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="M2.5 12a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5m0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5m0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5"/>
</svg>
</button>
<aside class="d-flex flex-column flex-shrink-0 p-3 bg-body-tertiary offcanvas-md offcanvas-start" tabindex="-1" id="sidebar" style="width: 280px;">
<div class="offcanvas-header">
<h5 class="offcanvas-title">LlamaHTML Menu</h5>
<button type="button" class="btn-close" data-bs-dismiss="offcanvas" data-bs-target="#sidebar" aria-label="Close"></button>
</div>
<div class="d-grid gap-2 mb-3" id="sidebar-header">
<button class="btn btn-primary" id="newChatBtn">New chat</button>
</div>
<div class="list-group list-group-flush border-bottom scrollarea flex-grow-1" id="sessionsList">
</div>
<div class="mt-3">
<div class="server-config mb-3">
<input type="url" class="form-control" id="serverUrl" placeholder="Server URL" value="http://127.0.0.1:8080">
</div>
<div class="d-grid gap-2">
<button class="btn btn-outline-secondary" id="settingsBtn" data-bs-toggle="modal" data-bs-target="#settingsModal">Settings</button>
<button class="btn btn-outline-secondary" id="themeSwitcher">🌙</button>
</div>
</div>
</aside>
<main class="main-content flex-grow-1 d-flex flex-column">
<div class="chat-container p-3" id="chatContainer">
<div class="empty-state text-center h-100 d-flex flex-column justify-content-center align-items-center">
<div>
<h2>LlamaHTML</h2>
<p class="lead text-body-secondary">Start a conversation with your local Llama model</p>
</div>
</div>
</div>
<div class="chat-input-container p-3 bg-body-tertiary border-top">
<div class="input-area">
<div id="stagedFilesArea" class="d-flex flex-wrap gap-2 mb-2" style="display: none;">
</div>
<div class="input-group">
<textarea class="form-control" id="chatInput" placeholder="Message Llama..." rows="1"></textarea>
<label for="fileInput" class="btn btn-outline-secondary" title="Attach files">📎</label>
<input type="file" id="fileInput" multiple class="d-none">
<button class="btn btn-primary" id="sendButton">Send</button>
</div>
<div class="status-bar text-center text-body-secondary small mt-2" id="statusBar"></div>
</div>
</div>
</main>
</div>
<div class="modal fade" id="settingsModal" tabindex="-1" aria-labelledby="settingsModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="settingsModalLabel">Settings</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="mb-3"><label for="temperature" class="form-label">Temperature</label><input type="number" class="form-control" id="temperature" min="0" max="2" step="0.1" value="0.7"><small class="form-text text-muted">Controls randomness.</small></div>
<div class="mb-3"><label for="nPredict" class="form-label">Max Tokens</label><input type="number" class="form-control" id="nPredict" min="1" step="1" value="2048"><small class="form-text text-muted">Max tokens to generate.</small></div>
<div class="mb-3"><label for="topP" class="form-label">Top P</label><input type="number" class="form-control" id="topP" min="0" max="1" step="0.01" value="0.95"><small class="form-text text-muted">Nucleus sampling.</small></div>
<div class="mb-3"><label for="topK" class="form-label">Top K</label><input type="number" class="form-control" id="topK" min="1" step="1" value="40"><small class="form-text text-muted">Top-k sampling.</small></div>
<div class="mb-3"><label for="stopSequences" class="form-label">Stop Sequences</label><input type="text" class="form-control" id="stopSequences" value="USER:, \nUSER:, <|user|>"><small class="form-text text-muted">Comma-separated strings.</small></div>
<div class="form-check"><input class="form-check-input" type="checkbox" id="rememberServerUrl"><label class="form-check-label" for="rememberServerUrl">Remember Server URL</label></div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<script>
const SESSION_INDEX_KEY = 'llamaChatIndex';
const SESSION_DATA_PREFIX = 'llamaChatSession_';
const MAX_TEXT_FILE_EMBED_SIZE = 200 * 1024;
const elements = {
serverUrl: document.getElementById('serverUrl'),
rememberServerUrl: document.getElementById('rememberServerUrl'),
chatInput: document.getElementById('chatInput'),
sendButton: document.getElementById('sendButton'),
statusBar: document.getElementById('statusBar'),
chatContainer: document.getElementById('chatContainer'),
themeSwitcher: document.getElementById('themeSwitcher'),
temperature: document.getElementById('temperature'),
nPredict: document.getElementById('nPredict'),
topP: document.getElementById('topP'),
topK: document.getElementById('topK'),
stopSequences: document.getElementById('stopSequences'),
sessionsList: document.getElementById('sessionsList'),
newChatBtn: document.getElementById('newChatBtn'),
fileInput: document.getElementById('fileInput'),
stagedFilesArea: document.getElementById('stagedFilesArea'),
settingsBtn: document.getElementById('settingsBtn'),
settingsModal: document.getElementById('settingsModal'),
sidebar: document.getElementById('sidebar'),
highlightTheme: document.getElementById('highlight-theme')
};
let chatHistory = [];
let serverAvailable = false;
let messageCounter = 0;
let currentSessionId = null;
let currentAbortController = null;
let stagedFiles = [];
let sidebarInstance = null;
function initializeTheme() {
const savedTheme = localStorage.getItem('theme') || 'light';
setTheme(savedTheme);
}
function setTheme(theme) {
document.documentElement.setAttribute('data-bs-theme', theme);
elements.themeSwitcher.textContent = theme === 'dark' ? '☀️' : '🌙';
const lightThemeUrl = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github.min.css';
const darkThemeUrl = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css';
elements.highlightTheme.href = theme === 'dark' ? darkThemeUrl : lightThemeUrl;
localStorage.setItem('theme', theme);
}
function toggleTheme() {
const currentTheme = document.documentElement.getAttribute('data-bs-theme') || 'light';
const newTheme = currentTheme === 'light' ? 'dark' : 'light';
setTheme(newTheme);
}
function initialize() {
sidebarInstance = new bootstrap.Offcanvas(elements.sidebar);
loadServerUrl();
setupEventListeners();
initializeTheme();
configureMarked();
checkServerStatus();
populateSessions();
startNewSession();
updateSendButtonState();
}
function configureMarked() {
marked.setOptions({
highlight: function(code, lang) {
const language = hljs.getLanguage(lang) ? lang : 'plaintext';
return hljs.highlight(code, { language, ignoreIllegals: true }).value;
},
gfm: true,
breaks: true,
langPrefix: 'hljs language-',
});
}
function setupEventListeners() {
elements.sendButton.addEventListener('click', handleSendPrompt);
elements.newChatBtn.addEventListener('click', () => {
if (currentAbortController) handleStopGeneration();
startNewSession();
closeMobileSidebar();
});
elements.themeSwitcher.addEventListener('click', toggleTheme);
elements.rememberServerUrl.addEventListener('change', handleRememberUrlChange);
elements.serverUrl.addEventListener('input', handleServerUrlInput);
elements.chatInput.addEventListener('input', () => {
updateSendButtonState();
autoResizeTextarea(elements.chatInput);
});
elements.chatInput.addEventListener('keydown', (event) => {
if ((event.ctrlKey || event.metaKey) && event.key === 'Enter' && !event.shiftKey) {
event.preventDefault();
if (!elements.sendButton.disabled && !elements.sendButton.textContent.includes('Stop')) {
handleSendPrompt();
}
}
});
elements.fileInput.addEventListener('change', handleFileSelection);
elements.stagedFilesArea.addEventListener('click', handleRemoveStagedFile);
elements.chatContainer.addEventListener('click', function(event) {
if (event.target.classList.contains('copy-code-button')) handleCopyCodeClick(event.target);
else if (event.target.classList.contains('download-code-button')) handleDownloadCodeClick(event.target);
});
elements.sessionsList.addEventListener('click', function(event) {
const sessionItem = event.target.closest('.list-group-item');
const deleteBtn = event.target.closest('.delete-btn');
if (deleteBtn && sessionItem) {
event.stopPropagation();
handleDeleteSession(sessionItem.dataset.sessionId);
} else if (sessionItem) {
handleLoadSession(sessionItem.dataset.sessionId);
closeMobileSidebar();
}
});
}
function closeMobileSidebar() {
if (window.innerWidth < 768) {
sidebarInstance.hide();
}
}
function autoResizeTextarea(textarea) {
textarea.style.height = 'auto';
textarea.style.height = Math.min(textarea.scrollHeight, 200) + 'px';
}
function loadServerUrl() {
const rememberedUrl = localStorage.getItem('llamaServerUrl');
const shouldRemember = localStorage.getItem('rememberLlamaServerUrl') === 'true';
elements.rememberServerUrl.checked = shouldRemember;
if (shouldRemember && rememberedUrl) {
elements.serverUrl.value = rememberedUrl;
}
}
function handleRememberUrlChange() {
if (elements.rememberServerUrl.checked) {
localStorage.setItem('llamaServerUrl', elements.serverUrl.value.trim());
localStorage.setItem('rememberLlamaServerUrl', 'true');
} else {
localStorage.removeItem('llamaServerUrl');
localStorage.removeItem('rememberLlamaServerUrl');
}
}
let serverUrlDebounceTimer;
function handleServerUrlInput() {
handleRememberUrlChange();
clearTimeout(serverUrlDebounceTimer);
serverUrlDebounceTimer = setTimeout(() => {
checkServerStatus();
updateSendButtonState();
}, 500);
}
async function checkServerStatus() {
const serverUrl = elements.serverUrl.value.trim();
if (!isValidHttpUrl(serverUrl)) {
showStatus("Invalid server URL format.", "danger");
serverAvailable = false;
updateSendButtonState();
return;
}
showStatus("Server URL looks valid. Ready to send.", "info");
serverAvailable = true;
updateSendButtonState();
}
function updateSendButtonState() {
if (currentAbortController) {
elements.sendButton.disabled = false;
return;
}
const urlValid = isValidHttpUrl(elements.serverUrl.value.trim());
const isLoading = elements.statusBar.querySelector('.spinner-border') !== null;
const canSend = urlValid && !isLoading && (elements.chatInput.value.trim().length > 0 || stagedFiles.length > 0);
elements.sendButton.disabled = !canSend;
}
function isValidHttpUrl(string) {
try {
const url = new URL(string);
return url.protocol === "http:" || url.protocol === "https:";
} catch (_) {
return false;
}
}
function handleFileSelection(event) {
const files = event.target.files;
if (!files) return;
showLoading(true, "Processing files...");
const newFiles = Array.from(files).filter(f => !stagedFiles.some(sf => sf.name === f.name));
if (newFiles.length !== files.length) showStatus("Duplicate filenames were ignored.", "warning");
if (newFiles.length === 0) {
showLoading(false);
return;
}
let filesProcessed = 0;
newFiles.forEach(file => {
const reader = new FileReader();
const fileData = { file, name: file.name, type: file.type, content: null, error: null };
stagedFiles.push(fileData);
reader.onload = e => {
fileData.content = e.target.result;
filesProcessed++;
if (filesProcessed === newFiles.length) finishFileProcessing();
};
reader.onerror = e => {
fileData.error = `Error reading file: ${e.target.error?.message || 'Unknown'}`;
filesProcessed++;
if (filesProcessed === newFiles.length) finishFileProcessing();
};
if (file.type.startsWith('text/') || /\.(txt|md|py|js|html|css|json|xml|csv|log)$/i.test(file.name)) {
reader.readAsText(file);
} else {
reader.readAsDataURL(file);
}
});
renderStagedFiles();
event.target.value = null;
}
function finishFileProcessing() {
renderStagedFiles();
showLoading(false);
updateSendButtonState();
elements.chatInput.focus();
}
function renderStagedFiles() {
elements.stagedFilesArea.innerHTML = '';
if (stagedFiles.length === 0) {
elements.stagedFilesArea.style.display = 'none';
updateSendButtonState();
return;
}
elements.stagedFilesArea.style.display = 'flex';
stagedFiles.forEach((fileData, index) => {
const item = document.createElement('div');
item.className = `badge d-flex align-items-center ${fileData.error ? 'text-bg-danger' : 'text-bg-secondary'}`;
item.title = fileData.name + (fileData.error ? ` (Error: ${fileData.error})` : '');
item.innerHTML = `
<span class="me-2">${fileData.name}</span>
<button type="button" class="btn-close btn-close-white" aria-label="Remove file" data-index="${index}"></button>
`;
elements.stagedFilesArea.appendChild(item);
});
updateSendButtonState();
}
function handleRemoveStagedFile(event) {
if (event.target.matches('[data-index]')) {
const indexToRemove = parseInt(event.target.dataset.index, 10);
stagedFiles.splice(indexToRemove, 1);
renderStagedFiles();
}
}
function clearStagedFiles() {
stagedFiles = [];
renderStagedFiles();
elements.fileInput.value = null;
}
async function handleSendPrompt() {
elements.sendButton.innerHTML = `<span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span> Stop`;
elements.sendButton.classList.replace('btn-primary', 'btn-danger');
elements.sendButton.removeEventListener('click', handleSendPrompt);
elements.sendButton.addEventListener('click', handleStopGeneration);
elements.chatInput.disabled = true;
const serverUrl = elements.serverUrl.value.trim();
let promptText = elements.chatInput.value.trim();
const temperature = parseFloat(elements.temperature.value);
const nPredict = parseInt(elements.nPredict.value, 10);
const topP = parseFloat(elements.topP.value);
const topK = parseInt(elements.topK.value, 10);
const stopSequences = elements.stopSequences.value.split(',').map(s => s.trim()).filter(Boolean);
if (!promptText && stagedFiles.length === 0) {
showStatus("Message cannot be empty.", "warning");
resetButtonToSendState();
elements.chatInput.disabled = false;
return;
}
const filesWithError = stagedFiles.filter(f => f.error);
if (filesWithError.length > 0) {
showStatus(`Cannot send due to errors reading files: ${filesWithError.map(f => f.name).join(', ')}`, "danger");
resetButtonToSendState();
elements.chatInput.disabled = false;
return;
}
let fileInfoForPrompt = "";
if (stagedFiles.length > 0) {
fileInfoForPrompt = "Attached Files:\n";
stagedFiles.forEach(fileData => {
fileInfoForPrompt += `[File: ${fileData.name} (${fileData.type})]\n`;
if (fileData.type.startsWith('text/') && fileData.content && fileData.content.length < MAX_TEXT_FILE_EMBED_SIZE) {
fileInfoForPrompt += `Content:\n---\n${fileData.content}\n---\n`;
} else if (!fileData.type.startsWith('text/') && fileData.content?.startsWith('data:')) {
fileInfoForPrompt += `(File is binary/image - content not embedded in text prompt)\n`;
} else if (fileData.type.startsWith('text/')) {
fileInfoForPrompt += `(Text file content too large to embed in prompt)\n`;
}
});
fileInfoForPrompt += "\nUser Message:\n";
}
const fullUserContent = fileInfoForPrompt + promptText;
if (currentAbortController) currentAbortController.abort();
currentAbortController = new AbortController();
const userMessage = { role: 'user', content: fullUserContent, id: `msg-${messageCounter++}` };
chatHistory.push(userMessage);
renderChatHistory();
elements.chatInput.value = '';
autoResizeTextarea(elements.chatInput);
clearStagedFiles();
showLoading(true, "Connecting...");
const modelMessage = { role: 'model', content: '', id: `msg-${messageCounter++}` };
chatHistory.push(modelMessage);
renderChatHistory();
const fullPromptForLlama = formatChatHistoryForLlama(chatHistory.slice(0, -1));
const requestBody = {
prompt: fullPromptForLlama, stream: true,
temperature, top_p: topP, top_k: topK,
n_predict: nPredict === -1 ? -1 : Math.max(1, nPredict),
stop: stopSequences
};
let responseOk = false;
try {
const response = await fetch(`${serverUrl}/completion`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(requestBody),
signal: currentAbortController.signal,
});
responseOk = response.ok;
if (!response.ok || !response.body) throw new Error(`API Error: ${response.status} ${response.statusText}`);
showLoading(true, "Receiving response...");
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { value, done } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
const lines = chunk.split('\n\n').filter(Boolean);
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = JSON.parse(line.substring(6));
if (data.content) modelMessage.content += data.content;
if (data.stop) break;
}
}
updateModelBubbleContent(modelMessage.id, modelMessage.content, true);
}
showStatus("Response complete.", "success");
} catch (error) {
if (error.name === 'AbortError') {
showStatus("Request cancelled by user.", "info");
if (chatHistory[chatHistory.length - 1].content.length < 15) chatHistory.pop();
} else {
const errorMsg = !responseOk ? `Connection Error: Could not connect to server.` : error.message;
showStatus(`Error: ${errorMsg}`, "danger");
chatHistory.pop();
chatHistory.pop();
}
renderChatHistory();
} finally {
updateModelBubbleContent(modelMessage.id, modelMessage.content, false);
resetButtonToSendState();
showLoading(false);
elements.chatInput.disabled = false;
currentAbortController = null;
updateSendButtonState();
elements.chatInput.focus();
}
}
function handleStopGeneration() {
if (currentAbortController) currentAbortController.abort();
}
function resetButtonToSendState() {
elements.sendButton.innerHTML = 'Send';
elements.sendButton.classList.replace('btn-danger', 'btn-primary');
elements.sendButton.removeEventListener('click', handleStopGeneration);
elements.sendButton.addEventListener('click', handleSendPrompt);
}
function formatChatHistoryForLlama(history) {
return history.map(msg => {
if (msg.role === 'user') return `USER: ${msg.content}`;
if (msg.role === 'model') return `ASSISTANT: ${msg.content}`;
return '';
}).join('\n') + '\nASSISTANT:';
}
function showLoading(isLoading, message = "") {
if (isLoading) {
elements.statusBar.innerHTML = `<div class="spinner-border spinner-border-sm me-2" role="status"></div><span>${escapeHtml(message)}</span>`;
} else {
if (!elements.statusBar.classList.contains('text-bg-danger')) {
elements.statusBar.innerHTML = '';
}
}
}
function showStatus(message, type = "info") {
showLoading(false);
elements.statusBar.className = `status-bar text-center small mt-2 p-1 rounded-pill text-bg-${type}`;
elements.statusBar.textContent = message;
if (type !== 'danger' && type !== 'warning') {
setTimeout(() => {
if (elements.statusBar.textContent === message) {
elements.statusBar.textContent = '';
elements.statusBar.className = 'status-bar text-center text-body-secondary small mt-2';
}
}, 4000);
}
}
function createMessageElement(message) {
const messageWrapper = document.createElement('div');
messageWrapper.className = `chat-message ${message.role}-message d-flex gap-3 mb-3`;
messageWrapper.dataset.messageId = message.id;
const avatar = `<div class="rounded-circle bg-secondary text-white d-flex align-items-center justify-content-center" style="width: 40px; height: 40px; flex-shrink: 0;">${message.role === 'user' ? 'U' : 'L'}</div>`;
const bodyDiv = `<div class="message-body p-3 border rounded-3 w-100">${message.content || ''}</div>`;
messageWrapper.innerHTML = avatar + bodyDiv;
const bodyElement = messageWrapper.querySelector('.message-body');
if (message.role === 'model' && message.content) {
bodyElement.innerHTML = marked.parse(message.content);
requestAnimationFrame(() => addCodeActionsToBubble(bodyElement));
} else if(message.role === 'user') {
bodyElement.textContent = message.content;
}
return messageWrapper;
}
function renderChatHistory() {
if (chatHistory.length === 0) {
elements.chatContainer.innerHTML = `<div class="empty-state text-center h-100 d-flex flex-column justify-content-center align-items-center"><div><h2>LlamaHTML</h2><p class="lead text-body-secondary">Start a conversation with your local Llama model</p></div></div>`;
} else {
elements.chatContainer.innerHTML = '';
chatHistory.forEach(message => elements.chatContainer.appendChild(createMessageElement(message)));
scrollToBottom();
}
updateSaveButtonState();
}
function updateModelBubbleContent(messageId, newContent, isStreamingUpdate = false) {
const messageDiv = document.querySelector(`.model-message[data-message-id="${messageId}"] .message-body`);
if (!messageDiv) return;
messageDiv.innerHTML = marked.parse(newContent || (isStreamingUpdate ? "" : "[Empty Response]"));
addCodeActionsToBubble(messageDiv);
if(isStreamingUpdate) scrollToBottom();
}
function addCodeActionsToBubble(container) {
container.querySelectorAll('pre').forEach(pre => {
if (pre.querySelector('.code-actions')) return;
pre.style.position = 'relative';
const codeElement = pre.querySelector('code');
if (!codeElement) return;
const actionsContainer = document.createElement('div');
actionsContainer.className = 'code-actions';
actionsContainer.innerHTML = `
<button class="code-action-button copy-code-button" title="Copy code">Copy</button>
<button class="code-action-button download-code-button" title="Download code">Download</button>
`;
pre.prepend(actionsContainer);
});
}
function handleCopyCodeClick(button) {
const code = button.closest('pre')?.querySelector('code')?.textContent || '';
navigator.clipboard.writeText(code).then(() => {
button.textContent = 'Copied!';
button.classList.add('copied');
setTimeout(() => {
button.textContent = 'Copy';
button.classList.remove('copied');
}, 2000);
});
}
function handleDownloadCodeClick(button) {
const pre = button.closest('pre');
const code = pre?.querySelector('code');
if (!code) return;
const langClass = Array.from(code.classList).find(c => c.startsWith('language-'));
const lang = langClass ? langClass.replace('language-', '') : 'txt';
const blob = new Blob([code.textContent], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `code-${lang}.${lang}`;
a.click();
URL.revokeObjectURL(url);
}
function escapeHtml(unsafe) {
return unsafe.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
}
function scrollToBottom() {
elements.chatContainer.scrollTop = elements.chatContainer.scrollHeight;
}
function getSessionIndex() {
try {
const index = JSON.parse(localStorage.getItem(SESSION_INDEX_KEY));
return Array.isArray(index) ? index : [];
} catch { return []; }
}
function saveSessionIndex(index) {
localStorage.setItem(SESSION_INDEX_KEY, JSON.stringify(index));
}
function populateSessions() {
const sessions = getSessionIndex();
elements.sessionsList.innerHTML = '';
sessions.forEach(session => {
const item = document.createElement('a');
item.href = '#';
item.className = `list-group-item list-group-item-action d-flex justify-content-between align-items-center ${session.id === currentSessionId ? 'active' : ''}`;
item.dataset.sessionId = session.id;
item.textContent = session.name;
item.innerHTML += `<button class="btn-close delete-btn" title="Delete session"></button>`;
elements.sessionsList.appendChild(item);
});
}
function startNewSession() {
if (currentAbortController) currentAbortController.abort();
chatHistory = [];
currentSessionId = null;
messageCounter = 0;
clearStagedFiles();
renderChatHistory();
showStatus("");
updateSendButtonState();
populateSessions();
elements.chatInput.focus();
}
function handleSaveSession() {
const sessions = getSessionIndex();
let existingSession = currentSessionId ? sessions.find(s => s.id === currentSessionId) : null;
let defaultName = existingSession ? existingSession.name : `Chat ${new Date().toLocaleString()}`;
const sessionName = prompt("Enter a name for this session:", defaultName);
if (!sessionName?.trim()) return;
const trimmedName = sessionName.trim();
if (!currentSessionId && sessions.some(s => s.name === trimmedName)) {
if (!confirm(`A session named "${trimmedName}" already exists. Overwrite?`)) return;
const conflictId = sessions.find(s => s.name === trimmedName).id;
localStorage.removeItem(`${SESSION_DATA_PREFIX}${conflictId}`);
saveSessionIndex(sessions.filter(s => s.id !== conflictId));
}
const sessionIdToSave = currentSessionId || `${Date.now()}`;
if (!existingSession) {
sessions.push({ id: sessionIdToSave, name: trimmedName });
currentSessionId = sessionIdToSave;
} else {
existingSession.name = trimmedName;
}
localStorage.setItem(`${SESSION_DATA_PREFIX}${sessionIdToSave}`, JSON.stringify(chatHistory));
saveSessionIndex(sessions);
populateSessions();
showStatus(`Session "${trimmedName}" saved.`, "success");
}
function handleLoadSession(sessionId) {
const hasUnsavedChanges = chatHistory.length > 0 && !currentSessionId;
if (hasUnsavedChanges && !confirm("Loading a session will discard the current unsaved chat. Continue?")) return;
try {
const historyJson = localStorage.getItem(`${SESSION_DATA_PREFIX}${sessionId}`);
chatHistory = JSON.parse(historyJson) || [];
currentSessionId = sessionId;
renderChatHistory();
populateSessions();
showStatus("Session loaded.", "info");
} catch(e) {
showStatus("Failed to load session.", "danger");
}
}
function handleDeleteSession(sessionId) {
const sessions = getSessionIndex();
const session = sessions.find(s => s.id === sessionId);
if (!session || !confirm(`Delete session "${session.name}"? This cannot be undone.`)) return;
localStorage.removeItem(`${SESSION_DATA_PREFIX}${sessionId}`);
saveSessionIndex(sessions.filter(s => s.id !== sessionId));
if (currentSessionId === sessionId) startNewSession();
populateSessions();
showStatus(`Session "${session.name}" deleted.`, "info");
}
function updateSaveButtonState() {
const canSave = chatHistory.length > 0 && !currentAbortController;
elements.saveSessionButton.disabled = !canSave;
}
const saveSessionButton = document.createElement('button');
saveSessionButton.id = 'saveSessionButton';
saveSessionButton.className = 'btn btn-outline-primary';
saveSessionButton.textContent = 'Save Chat';
saveSessionButton.addEventListener('click', handleSaveSession);
document.getElementById('sidebar-header').appendChild(saveSessionButton);
elements.saveSessionButton = saveSessionButton;
initialize();
</script>
</body>
</html>