-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
3519 lines (3033 loc) · 120 KB
/
app.js
File metadata and controls
3519 lines (3033 loc) · 120 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
// Core app state
const messagesEl = document.getElementById('messages');
const inputEl = document.getElementById('input');
const sendBtn = document.getElementById('send');
const modelEl = document.getElementById('model');
const systemEl = document.getElementById('system');
const clearBtn = document.getElementById('clear');
const exportBtn = document.getElementById('export');
const sessionsEl = document.getElementById('sessions');
const statusEl = document.getElementById('status');
const newChatBtn = document.getElementById('newChat');
// Storage keys - versioned for schema changes
const STORAGE_KEY = 'chat_sessions_v2'; // Updated version for new schema
const VOTES_KEY = 'model_votes_v2'; // Updated for blind mode
const PROMPTS_KEY = 'saved_prompts_v1';
const BLIND_SESSIONS_KEY = 'blind_sessions_v1'; // New: blind mode state
const MODEL_INSTANCES_KEY = 'model_instances_v1'; // New: saved hyperparameter configs
const SIDEBAR_STATE_KEY = 'sidebar_collapsed_v1';
let sessions = [];
let currentSessionId = null;
let abortController = null;
let requestTimeout = null;
const REQUEST_TIMEOUT_MS = 300000; // 5 minutes for multiple models
let uploadedFiles = []; // Array of uploaded files for current conversation
let previousModels = []; // Store previous model selection for "back to comparison"
let sidebarCollapsed = false;
// ========== BLIND MODE STATE ==========
let blindModeEnabled = false;
let blindSessionState = null; // {sessionId, mapping: {instanceId: blindLabel}, revealed: false, revealedAt: null, votes: {}}
// ========== MODEL INSTANCE STATE ==========
// Each instance: {id, model, temperature, top_p, top_k, repeat_penalty, num_predict, seed}
let modelInstances = [];
// Default hyperparameters (Ollama defaults)
const DEFAULT_HYPERPARAMS = {
temperature: 0.7,
top_p: 0.9,
top_k: 40,
repeat_penalty: 1.1,
num_predict: -1, // -1 = unlimited
seed: 0 // 0 = random
};
// ========== SIDEBAR TOGGLE ==========
function toggleSidebar() {
const sidebar = document.getElementById('sidebar');
const mainArea = document.querySelector('.main-area');
const hamburger = document.getElementById('sidebarToggle');
sidebarCollapsed = !sidebarCollapsed;
if (sidebarCollapsed) {
sidebar.classList.add('collapsed');
mainArea.classList.add('sidebar-collapsed');
hamburger.classList.add('active');
} else {
sidebar.classList.remove('collapsed');
mainArea.classList.remove('sidebar-collapsed');
hamburger.classList.remove('active');
}
localStorage.setItem(SIDEBAR_STATE_KEY, sidebarCollapsed ? 'true' : 'false');
}
function loadSidebarState() {
const saved = localStorage.getItem(SIDEBAR_STATE_KEY);
if (saved === 'true') {
sidebarCollapsed = true;
const sidebar = document.getElementById('sidebar');
const mainArea = document.querySelector('.main-area');
const hamburger = document.getElementById('sidebarToggle');
if (sidebar) sidebar.classList.add('collapsed');
if (mainArea) mainArea.classList.add('sidebar-collapsed');
if (hamburger) hamburger.classList.add('active');
}
}
// ========== UNIFIED MODEL SELECTION ==========
function addModelToArena() {
const modelSelect = document.getElementById('modelSelect');
const tempInput = document.getElementById('addModelTemp');
const topPInput = document.getElementById('addModelTopP');
const topKInput = document.getElementById('addModelTopK');
const repeatPenaltyInput = document.getElementById('addModelRepeatPenalty');
const numPredictInput = document.getElementById('addModelNumPredict');
const seedInput = document.getElementById('addModelSeed');
if (!modelSelect || !modelSelect.value) {
showHelperText('⚠️ Please select a model');
setTimeout(hideHelperText, 2000);
return;
}
const modelName = modelSelect.value;
const temperature = parseFloat(tempInput?.value) || DEFAULT_HYPERPARAMS.temperature;
const top_p = parseFloat(topPInput?.value) || DEFAULT_HYPERPARAMS.top_p;
const top_k = parseInt(topKInput?.value) || DEFAULT_HYPERPARAMS.top_k;
const repeat_penalty = parseFloat(repeatPenaltyInput?.value) || DEFAULT_HYPERPARAMS.repeat_penalty;
const num_predict = parseInt(numPredictInput?.value);
const seed = parseInt(seedInput?.value) || DEFAULT_HYPERPARAMS.seed;
// Create instance with all hyperparameters
const params = {
temperature: temperature,
top_p: top_p,
top_k: top_k,
repeat_penalty: repeat_penalty,
num_predict: isNaN(num_predict) ? DEFAULT_HYPERPARAMS.num_predict : num_predict,
seed: seed
};
const inst = createModelInstance(modelName, params);
// Allow duplicates with DIFFERENT temperatures, but not identical instances
if (isDuplicateInstance(inst)) {
showHelperText('⚠️ This exact configuration already exists');
setTimeout(hideHelperText, 2000);
return;
}
if (modelInstances.length >= 8) {
showHelperText('⚠️ Maximum 8 models allowed');
setTimeout(hideHelperText, 2000);
return;
}
modelInstances.push(inst);
saveModelInstances();
renderSelectedModelsChips();
// Reset dropdown but keep temperature
modelSelect.value = '';
showHelperText(`✓ Added ${modelName}`);
setTimeout(hideHelperText, 1500);
}
function removeModelFromArena(instanceId) {
modelInstances = modelInstances.filter(i => i.id !== instanceId);
saveModelInstances();
renderSelectedModelsChips();
}
function renderSelectedModelsChips() {
const container = document.getElementById('selectedModelsChips');
if (!container) return;
if (modelInstances.length === 0) {
container.innerHTML = '<div class="empty-models-hint">Select models above to compare</div>';
return;
}
const isBlindActive = blindModeEnabled && blindSessionState && !blindSessionState.revealed;
let html = '';
modelInstances.forEach((inst, idx) => {
// In blind mode, hide the actual model name and hyperparams
let displayText;
let displayParams = '';
const chipClass = isBlindActive ? 'model-chip blind-mode' : 'model-chip';
if (isBlindActive) {
// Show blind label or generic "Model X"
const blindLabel = blindSessionState.mapping[inst.id] || `Model ${String.fromCharCode(65 + idx)}`;
displayText = blindLabel;
// No hyperparams shown in blind mode
} else {
displayText = inst.model;
// Show all hyperparameters using helper
displayParams = formatHyperparamsShort(inst);
}
html += `
<div class="${chipClass}" data-instance-id="${inst.id}">
<span class="chip-name">${displayText}</span>
${displayParams ? `<span class="chip-params">${displayParams}</span>` : ''}
${!isBlindActive ? `<button class="chip-remove" onclick="removeModelFromArena('${inst.id}')" title="Remove">×</button>` : ''}
</div>
`;
});
container.innerHTML = html;
}
async function populateModelDropdown() {
const select = document.getElementById('modelSelect');
if (!select) return;
select.innerHTML = '<option value="">+ Add model...</option>';
// Always fetch fresh models from API
try {
const res = await fetch('/api/models');
const data = await res.json();
const models = data.models || [];
models.forEach(m => {
const opt = document.createElement('option');
opt.value = m;
opt.textContent = m;
select.appendChild(opt);
// Also add to hidden select for compatibility if not already there
if (!Array.from(modelEl.options).some(o => o.value === m)) {
const hiddenOpt = document.createElement('option');
hiddenOpt.value = m;
hiddenOpt.textContent = m;
modelEl.appendChild(hiddenOpt);
}
});
// Update global installedModels if defined
if (typeof installedModels !== 'undefined') {
installedModels = models;
}
} catch (err) {
console.error('Failed to load models:', err);
}
}
// Export new functions to window
window.toggleSidebar = toggleSidebar;
window.addModelToArena = addModelToArena;
window.removeModelFromArena = removeModelFromArena;
// ========== BLIND MODE UTILITIES ==========
function generateBlindLabels(count) {
const labels = [];
for (let i = 0; i < count; i++) {
labels.push('Model ' + String.fromCharCode(65 + i)); // A, B, C, ...
}
return labels;
}
function shuffleArray(array) {
const shuffled = [...array];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
function createBlindMapping(instanceIds) {
const labels = generateBlindLabels(instanceIds.length);
const shuffledLabels = shuffleArray(labels);
const mapping = {};
instanceIds.forEach((id, idx) => {
mapping[id] = shuffledLabels[idx];
});
return mapping;
}
function loadBlindSession(sessionId) {
try {
const raw = localStorage.getItem(BLIND_SESSIONS_KEY);
const allSessions = raw ? JSON.parse(raw) : {};
return allSessions[sessionId] || null;
} catch (e) {
return null;
}
}
function saveBlindSession(sessionId, blindState) {
try {
const raw = localStorage.getItem(BLIND_SESSIONS_KEY);
const allSessions = raw ? JSON.parse(raw) : {};
allSessions[sessionId] = blindState;
localStorage.setItem(BLIND_SESSIONS_KEY, JSON.stringify(allSessions));
} catch (e) {
console.error('Failed to save blind session:', e);
}
}
function getBlindLabel(instanceId) {
if (!blindModeEnabled || !blindSessionState || blindSessionState.revealed) {
return null;
}
// Direct lookup
if (blindSessionState.mapping[instanceId]) {
return blindSessionState.mapping[instanceId];
}
// Fallback: try to find by model name prefix (handles ID format differences)
const modelName = instanceId.split('__')[0];
for (const [id, label] of Object.entries(blindSessionState.mapping)) {
if (id.split('__')[0] === modelName) {
return label;
}
}
return null;
}
// Helper to format hyperparams for display (condensed)
function formatHyperparamsShort(inst) {
let parts = [`T=${inst.temperature}`, `P=${inst.top_p}`, `K=${inst.top_k}`];
// Only show non-default advanced params
if (inst.repeat_penalty !== DEFAULT_HYPERPARAMS.repeat_penalty) {
parts.push(`R=${inst.repeat_penalty}`);
}
if (inst.num_predict !== DEFAULT_HYPERPARAMS.num_predict) {
parts.push(`M=${inst.num_predict}`);
}
if (inst.seed !== DEFAULT_HYPERPARAMS.seed) {
parts.push(`S=${inst.seed}`);
}
return parts.join(' ');
}
function getDisplayName(instanceId, model) {
const blindLabel = getBlindLabel(instanceId);
if (blindLabel) {
// In blind mode, ONLY show the blind label - no hyperparams or model info
return blindLabel;
}
// In blind mode but no label found - create one on the fly
if (blindModeEnabled && blindSessionState && !blindSessionState.revealed) {
const existingLabels = Object.values(blindSessionState.mapping);
const nextIdx = existingLabels.length;
const newLabel = 'Model ' + String.fromCharCode(65 + nextIdx);
blindSessionState.mapping[instanceId] = newLabel;
saveBlindSession(currentSessionId, blindSessionState);
return newLabel; // Return ONLY the label, no hyperparams
}
// Normal mode: ALWAYS show all hyperparams for unique identification
const inst = modelInstances.find(i => i.id === instanceId);
if (inst) {
return `${model} (${formatHyperparamsShort(inst)})`;
}
// Fallback: try to parse from instanceId
const parts = instanceId.split('__');
if (parts.length > 1) {
const paramParts = parts[1].split('_');
if (paramParts.length >= 3) {
return `${model} (T=${paramParts[0]} P=${paramParts[1]} K=${paramParts[2]})`;
}
}
return model;
}
function hasCustomHyperparams(inst) {
return inst.temperature !== DEFAULT_HYPERPARAMS.temperature ||
inst.top_p !== DEFAULT_HYPERPARAMS.top_p ||
inst.top_k !== DEFAULT_HYPERPARAMS.top_k ||
inst.repeat_penalty !== DEFAULT_HYPERPARAMS.repeat_penalty ||
inst.num_predict !== DEFAULT_HYPERPARAMS.num_predict ||
inst.seed !== DEFAULT_HYPERPARAMS.seed;
}
// ========== MODEL INSTANCE UTILITIES ==========
function generateInstanceId(model, params) {
// Create deterministic ID from model + hyperparams
const paramStr = `${params.temperature || DEFAULT_HYPERPARAMS.temperature}_${params.top_p || DEFAULT_HYPERPARAMS.top_p}_${params.top_k || DEFAULT_HYPERPARAMS.top_k}_${params.repeat_penalty || DEFAULT_HYPERPARAMS.repeat_penalty}_${params.num_predict !== undefined ? params.num_predict : DEFAULT_HYPERPARAMS.num_predict}_${params.seed || DEFAULT_HYPERPARAMS.seed}`;
return `${model}__${paramStr}`.replace(/[^a-zA-Z0-9_.-]/g, '_');
}
function createModelInstance(model, params = {}) {
const inst = {
id: generateInstanceId(model, params),
model: model,
temperature: params.temperature !== undefined ? params.temperature : DEFAULT_HYPERPARAMS.temperature,
top_p: params.top_p !== undefined ? params.top_p : DEFAULT_HYPERPARAMS.top_p,
top_k: params.top_k !== undefined ? params.top_k : DEFAULT_HYPERPARAMS.top_k,
repeat_penalty: params.repeat_penalty !== undefined ? params.repeat_penalty : DEFAULT_HYPERPARAMS.repeat_penalty,
num_predict: params.num_predict !== undefined ? params.num_predict : DEFAULT_HYPERPARAMS.num_predict,
seed: params.seed !== undefined ? params.seed : DEFAULT_HYPERPARAMS.seed
};
return inst;
}
function isDuplicateInstance(newInst) {
return modelInstances.some(inst => inst.id === newInst.id);
}
function validateHyperparams(params) {
const errors = [];
if (params.temperature !== undefined && params.temperature <= 0) {
errors.push('Temperature must be > 0');
}
if (params.top_p !== undefined && (params.top_p <= 0 || params.top_p > 1)) {
errors.push('Top-p must be in (0, 1]');
}
if (params.top_k !== undefined && params.top_k < 0) {
errors.push('Top-k must be >= 0');
}
return errors;
}
function saveModelInstances() {
try {
localStorage.setItem(MODEL_INSTANCES_KEY, JSON.stringify(modelInstances));
} catch (e) {
console.error('Failed to save model instances:', e);
}
}
function loadModelInstances() {
try {
const raw = localStorage.getItem(MODEL_INSTANCES_KEY);
modelInstances = raw ? JSON.parse(raw) : [];
} catch (e) {
modelInstances = [];
}
}
// Markdown renderer - simple and safe
function renderMarkdown(text) {
if (!text) return '';
let html = text;
// Escape HTML first
html = html
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
// Code blocks (``` ... ```)
html = html.replace(/```[\s\S]*?```/g, (match) => {
const code = match.slice(3, -3).trim();
return '<pre><code>' + code + '</code></pre>';
});
// Inline code (`...`)
html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
// Bold (**...** or __...__)
html = html.replace(/\*\*([^\*\n]+)\*\*/g, '<strong>$1</strong>');
html = html.replace(/__([^_\n]+)__/g, '<strong>$1</strong>');
// Italic (*...* or _..._)
html = html.replace(/\*([^\*\n]+)\*/g, '<em>$1</em>');
html = html.replace(/_([^_\n]+)_/g, '<em>$1</em>');
// Links [text](url)
html = html.replace(/\[([^\]]+)\]\(([^\)]+)\)/g, '<a href="$2" target="_blank">$1</a>');
// Line breaks
html = html.replace(/\n/g, '<br>');
return html;
}
// Storage functions
function loadSessions(){
try {
const raw = localStorage.getItem(STORAGE_KEY);
sessions = raw ? JSON.parse(raw) : [];
} catch(e) {
console.error('localStorage error:', e);
sessions = [];
}
}
function saveSessions(){
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(sessions));
} catch(e) {
console.error('localStorage save error:', e);
}
}
function makeId(){
return Math.random().toString(36).slice(2, 10);
}
// Theme management
function initTheme(){
const savedTheme = localStorage.getItem('theme-preference') || 'light-mode';
applyTheme(savedTheme);
}
function applyTheme(theme){
const html = document.documentElement;
html.className = theme;
const themeBtn = document.getElementById('themeToggle');
if(themeBtn){
themeBtn.textContent = theme === 'dark-mode' ? '☀️' : '🌙';
}
localStorage.setItem('theme-preference', theme);
}
function toggleTheme(){
const html = document.documentElement;
const currentTheme = html.className || 'light-mode';
const newTheme = currentTheme === 'light-mode' ? 'dark-mode' : 'light-mode';
applyTheme(newTheme);
}
// ========== FEATURE UTILITIES ==========
// Feature 1: Copy to clipboard
async function copyToClipboard(text, buttonEl){
try {
await navigator.clipboard.writeText(text);
const originalHTML = buttonEl.innerHTML;
buttonEl.innerHTML = '✓ Copied!';
buttonEl.style.color = 'var(--success)';
setTimeout(() => {
buttonEl.innerHTML = originalHTML;
buttonEl.style.color = '';
}, 2000);
} catch(err) {
showHelperText('⚠️ Failed to copy to clipboard');
setTimeout(hideHelperText, 3000);
}
}
// Feature 2: Continue with single model
function continueWithModel(modelName){
// Store previous selection
previousModels = Array.from(modelEl.selectedOptions).map(o => o.value);
// Select only this model
Array.from(modelEl.options).forEach(opt => {
opt.selected = opt.value === modelName;
});
updateModelBadge();
// Save to session
if(currentSessionId) {
const s = sessions.find(x => x.id === currentSessionId);
if(s) {
s.models = [modelName];
s.previousModels = previousModels;
s.updatedAt = Date.now();
saveSessions();
}
}
// Show banner
showSingleModelBanner(modelName);
showHelperText(`✓ Now chatting with ${modelName} only`);
setTimeout(hideHelperText, 3000);
}
function showSingleModelBanner(modelName){
let banner = document.getElementById('singleModelBanner');
if(!banner){
banner = document.createElement('div');
banner.id = 'singleModelBanner';
banner.className = 'single-model-banner';
const mainArea = document.querySelector('.main-area');
if(mainArea) mainArea.insertBefore(banner, mainArea.firstChild);
}
banner.innerHTML = `
<span>ℹ️ Single model mode: <strong>${modelName}</strong></span>
<button onclick="backToComparisonMode()" class="btn btn-sm btn-outline-primary">← Back to Comparison Mode</button>
`;
banner.style.display = 'flex';
}
function hideSingleModelBanner(){
const banner = document.getElementById('singleModelBanner');
if(banner) banner.style.display = 'none';
}
window.backToComparisonMode = function(){
const s = sessions.find(x => x.id === currentSessionId);
if(s && s.previousModels && s.previousModels.length > 0){
Array.from(modelEl.options).forEach(opt => {
opt.selected = s.previousModels.includes(opt.value);
});
updateModelBadge();
s.models = s.previousModels;
s.updatedAt = Date.now();
saveSessions();
hideSingleModelBanner();
showHelperText('✓ Switched back to comparison mode');
setTimeout(hideHelperText, 3000);
}
};
// Feature 3: Regenerate response
async function regenerateResponse(modelName, originalPrompt, bubbleId){
const s = sessions.find(x => x.id === currentSessionId);
if(!s) return;
const bubble = document.getElementById(bubbleId);
if(!bubble) return;
// Store previous response
const previousContent = bubble.textContent || bubble.innerHTML;
// Show loading
bubble.innerHTML = '<span class="loading-spinner">⏳</span> Regenerating...';
const currentSystem = s.system || systemEl.value;
const payload = {
message: originalPrompt,
history: s.history.filter(h => h.role === 'system' || h.role === 'user'),
system: currentSystem,
model: modelName
};
try {
const res = await fetch('/api/chat', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(payload)
});
if(!res.ok) throw new Error('Regeneration failed');
const data = await res.json();
const newResponse = data.assistant || 'No response';
bubble.innerHTML = renderMarkdown(newResponse);
// Update metrics if available
const metricsId = bubbleId.replace('bubble-', 'metrics-');
const metricsDiv = document.getElementById(metricsId);
if(metricsDiv && data.metrics){
const tps = data.metrics.tokens_per_sec || 0;
const duration = data.metrics.duration_s || data.metrics.duration || 0;
metricsDiv.textContent = data.metrics.tokens + ' tok • ' + duration.toFixed(2) + 's • ' + tps.toFixed(1) + ' t/s [Regenerated]';
metricsDiv.style.display = 'block';
metricsDiv.style.opacity = '1';
}
showHelperText('✓ Response regenerated');
setTimeout(hideHelperText, 2000);
} catch(err) {
bubble.innerHTML = 'Error regenerating: ' + err.message;
showHelperText('⚠️ Failed to regenerate response');
setTimeout(hideHelperText, 3000);
}
}
// Regenerate response using model instance (with hyperparameters)
async function regenerateInstanceResponse(instanceId, originalPrompt, bubbleId){
const s = sessions.find(x => x.id === currentSessionId);
if(!s) return;
const bubble = document.getElementById(bubbleId);
if(!bubble) return;
// Find the instance in current modelInstances
let inst = modelInstances.find(i => i.id === instanceId);
// If not found, try to reconstruct from instanceId
if(!inst) {
// Parse instanceId format: model__temp_topp_topk
const parts = instanceId.split('__');
const modelName = parts[0];
let params = DEFAULT_HYPERPARAMS;
if (parts.length > 1) {
const paramParts = parts[1].split('_');
if (paramParts.length >= 3) {
params = {
temperature: parseFloat(paramParts[0]) || DEFAULT_HYPERPARAMS.temperature,
top_p: parseFloat(paramParts[1]) || DEFAULT_HYPERPARAMS.top_p,
top_k: parseInt(paramParts[2]) || DEFAULT_HYPERPARAMS.top_k
};
}
}
inst = {
id: instanceId,
model: modelName,
...params
};
}
// Show loading
bubble.innerHTML = '<span class="loading-spinner">⏳</span> Regenerating...';
const currentSystem = s.system || systemEl.value;
const payload = {
message: originalPrompt,
history: s.history.filter(h => h.role === 'system' || h.role === 'user'),
system: currentSystem,
model_instances: [inst]
};
try {
const res = await fetch('/api/chat', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(payload)
});
if(!res.ok) throw new Error('Regeneration failed');
const data = await res.json();
const newResponse = data.assistant || 'No response';
bubble.innerHTML = renderMarkdown(newResponse);
// Update metrics if available
const metricsId = bubbleId.replace('bubble-', 'metrics-');
const metricsDiv = document.getElementById(metricsId);
if(metricsDiv && data.metrics){
const tps = data.metrics.tokens_per_sec || 0;
const duration = data.metrics.duration_s || data.metrics.duration || 0;
metricsDiv.textContent = data.metrics.tokens + ' tok • ' + duration.toFixed(2) + 's • ' + tps.toFixed(1) + ' t/s [Regenerated]';
metricsDiv.style.display = 'block';
metricsDiv.style.opacity = '1';
}
showHelperText('✓ Response regenerated');
setTimeout(hideHelperText, 2000);
} catch(err) {
bubble.innerHTML = 'Error regenerating: ' + err.message;
showHelperText('⚠️ Failed to regenerate response');
setTimeout(hideHelperText, 3000);
}
}
// Continue with a specific model instance (switch to single model mode)
function continueWithInstance(instanceId){
const inst = modelInstances.find(i => i.id === instanceId);
if(inst){
// Clear all instances and keep only this one
modelInstances = [inst];
saveModelInstances();
renderModelInstancesPanel();
showHelperText(`✓ Continuing with ${inst.model}`);
setTimeout(hideHelperText, 2000);
} else {
// Fallback: try to use as model name
continueWithModel(instanceId);
}
}
// Feature 4: Voting system (updated for Blind Mode)
function loadVotes(){
try {
const raw = localStorage.getItem(VOTES_KEY);
return raw ? JSON.parse(raw) : {};
} catch(e) {
return {};
}
}
function saveVote(sessionId, messageId, instanceId, vote){
// In blind mode, votes are only allowed and tied to blind labels
if (blindModeEnabled && blindSessionState && !blindSessionState.revealed) {
const blindLabel = blindSessionState.mapping[instanceId];
if (!blindLabel) return; // Safety check
// Store vote in blind session state
if (!blindSessionState.votes) blindSessionState.votes = {};
const key = `${messageId}-${blindLabel}`;
blindSessionState.votes[key] = {
messageId,
blindLabel,
vote,
timestamp: Date.now()
};
saveBlindSession(sessionId, blindSessionState);
return;
}
// Normal mode voting (non-blind)
const votes = loadVotes();
const key = `${sessionId}-${messageId}-${instanceId}`;
votes[key] = {sessionId, messageId, instanceId, vote, timestamp: Date.now()};
localStorage.setItem(VOTES_KEY, JSON.stringify(votes));
}
function getVote(sessionId, messageId, instanceId){
// In blind mode, check blind session votes
if (blindModeEnabled && blindSessionState && !blindSessionState.revealed) {
const blindLabel = blindSessionState.mapping[instanceId];
if (!blindLabel || !blindSessionState.votes) return null;
const key = `${messageId}-${blindLabel}`;
return blindSessionState.votes[key]?.vote || null;
}
const votes = loadVotes();
const key = `${sessionId}-${messageId}-${instanceId}`;
return votes[key]?.vote || null;
}
function getModelVoteStats(instanceId){
// In blind mode after reveal, show stats by blind label
if (blindSessionState && blindSessionState.revealed) {
const blindLabel = blindSessionState.mapping[instanceId];
let upCount = 0, downCount = 0;
if (blindSessionState.votes) {
Object.values(blindSessionState.votes).forEach(v => {
if (v.blindLabel === blindLabel) {
if (v.vote === 'up') upCount++;
if (v.vote === 'down') downCount++;
}
});
}
return {upCount, downCount, blindLabel};
}
const votes = loadVotes();
let upCount = 0, downCount = 0;
Object.values(votes).forEach(v => {
if(v.instanceId === instanceId){
if(v.vote === 'up') upCount++;
if(v.vote === 'down') downCount++;
}
});
return {upCount, downCount};
}
function handleVote(sessionId, messageId, instanceId, voteType, buttonEl){
// Check if voting is allowed
if (blindModeEnabled && blindSessionState && blindSessionState.revealed) {
showHelperText('⚠️ Voting locked after reveal');
setTimeout(hideHelperText, 2000);
return;
}
if (!blindModeEnabled) {
// In normal mode, voting is disabled (only allowed in blind mode)
showHelperText('⚠️ Enable Blind Mode for voting');
setTimeout(hideHelperText, 2000);
return;
}
const currentVote = getVote(sessionId, messageId, instanceId);
const newVote = currentVote === voteType ? null : voteType;
saveVote(sessionId, messageId, instanceId, newVote);
// Update UI
const container = buttonEl.closest('.vote-container') || buttonEl.parentElement;
if(container){
const upBtn = container.querySelector('.vote-up');
const downBtn = container.querySelector('.vote-down');
if(upBtn && downBtn){
upBtn.classList.toggle('voted', newVote === 'up');
downBtn.classList.toggle('voted', newVote === 'down');
}
}
// Show feedback
const blindLabel = getBlindLabel(instanceId);
showHelperText(`✓ Vote recorded for ${blindLabel || instanceId}`);
setTimeout(hideHelperText, 2000);
}
// ========== BLIND MODE UI FUNCTIONS ==========
function toggleBlindMode() {
const checkbox = document.getElementById('blindModeToggle');
blindModeEnabled = checkbox ? checkbox.checked : !blindModeEnabled;
if (blindModeEnabled && currentSessionId) {
// Try to load existing blind session
blindSessionState = loadBlindSession(currentSessionId);
if (!blindSessionState) {
// Get instances to use (from modelInstances or legacy selection)
let instancesToUse = [];
if (modelInstances.length > 0) {
instancesToUse = [...modelInstances];
} else {
// Use legacy model selection
const selected = Array.from(modelEl.selectedOptions).map(o => o.value);
instancesToUse = selected.map(m => createModelInstance(m, DEFAULT_HYPERPARAMS));
}
// Create blind session state (even if no instances yet - will be populated on first message)
const instanceIds = instancesToUse.map(i => i.id);
blindSessionState = {
sessionId: currentSessionId,
mapping: instanceIds.length > 0 ? createBlindMapping(instanceIds) : {},
revealed: false,
revealedAt: null,
votes: {}
};
saveBlindSession(currentSessionId, blindSessionState);
}
showHelperText('🎭 Blind Mode enabled - model names will be hidden');
} else {
blindSessionState = null;
showHelperText('👁️ Blind Mode disabled');
}
updateBlindModeUI();
renderSelectedModelsChips(); // Re-render chips to show/hide hyperparams
setTimeout(hideHelperText, 2000);
renderMessages();
}
function revealModels() {
if (!blindModeEnabled || !blindSessionState || blindSessionState.revealed) {
return;
}
showConfirmDialog(
'🎭 Reveal all model identities? Voting will be locked permanently.',
() => {
blindSessionState.revealed = true;
blindSessionState.revealedAt = Date.now();
saveBlindSession(currentSessionId, blindSessionState);
renderMessages();
updateBlindModeUI();
showRevealSummary();
}
);
}
function showRevealSummary() {
if (!blindSessionState || !blindSessionState.revealed) return;
let summaryHtml = '<div class="reveal-summary"><h4>🎉 Model Reveal</h4><div class="reveal-table-container"><table class="reveal-table"><tr><th>Blind Label</th><th>Actual Model</th><th>Hyperparameters</th><th>Likes</th><th>Dislikes</th></tr>';
// Get all instances and their stats
const instanceIds = Object.keys(blindSessionState.mapping);
instanceIds.forEach(instanceId => {
const blindLabel = blindSessionState.mapping[instanceId];
const inst = modelInstances.find(i => i.id === instanceId);
const model = inst ? inst.model : instanceId;
const stats = getModelVoteStats(instanceId);
// Build hyperparameters string - format more compactly
let hyperparams = '';
if (inst) {
const params = [];
params.push(`T=${inst.temperature}`);
params.push(`P=${inst.top_p}`);
params.push(`K=${inst.top_k}`);
// Add non-default advanced params
if (inst.repeat_penalty !== DEFAULT_HYPERPARAMS.repeat_penalty) {
params.push(`R=${inst.repeat_penalty}`);
}
if (inst.num_predict !== DEFAULT_HYPERPARAMS.num_predict) {
params.push(`M=${inst.num_predict}`);
}
if (inst.seed !== DEFAULT_HYPERPARAMS.seed) {
params.push(`S=${inst.seed}`);
}
hyperparams = params.join(' • ');
}
summaryHtml += `<tr><td>${blindLabel}</td><td>${model}</td><td><small style="color:var(--text-muted);font-size:0.75em;">${hyperparams}</small></td><td class="votes-up">👍 ${stats.upCount}</td><td class="votes-down">👎 ${stats.downCount}</td></tr>`;
});
summaryHtml += '</table></div></div>';
// Show as a modal or append to messages
showInfoModal('Model Reveal Results', summaryHtml);
}
function updateBlindModeUI() {
const blindToggle = document.getElementById('blindModeToggle');
const revealBtn = document.getElementById('revealModelsBtn');
const addModelRow = document.querySelector('.add-model-row');
const blindInline = document.getElementById('blindModeInline');
if (blindToggle) {
blindToggle.checked = blindModeEnabled;
}
const isBlindActive = blindModeEnabled && blindSessionState && !blindSessionState.revealed;
if (revealBtn) {
revealBtn.style.display = isBlindActive ? 'inline-flex' : 'none';
}
// Hide add model row in blind mode (but keep chips visible with blind labels)
if (addModelRow) {
addModelRow.style.display = isBlindActive ? 'none' : 'flex';
}
// Add visual indicator when blind mode is active
if (blindInline) {
if (isBlindActive) {
blindInline.classList.add('active');
} else {
blindInline.classList.remove('active');
}
}
}
function showInfoModal(title, contentHtml) {
let modal = document.getElementById('infoModal');
if (!modal) {
modal = document.createElement('div');
modal.id = 'infoModal';
modal.className = 'confirm-modal';
document.body.appendChild(modal);
}
let modalMaxWidth = '500px';
try {
if (title && title.toLowerCase().includes('reveal')) modalMaxWidth = '1100px';