-
Notifications
You must be signed in to change notification settings - Fork 330
Expand file tree
/
Copy pathrenderer.js
More file actions
1066 lines (921 loc) · 33.9 KB
/
Copy pathrenderer.js
File metadata and controls
1066 lines (921 loc) · 33.9 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
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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// =====================================================
// Foundry Local Chat - Renderer Process
// =====================================================
// Simple markdown parser with code block handling
const SimpleMarkdown = {
parse(text) {
if (!text) return '';
// Extract code blocks first to protect them from other processing
const codeBlocks = [];
let html = text.replace(/```(\w*)\n([\s\S]*?)```/g, (match, lang, code) => {
const placeholder = `__CODE_BLOCK_${codeBlocks.length}__`;
codeBlocks.push({ lang, code });
return placeholder;
});
// Extract inline code
const inlineCodes = [];
html = html.replace(/`([^`]+)`/g, (match, code) => {
const placeholder = `__INLINE_CODE_${inlineCodes.length}__`;
inlineCodes.push(code);
return placeholder;
});
// Now escape HTML on the remaining text
html = this.escapeHtml(html);
// Headings (### before ## before #)
html = html.replace(/^### (.+)$/gm, '<h4>$1</h4>');
html = html.replace(/^## (.+)$/gm, '<h3>$1</h3>');
html = html.replace(/^# (.+)$/gm, '<h2>$1</h2>');
// Unordered lists
html = html.replace(/^- (.+)$/gm, '<li>$1</li>');
html = html.replace(/(<li>.*<\/li>\n?)+/g, '<ul>$&</ul>');
// Bold
html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
// Italic
html = html.replace(/\*([^*]+)\*/g, '<em>$1</em>');
// Links
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>');
// Line breaks (but not inside block elements)
html = html.replace(/\n/g, '<br>');
// Clean up extra <br> around block elements
html = html.replace(/<br>(<h[234]>)/g, '$1');
html = html.replace(/(<\/h[234]>)<br>/g, '$1');
html = html.replace(/<br>(<ul>)/g, '$1');
html = html.replace(/(<\/ul>)<br>/g, '$1');
// Restore inline code
inlineCodes.forEach((code, i) => {
html = html.replace(`__INLINE_CODE_${i}__`, `<code>${this.escapeHtml(code)}</code>`);
});
// Restore code blocks
codeBlocks.forEach((block, i) => {
const codeHtml = `<div class="code-block-wrapper">
<button class="code-copy-btn" data-copy="true" title="Copy code">
<span class="copy-icon">⧉</span>
<span class="check-icon">✓</span>
</button>
<pre><code class="language-${block.lang || 'plaintext'}">${this.escapeHtml(block.code.trim())}</code></pre>
</div>`;
html = html.replace(`__CODE_BLOCK_${i}__`, codeHtml);
});
return html;
},
escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
};
// Copy code to clipboard - use event delegation
document.addEventListener('click', async (e) => {
const button = e.target.closest('.code-copy-btn');
if (!button) return;
const codeBlock = button.closest('.code-block-wrapper').querySelector('code');
const text = codeBlock.textContent;
try {
await navigator.clipboard.writeText(text);
button.classList.add('copied');
setTimeout(() => button.classList.remove('copied'), 2000);
} catch (err) {
console.error('Failed to copy:', err);
}
});
// Estimate tokens from text (rough approximation: ~4 chars per token)
function estimateTokens(text) {
return Math.ceil(text.length / 4);
}
// Calculate total context tokens from all messages
function calculateContextTokens() {
return messages.reduce((total, msg) => total + estimateTokens(msg.content), 0);
}
// Update context usage display
function updateContextUsage() {
contextTokens = calculateContextTokens();
const percentage = Math.min(100, Math.round((contextTokens / CONTEXT_LIMIT) * 100));
contextFill.style.width = `${percentage}%`;
contextLabel.textContent = `${percentage}%`;
// Update color based on usage
contextFill.classList.remove('warning', 'danger');
if (percentage >= 90) {
contextFill.classList.add('danger');
} else if (percentage >= 70) {
contextFill.classList.add('warning');
}
// Update tooltip
contextUsage.title = `Context: ${contextTokens.toLocaleString()} / ${CONTEXT_LIMIT.toLocaleString()} tokens (~${percentage}%)`;
}
// State
let messages = [];
let currentModelAlias = null;
let isGenerating = false;
let contextTokens = 0;
const CONTEXT_LIMIT = 8192; // Default context window, will update based on model
// DOM Elements
const sidebar = document.getElementById('sidebar');
const sidebarToggle = document.getElementById('sidebarToggle');
const mobileMenuBtn = document.getElementById('mobileMenuBtn');
const modelList = document.getElementById('modelList');
const refreshModels = document.getElementById('refreshModels');
const modelBadge = document.getElementById('modelBadge');
const chatMessages = document.getElementById('chatMessages');
const chatForm = document.getElementById('chatForm');
const messageInput = document.getElementById('messageInput');
const sendBtn = document.getElementById('sendBtn');
const newChatBtn = document.getElementById('newChatBtn');
const toastContainer = document.getElementById('toastContainer');
const recordBtn = document.getElementById('recordBtn');
const transcriptionSettingsBtn = document.getElementById('transcriptionSettingsBtn');
const whisperModal = document.getElementById('whisperModal');
const whisperModelList = document.getElementById('whisperModelList');
const whisperModalCancel = document.getElementById('whisperModalCancel');
const currentWhisperModelEl = document.getElementById('currentWhisperModel');
const contextFill = document.getElementById('contextFill');
const contextLabel = document.getElementById('contextLabel');
const contextUsage = document.getElementById('contextUsage');
// Recording state
let mediaRecorder = null;
let audioChunks = [];
let isRecording = false;
let selectedWhisperModel = null;
// Initialize
document.addEventListener('DOMContentLoaded', async () => {
setupEventListeners();
setupSidebarResize();
setupRecordButton();
updateContextUsage();
await loadModels();
setupChatChunkListener();
});
function setupSidebarResize() {
const resizeHandle = document.getElementById('sidebarResizeHandle');
let isResizing = false;
resizeHandle.addEventListener('mousedown', (e) => {
isResizing = true;
resizeHandle.classList.add('dragging');
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
});
document.addEventListener('mousemove', (e) => {
if (!isResizing) return;
const newWidth = Math.min(Math.max(e.clientX, 240), 480);
sidebar.style.width = newWidth + 'px';
});
document.addEventListener('mouseup', () => {
if (isResizing) {
isResizing = false;
resizeHandle.classList.remove('dragging');
document.body.style.cursor = '';
document.body.style.userSelect = '';
}
});
}
function setupRecordButton() {
recordBtn.addEventListener('click', handleRecordClick);
transcriptionSettingsBtn.addEventListener('click', openTranscriptionSettings);
whisperModalCancel.addEventListener('click', () => {
whisperModal.classList.remove('visible');
});
}
async function openTranscriptionSettings() {
const whisperModels = await window.foundryAPI.getWhisperModels();
showWhisperModal(whisperModels, true);
}
async function handleRecordClick() {
if (isRecording) {
// Stop recording
stopRecording();
} else {
// Check if whisper model is available
const whisperModels = await window.foundryAPI.getWhisperModels();
const cachedModels = whisperModels.filter(m => m.isCached);
if (cachedModels.length === 0) {
// Show modal to download whisper model
showWhisperModal(whisperModels, false);
} else {
// Start recording
startRecording();
}
}
}
function showWhisperModal(models, isSettings = false) {
// Update current model display
const cachedModels = models.filter(m => m.isCached);
const modelNameEl = currentWhisperModelEl.querySelector('.model-name');
if (cachedModels.length > 0) {
const current = selectedWhisperModel || cachedModels.sort((a, b) => (a.fileSizeMb || 0) - (b.fileSizeMb || 0))[0].alias;
modelNameEl.textContent = current;
} else {
modelNameEl.textContent = 'None - download a model below';
}
whisperModelList.innerHTML = '';
models.forEach(model => {
const sizeStr = model.fileSizeMb ? `${(model.fileSizeMb / 1024).toFixed(1)} GB` : '';
const isSelected = selectedWhisperModel === model.alias;
const item = document.createElement('div');
item.className = 'whisper-model-item' + (isSelected ? ' selected' : '');
item.innerHTML = `
<div class="model-info">
<span class="model-name">${model.alias}</span>
<span class="model-size">${sizeStr}</span>
</div>
<div class="model-actions">
${model.isCached
? `<button class="use-btn">${isSelected ? '✓ Selected' : 'Select'}</button>
<button class="delete-btn" title="Delete from cache">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="3 6 5 6 21 6"></polyline>
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
</svg>
</button>`
: '<button class="download-btn">Download</button>'
}
</div>
`;
if (model.isCached) {
const useBtn = item.querySelector('.use-btn');
useBtn.addEventListener('click', () => {
selectedWhisperModel = model.alias;
showToast(`Selected ${model.alias} for transcription`, 'success');
// Refresh modal to show selection
showWhisperModal(models, true);
});
const deleteBtn = item.querySelector('.delete-btn');
deleteBtn.addEventListener('click', async () => {
if (confirm(`Delete ${model.alias} from cache?`)) {
try {
await window.foundryAPI.deleteModel(model.alias);
if (selectedWhisperModel === model.alias) {
selectedWhisperModel = null;
}
showToast(`Deleted ${model.alias}`, 'success');
const updatedModels = await window.foundryAPI.getWhisperModels();
showWhisperModal(updatedModels, true);
} catch (error) {
showToast('Delete failed: ' + error.message, 'error');
}
}
});
} else {
const downloadBtn = item.querySelector('.download-btn');
downloadBtn.addEventListener('click', async () => {
downloadBtn.textContent = 'Downloading...';
downloadBtn.disabled = true;
try {
await window.foundryAPI.downloadWhisperModel(model.alias);
showToast(`Downloaded ${model.alias}`, 'success');
selectedWhisperModel = model.alias;
const updatedModels = await window.foundryAPI.getWhisperModels();
showWhisperModal(updatedModels, true);
} catch (error) {
showToast('Download failed: ' + error.message, 'error');
downloadBtn.textContent = 'Download';
downloadBtn.disabled = false;
}
});
}
whisperModelList.appendChild(item);
});
whisperModal.classList.add('visible');
}
async function startRecording() {
try {
// Request 16kHz mono audio for Whisper compatibility
const stream = await navigator.mediaDevices.getUserMedia({
audio: {
sampleRate: 16000,
channelCount: 1,
echoCancellation: true,
noiseSuppression: true
}
});
mediaRecorder = new MediaRecorder(stream);
audioChunks = [];
mediaRecorder.ondataavailable = (e) => {
audioChunks.push(e.data);
};
mediaRecorder.onstop = async () => {
// Stop all tracks
stream.getTracks().forEach(track => track.stop());
// Create audio blob
const audioBlob = new Blob(audioChunks, { type: mediaRecorder.mimeType });
await transcribeAudio(audioBlob);
};
mediaRecorder.start();
isRecording = true;
recordBtn.classList.add('recording');
showToast('Recording... Click stop when done', 'warning');
} catch (error) {
console.error('Failed to start recording:', error);
showToast('Failed to access microphone', 'error');
}
}
function stopRecording() {
if (mediaRecorder && isRecording) {
mediaRecorder.stop();
isRecording = false;
recordBtn.classList.remove('recording');
recordBtn.classList.add('transcribing');
}
}
// Convert audio blob to 16kHz mono WAV format for Whisper
async function convertToWav(audioBlob) {
const audioContext = new AudioContext();
try {
const arrayBuffer = await audioBlob.arrayBuffer();
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
// Resample to 16kHz mono
const targetSampleRate = 16000;
const offlineContext = new OfflineAudioContext(1, audioBuffer.duration * targetSampleRate, targetSampleRate);
const source = offlineContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(offlineContext.destination);
source.start(0);
const resampledBuffer = await offlineContext.startRendering();
// Convert to WAV
const wavBuffer = audioBufferToWav(resampledBuffer);
return new Blob([wavBuffer], { type: 'audio/wav' });
} finally {
await audioContext.close();
}
}
// Encode AudioBuffer to 16-bit PCM WAV format
function audioBufferToWav(buffer) {
const numChannels = 1; // Force mono
const sampleRate = buffer.sampleRate;
const bitDepth = 16;
const bytesPerSample = bitDepth / 8;
const blockAlign = numChannels * bytesPerSample;
// Get mono channel (mix down if stereo)
let monoData;
if (buffer.numberOfChannels === 1) {
monoData = buffer.getChannelData(0);
} else {
// Mix stereo to mono
const left = buffer.getChannelData(0);
const right = buffer.getChannelData(1);
monoData = new Float32Array(left.length);
for (let i = 0; i < left.length; i++) {
monoData[i] = (left[i] + right[i]) / 2;
}
}
const samples = monoData.length;
const dataSize = samples * blockAlign;
const bufferSize = 44 + dataSize;
const arrayBuffer = new ArrayBuffer(bufferSize);
const view = new DataView(arrayBuffer);
// RIFF header
writeString(view, 0, 'RIFF');
view.setUint32(4, 36 + dataSize, true);
writeString(view, 8, 'WAVE');
// fmt chunk
writeString(view, 12, 'fmt ');
view.setUint32(16, 16, true); // chunk size
view.setUint16(20, 1, true); // PCM format
view.setUint16(22, numChannels, true);
view.setUint32(24, sampleRate, true);
view.setUint32(28, sampleRate * blockAlign, true);
view.setUint16(32, blockAlign, true);
view.setUint16(34, bitDepth, true);
// data chunk
writeString(view, 36, 'data');
view.setUint32(40, dataSize, true);
// Write audio data as 16-bit PCM
let offset = 44;
for (let i = 0; i < samples; i++) {
const sample = Math.max(-1, Math.min(1, monoData[i]));
const intSample = sample < 0 ? sample * 0x8000 : sample * 0x7FFF;
view.setInt16(offset, intSample, true);
offset += 2;
}
return arrayBuffer;
}
function writeString(view, offset, string) {
for (let i = 0; i < string.length; i++) {
view.setUint8(offset + i, string.charCodeAt(i));
}
}
async function transcribeAudio(audioBlob) {
try {
showToast('Converting audio...', 'warning');
// Convert to 16kHz mono WAV format for Whisper compatibility
let wavBlob;
try {
wavBlob = await convertToWav(audioBlob);
} catch (e) {
console.error('WAV conversion failed:', e);
showToast('Audio conversion failed: ' + e.message, 'error');
recordBtn.classList.remove('transcribing');
return;
}
showToast('Transcribing audio...', 'warning');
// Convert blob to base64
const arrayBuffer = await wavBlob.arrayBuffer();
const uint8Array = new Uint8Array(arrayBuffer);
// Use chunked base64 encoding for large arrays
let base64 = '';
const chunkSize = 32768;
for (let i = 0; i < uint8Array.length; i += chunkSize) {
const chunk = uint8Array.subarray(i, i + chunkSize);
base64 += String.fromCharCode.apply(null, chunk);
}
base64 = btoa(base64);
const tempPath = `/tmp/foundry_audio_${Date.now()}.wav`;
const result = await window.foundryAPI.transcribeAudio(tempPath, base64);
// Insert transcribed text into input
const text = result.text || result.Text || '';
if (text) {
messageInput.value += text;
messageInput.dispatchEvent(new Event('input'));
showToast('Transcription complete', 'success');
} else {
showToast('No speech detected', 'warning');
}
} catch (error) {
console.error('Transcription failed:', error);
showToast('Transcription failed: ' + error.message, 'error');
} finally {
recordBtn.classList.remove('transcribing');
}
}
function setupEventListeners() {
// Sidebar toggle
sidebarToggle.addEventListener('click', () => {
sidebar.classList.toggle('collapsed');
});
mobileMenuBtn.addEventListener('click', () => {
sidebar.classList.toggle('open');
});
// Refresh models
refreshModels.addEventListener('click', async () => {
refreshModels.classList.add('spinning');
await loadModels();
refreshModels.classList.remove('spinning');
});
// Chat form
chatForm.addEventListener('submit', handleSendMessage);
// Textarea auto-resize
messageInput.addEventListener('input', () => {
messageInput.style.height = 'auto';
messageInput.style.height = Math.min(messageInput.scrollHeight, 150) + 'px';
});
// Enter to send, Shift+Enter for new line
messageInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
chatForm.dispatchEvent(new Event('submit'));
}
});
// New chat
newChatBtn.addEventListener('click', clearChat);
// Close sidebar on outside click (mobile)
document.addEventListener('click', (e) => {
if (window.innerWidth <= 768 &&
sidebar.classList.contains('open') &&
!sidebar.contains(e.target) &&
!mobileMenuBtn.contains(e.target)) {
sidebar.classList.remove('open');
}
});
}
function setupChatChunkListener() {
window.foundryAPI.onChatChunk((data) => {
if (data.content) {
appendToLastAssistantMessage(data.content);
}
});
}
// Model Management
async function loadModels() {
modelList.innerHTML = `
<div class="loading-spinner">
<div class="spinner"></div>
<span>Loading models...</span>
</div>
`;
try {
const models = await window.foundryAPI.getModels();
if (!models || models.length === 0) {
modelList.innerHTML = `
<div class="loading-spinner">
<span>No models found</span>
</div>
`;
return;
}
// Filter out whisper/audio models - only show chat models
const chatModels = models.filter(m => {
const alias = m.alias.toLowerCase();
// Exclude whisper and other audio models
if (alias.includes('whisper')) return false;
return true;
});
const displayModels = chatModels;
// Sort: cached first, then by name
displayModels.sort((a, b) => {
if (a.isCached && !b.isCached) return -1;
if (!a.isCached && b.isCached) return 1;
return a.alias.localeCompare(b.alias);
});
// Group by cached status
const cachedModels = displayModels.filter(m => m.isCached);
const availableModels = displayModels.filter(m => !m.isCached);
modelList.innerHTML = '';
if (cachedModels.length > 0) {
const cachedGroup = document.createElement('div');
cachedGroup.className = 'model-group';
cachedGroup.innerHTML = `
<div class="model-group-header">
<div class="status-dot cached"></div>
<span>Downloaded</span>
</div>
`;
cachedModels.forEach(model => {
cachedGroup.appendChild(createModelItem(model));
});
modelList.appendChild(cachedGroup);
}
if (availableModels.length > 0) {
const availableGroup = document.createElement('div');
availableGroup.className = 'model-group';
availableGroup.innerHTML = `
<div class="model-group-header">
<div class="status-dot"></div>
<span>Available</span>
</div>
`;
availableModels.forEach(model => {
availableGroup.appendChild(createModelItem(model));
});
modelList.appendChild(availableGroup);
}
if (displayModels.length === 0) {
modelList.innerHTML = `
<div class="loading-spinner">
<span>No models available</span>
</div>
`;
}
} catch (error) {
console.error('Failed to load models:', error);
modelList.innerHTML = `
<div class="loading-spinner">
<span>Failed to load models</span>
<span style="font-size: 11px; color: var(--error);">${error.message || error}</span>
</div>
`;
showToast('Failed to load models: ' + error.message, 'error');
}
}
function createModelItem(model) {
const variant = model.variants[0];
const item = document.createElement('div');
item.className = 'model-item';
const isActive = model.alias === currentModelAlias;
if (isActive) {
item.classList.add('active');
}
const sizeMb = variant?.fileSizeMb;
const sizeStr = sizeMb ? `${(sizeMb / 1024).toFixed(1)} GB` : '';
let statusHtml;
if (isActive) {
statusHtml = `
<button class="unload-btn">Unload</button>
`;
} else if (model.isCached) {
statusHtml = `
<button class="delete-model-btn" title="Delete from cache">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="3 6 5 6 21 6"></polyline>
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
<line x1="10" y1="11" x2="10" y2="17"></line>
<line x1="14" y1="11" x2="14" y2="17"></line>
</svg>
</button>
<button class="load-btn">Load</button>
`;
} else {
statusHtml = '<button class="download-btn">Download</button>';
}
item.innerHTML = `
<div class="model-icon">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/>
<polyline points="3.27 6.96 12 12.01 20.73 6.96"/>
<line x1="12" y1="22.08" x2="12" y2="12"/>
</svg>
</div>
<div class="model-info">
<div class="model-name">${model.alias}</div>
<div class="model-size">${sizeStr}</div>
</div>
<div class="model-status">
${statusHtml}
</div>
`;
// Handle click events
if (isActive) {
const unloadBtn = item.querySelector('.unload-btn');
unloadBtn.addEventListener('click', async (e) => {
e.stopPropagation();
await unloadModel();
});
} else if (model.isCached) {
const loadBtn = item.querySelector('.load-btn');
loadBtn.addEventListener('click', async (e) => {
e.stopPropagation();
await loadModel(model.alias);
});
const deleteBtn = item.querySelector('.delete-model-btn');
deleteBtn.addEventListener('click', async (e) => {
e.stopPropagation();
if (confirm(`Delete ${model.alias} from cache?`)) {
try {
await window.foundryAPI.deleteModel(model.alias);
showToast(`Deleted ${model.alias}`, 'success');
await loadModels();
} catch (error) {
showToast('Delete failed: ' + error.message, 'error');
}
}
});
} else {
const downloadBtn = item.querySelector('.download-btn');
downloadBtn.addEventListener('click', async (e) => {
e.stopPropagation();
await downloadModel(model.alias, item);
});
}
return item;
}
async function downloadModel(alias, itemElement) {
const statusEl = itemElement.querySelector('.model-status');
statusEl.innerHTML = '<div class="status-indicator loading"></div>';
try {
showToast(`Downloading ${alias}...`, 'warning');
await window.foundryAPI.downloadModel(alias);
showToast(`Downloaded ${alias}. Loading...`, 'success');
await loadModels();
// Auto-load the model after download
await loadModel(alias);
} catch (error) {
console.error('Download failed:', error);
showToast('Download failed: ' + error.message, 'error');
await loadModels();
}
}
async function loadModel(alias) {
if (isGenerating) {
showToast('Please wait for the current response to finish', 'warning');
return;
}
// Update UI to show loading
const items = modelList.querySelectorAll('.model-item');
items.forEach(item => {
item.classList.remove('active');
const nameEl = item.querySelector('.model-name');
if (nameEl.textContent.includes(alias) || item.dataset.alias === alias) {
item.classList.add('loading');
}
});
try {
showToast(`Loading ${alias}...`, 'warning');
await window.foundryAPI.loadModel(alias);
currentModelAlias = alias;
// Update UI
updateCurrentModelDisplay(alias);
enableChat();
showToast(`Model ${alias} loaded`, 'success');
// Refresh model list to update active state
await loadModels();
} catch (error) {
console.error('Failed to load model:', error);
showToast('Failed to load model: ' + error.message, 'error');
await loadModels();
}
}
async function unloadModel() {
if (isGenerating) {
showToast('Please wait for the current response to finish', 'warning');
return;
}
try {
showToast('Unloading model...', 'warning');
await window.foundryAPI.unloadModel();
currentModelAlias = null;
// Update UI
modelBadge.textContent = 'Select a model to start';
disableChat();
showToast('Model unloaded', 'success');
// Refresh model list
await loadModels();
} catch (error) {
console.error('Failed to unload model:', error);
showToast('Failed to unload model: ' + error.message, 'error');
}
}
function updateCurrentModelDisplay(alias) {
modelBadge.textContent = alias;
}
function enableChat() {
messageInput.disabled = false;
sendBtn.disabled = false;
messageInput.placeholder = 'Type your message...';
messageInput.focus();
}
function disableChat() {
messageInput.disabled = true;
sendBtn.disabled = true;
messageInput.placeholder = 'Select a model to start chatting...';
}
// Chat Management
async function handleSendMessage(e) {
e.preventDefault();
const content = messageInput.value.trim();
if (!content || isGenerating || !currentModelAlias) return;
// Clear welcome message if present
const welcomeMessage = chatMessages.querySelector('.welcome-message');
if (welcomeMessage) {
welcomeMessage.remove();
}
// Add user message
messages.push({ role: 'user', content });
addMessageToChat('user', content);
updateContextUsage();
// Clear input
messageInput.value = '';
messageInput.style.height = 'auto';
// Disable send button
isGenerating = true;
sendBtn.disabled = true;
// Add typing indicator
const typingEl = addTypingIndicator();
try {
// Make API call
const result = await window.foundryAPI.chat(messages);
// Remove typing indicator
typingEl.remove();
// Add assistant message (content was already streamed, just add stats)
messages.push({ role: 'assistant', content: result.content });
updateLastAssistantMessageStats(result.stats);
updateContextUsage();
} catch (error) {
console.error('Chat error:', error);
typingEl.remove();
showToast('Chat error: ' + error.message, 'error');
} finally {
isGenerating = false;
sendBtn.disabled = false;
messageInput.focus();
}
}
function addMessageToChat(role, content) {
const messageEl = document.createElement('div');
messageEl.className = `message ${role}`;
const avatar = role === 'user' ? 'U' :
`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/>
</svg>`;
messageEl.innerHTML = `
<div class="message-avatar">${avatar}</div>
<div class="message-content">
<div class="message-bubble">${role === 'user' ? SimpleMarkdown.escapeHtml(content) : SimpleMarkdown.parse(content)}</div>
${role === 'assistant' ? '<div class="message-stats"></div>' : ''}
</div>
`;
chatMessages.appendChild(messageEl);
scrollToBottom();
return messageEl;
}
function addTypingIndicator() {
const typingEl = document.createElement('div');
typingEl.className = 'message assistant';
typingEl.id = 'typing-indicator';
typingEl.innerHTML = `
<div class="message-avatar">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/>
</svg>
</div>
<div class="message-content">
<div class="typing-indicator">
<span></span>
<span></span>
<span></span>
</div>
</div>
`;
chatMessages.appendChild(typingEl);
scrollToBottom();
return typingEl;
}
let currentAssistantMessage = null;
let currentAssistantContent = '';
function appendToLastAssistantMessage(content) {
// If there's a typing indicator, replace it with actual message
const typingIndicator = document.getElementById('typing-indicator');
if (typingIndicator) {
typingIndicator.remove();
currentAssistantMessage = addMessageToChat('assistant', '');
currentAssistantContent = '';
}
if (!currentAssistantMessage) {
currentAssistantMessage = addMessageToChat('assistant', '');
currentAssistantContent = '';
}
currentAssistantContent += content;
const bubble = currentAssistantMessage.querySelector('.message-bubble');
bubble.innerHTML = SimpleMarkdown.parse(currentAssistantContent);
scrollToBottom();
}
function updateLastAssistantMessageStats(stats) {
if (!currentAssistantMessage) return;
const statsEl = currentAssistantMessage.querySelector('.message-stats');
if (statsEl && stats) {
statsEl.innerHTML = `
<div class="stat-item">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="12" r="10"/>
<polyline points="12 6 12 12 16 14"/>
</svg>
<span>TTFT: ${stats.timeToFirstToken}ms</span>
</div>
<div class="stat-item">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/>
</svg>
<span>${stats.tokensPerSecond} tok/s</span>
</div>
<div class="stat-item">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M22 11.08V12a10 10 0 11-5.93-9.14"/>
<polyline points="22 4 12 14.01 9 11.01"/>
</svg>
<span>${stats.tokenCount} tokens</span>
</div>
`;
}
// Reset for next message
currentAssistantMessage = null;
currentAssistantContent = '';
}
function clearChat() {
messages = [];