-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1944 lines (1836 loc) · 101 KB
/
index.html
File metadata and controls
1944 lines (1836 loc) · 101 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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>Local AI - Single HTML (with Small Model)</title>
<style>
:root { --bg:#0e0f13; --fg:#e5e7eb; --mut:#9ca3af; --accent:#7c3aed; --panel:#0b0c10; }
*{box-sizing:border-box}
html, body { height: 100% }
body { margin:0; background:var(--bg); color:var(--fg); font:16px/1.4 system-ui, Segoe UI, Roboto, Helvetica, Arial }
.app { display:flex; flex-direction:column; height:100% }
.header { position:sticky; top:0; background:linear-gradient(180deg, rgba(0,0,0,.5), transparent); backdrop-filter: blur(8px); padding:12px 12px 8px; border-bottom:1px solid rgba(255,255,255,.06) }
.title { font-weight:700 }
.sub { font-size:12px; color:var(--mut) }
.toolbar { display:flex; gap:8px; align-items:center; flex-wrap:wrap; margin-top:8px }
select, .badge { background:transparent; color:var(--fg); border:1px solid #333; border-radius:10px; padding:6px 10px }
.load { background:var(--accent); color:#fff; border:0; border-radius:10px; padding:6px 12px; font-weight:600 }
.status { font-size:12px; color:var(--mut); margin-left:auto }
.messages { flex:1; overflow:auto; padding:12px 12px 90px }
.msg { max-width:90%; padding:10px 12px; border-radius:14px; margin:6px 0; word-wrap:break-word; white-space:pre-wrap }
.user { margin-left:auto; background:#1f2937 }
.bot { margin-right:auto; background:#111827; border:1px solid #222 }
.inputbar { position:fixed; left:0; right:0; bottom:0; padding:10px 12px; background:linear-gradient(0deg, rgba(14,15,19,1), rgba(14,15,19,.85)); border-top:1px solid rgba(255,255,255,.06); z-index:20 }
.row { display:flex; gap:8px }
#in { flex:1; resize:none; max-height:180px; height:48px; padding:10px; border-radius:10px; border:1px solid #222; background:var(--panel); color:var(--fg); outline:none }
.btn { background:var(--accent); border:0; color:#fff; padding:0 14px; border-radius:10px; font-weight:600; min-width:60px }
.btn.ghost { background:transparent; color:var(--fg); border:1px solid #333 }
.btn.muted { background:#374151; color:#e5e7eb }
.ctrls { display:flex; gap:10px; align-items:center; flex-wrap:wrap; margin-top:6px }
.range { accent-color:var(--accent) }
.badge { color:var(--mut); font-size:12px }
.badge.accentPreview { border-color: var(--accent); color: var(--fg) }
.warning { background:#2a1c1c; border:1px solid #553; color:#f8d7da; padding:8px 10px; border-radius:10px; font-size:13px; margin-top:8px }
a { color:#a78bfa }
/* Progress bar */
.progress { position:relative; display:none; gap:8px; align-items:center; margin-top:8px }
.progressTrack { flex:1; background:#1b1d26; border:1px solid #2a2d3a; border-radius:999px; height:10px; overflow:hidden }
.progressBar { height:100%; width:0%; background:linear-gradient(90deg, var(--accent), #a78bfa); border-radius:999px; transition:width .15s ease }
.progressText { font-size:12px; color:var(--mut); min-width:52px; text-align:right }
/* Logs/Downloads modal */
.logModal { position:fixed; inset:0; display:none; place-items:center; background:rgba(0,0,0,.55); backdrop-filter:blur(6px); padding:16px; z-index:50 }
.logPanel { width:min(980px, 96vw); max-height:80vh; background:#0b0c10; border:1px solid #2a2d3a; border-radius:12px; overflow:hidden; box-shadow:0 10px 30px rgba(0,0,0,.4) }
.logHead { display:flex; align-items:center; gap:8px; justify-content:space-between; padding:10px 12px; border-bottom:1px solid #1f2230; background:#0f1117 }
.logTitle { font-weight:600 }
.logBtns { display:flex; gap:8px; align-items:center }
.tabs { display:flex; gap:6px; }
.tab { background:#1b1f2b; color:#e5e7eb; border:1px solid #2a2d3a; border-radius:8px; padding:6px 10px; font-size:12px; cursor:pointer }
.tab.active { background:#a78bfa; color:#0b0c10; border-color:#a78bfa }
.panelBody { display:flex; flex-direction:column }
#downloadsBody { display:none }
#logsBody { display:none }
#downloadsList { padding:16px; max-height:60vh; overflow:auto }
.downloadsGrid { display:grid; grid-template-columns:repeat(auto-fill, minmax(280px, 1fr)); gap:12px; margin-bottom:16px }
.downloadItem { background:#1b1f2b; border:1px solid #2a2d3a; border-radius:12px; padding:12px; display:flex; flex-direction:column; gap:8px; transition:all 0.2s ease }
.downloadItem:hover { border-color:var(--accent); background:#1f2330; transform:translateY(-2px); box-shadow:0 4px 12px rgba(0,0,0,0.3) }
.downloadItemHeader { display:flex; align-items:center; justify-content:space-between; gap:8px }
.downloadItemName { font-weight:600; font-size:14px; color:var(--fg); word-break:break-word; flex:1 }
.downloadItemMeta { display:flex; align-items:center; gap:8px; flex-wrap:wrap; font-size:11px; color:var(--mut) }
.modelBadge { background:var(--accent); color:#fff; padding:2px 6px; border-radius:6px; font-size:10px; font-weight:600; text-transform:uppercase }
.modelBadge.small { background:#4ade80; }
.modelBadge.medium { background:#fbbf24; }
.modelBadge.large { background:#ef4444; }
.modelBadge.cached { background:#10b981; }
.downloadItemActions { display:flex; gap:6px; margin-top:4px }
.downloadItemBtn { background:transparent; border:1px solid #2a2d3a; color:var(--fg); padding:6px 10px; border-radius:8px; font-size:11px; cursor:pointer; transition:all 0.2s }
.downloadItemBtn:hover { background:#2a2d3a; border-color:var(--accent) }
.downloadItemBtn.danger { border-color:#523; color:#fca5a5 }
.downloadItemBtn.danger:hover { background:#2b1b1b; border-color:#fca5a5 }
.downloadItemBtn.primary { background:var(--accent); border-color:var(--accent); color:#fff }
.downloadItemBtn.primary:hover { opacity:0.9 }
.delBtn { background:#2b1b1b; color:#fca5a5; border:1px solid #523; padding:4px 8px; border-radius:8px; font-size:12px }
.mgrBtns { display:flex; gap:8px; padding:12px 16px; border-top:1px solid #1f2230; background:#0f1117; flex-wrap:wrap }
.downloadsSection { margin-bottom:20px }
.downloadsSectionTitle { font-size:14px; font-weight:600; color:var(--fg); margin-bottom:12px; display:flex; align-items:center; gap:8px }
.downloadsSectionTitle::before { content:''; width:3px; height:16px; background:var(--accent); border-radius:2px }
.emptyState { text-align:center; padding:40px 20px; color:var(--mut); font-size:14px }
.emptyStateIcon { font-size:48px; margin-bottom:12px; opacity:0.5 }
body.light .downloadItem { background:#f3f4f6; border-color:#e5e7eb }
body.light .downloadItem:hover { background:#ffffff; border-color:var(--accent) }
body.light .downloadItemBtn { border-color:#e5e7eb; color:#111827 }
body.light .downloadItemBtn:hover { background:#e5e7eb }
body.light .mgrBtns { background:#f3f4f6; border-color:#e5e7eb }
.switch { display:inline-flex; align-items:center; gap:6px; padding:4px 8px; border-radius:10px; border:1px solid #333; user-select:none }
.switch input { appearance:none; width:34px; height:20px; background:#222; border-radius:999px; position:relative; outline:none; cursor:pointer; border:1px solid #333 }
.switch input:checked { background:#4ade80; border-color:#4ade80 }
.switch input::after { content:''; position:absolute; top:2px; left:2px; width:16px; height:16px; background:#fff; border-radius:50%; transition:left .2s ease }
.switch input:checked::after { left:16px }
select.nice { appearance:none; background:linear-gradient(180deg,#0f1117,#0b0c10); padding-right:26px; position:relative }
/* Light theme */
body.light { --bg:#f7f7fb; --fg:#111827; --mut:#4b5563; --panel:#ffffff }
body.light .user { background:#e5e7eb }
body.light .bot { background:#f3f4f6; border-color:#e5e7eb }
body.light .header { background:linear-gradient(180deg, rgba(255,255,255,.85), transparent); border-bottom:1px solid rgba(0,0,0,.06) }
body.light .inputbar { background:linear-gradient(0deg, #ffffff, rgba(255,255,255,.9)); border-top:1px solid rgba(0,0,0,.08) }
body.light #in { border-color:#e5e7eb; background:#fff; color:#111827 }
body.light select, body.light .badge { border-color:#e5e7eb; color:#111827 }
body.light select.nice { background: linear-gradient(180deg, #ffffff, #f7f7fb) }
body.light .progressTrack { background:#e5e7eb; border-color:#e5e7eb }
body.light .progressText { color:#6b7280 }
body.light .logPanel, body.light .creditsPanel { background:#ffffff; border-color:#e5e7eb }
body.light .logHead, body.light .creditsHead, body.light .mgrBtns { background:#f3f4f6; border-color:#e5e7eb }
body.light .tab { background:#e5e7eb; color:#111827; border-color:#e5e7eb }
body.light .tab.active { background:#a78bfa; color:#0b0c10; border-color:#a78bfa }
.logBtn { background:#1b1f2b; color:#e5e7eb; border:1px solid #2a2d3a; border-radius:8px; padding:6px 10px; font-size:12px }
#logBody { margin:0; padding:12px; font:12px/1.4 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; color:#d1d5db; background:#0b0c10; max-height:64vh; overflow:auto; white-space:pre-wrap }
/* Credits modal */
.creditsModal { position:fixed; inset:0; display:none; place-items:center; background:rgba(0,0,0,.55); backdrop-filter:blur(6px); padding:16px; z-index:60 }
.creditsPanel { width:min(560px, 94vw); background:#0b0c10; border:1px solid #2a2d3a; border-radius:12px; overflow:hidden; box-shadow:0 10px 30px rgba(0,0,0,.4) }
.creditsHead { display:flex; align-items:center; justify-content:space-between; padding:10px 12px; border-bottom:1px solid #1f2230; background:#0f1117 }
.creditsBody { padding:12px; color:var(--fg); font-size:14px }
/* Panic overlay */
.panicOverlay { position:fixed; inset:0; background:#000; z-index:9999; display:none }
/* Textareas default styling */
.creditsBody textarea { background:#0f1117; color:var(--fg); border:1px solid #2a2d3a }
/* Fix system prompt and memory inputs in light mode */
body.light #sysModal .creditsBody textarea,
body.light #memModal .creditsBody textarea { background:#fff; color:#111827; border-color:#e5e7eb }
body.light #sysModal .creditsBody textarea::placeholder,
body.light #memModal .creditsBody textarea::placeholder { color:#6b7280 }
/* Model menu dropdown */
.modelMenu { position:relative; display:inline-flex; align-items:center }
.modelMenuBtn { background:transparent; color:var(--fg); border:1px solid #333; border-radius:10px; padding:6px 10px; cursor:pointer; font-size:12px; display:flex; align-items:center; gap:4px }
.modelMenuBtn:hover { background:#1f2937; border-color:#444 }
body.light .modelMenuBtn { border-color:#e5e7eb }
body.light .modelMenuBtn:hover { background:#e5e7eb }
.modelMenuDropdown { position:absolute; bottom:100%; right:0; margin-bottom:8px; background:#0b0c10; border:1px solid #2a2d3a; border-radius:8px; min-width:160px; box-shadow:0 4px 12px rgba(0,0,0,.4); z-index:100; display:none; overflow:hidden }
.modelMenuDropdown.show { display:block }
body.light .modelMenuDropdown { background:#ffffff; border-color:#e5e7eb }
.modelMenuItem { display:block; width:100%; padding:10px 12px; color:var(--fg); text-align:left; border:none; background:transparent; cursor:pointer; font-size:13px; border-bottom:1px solid #1f2230 }
.modelMenuItem:last-child { border-bottom:none }
.modelMenuItem:hover { background:#1f2937 }
body.light .modelMenuItem { border-bottom-color:#e5e7eb }
body.light .modelMenuItem:hover { background:#f3f4f6 }
/* Model Selector */
.modelFilterBtn { background:#1b1f2b; color:var(--fg); border:1px solid #2a2d3a; padding:6px 12px; border-radius:8px; font-size:12px; cursor:pointer; transition:all 0.2s }
.modelFilterBtn:hover { background:#2a2d3a; border-color:var(--accent) }
.modelFilterBtn.active { background:var(--accent); border-color:var(--accent); color:#fff }
body.light .modelFilterBtn { background:#e5e7eb; border-color:#e5e7eb; color:#111827 }
body.light .modelFilterBtn:hover { background:#d1d5db }
body.light .modelFilterBtn.active { background:var(--accent); border-color:var(--accent); color:#fff }
.modelCard { background:#1b1f2b; border:2px solid #2a2d3a; border-radius:12px; padding:16px; display:flex; flex-direction:column; gap:10px; transition:all 0.2s; cursor:pointer; position:relative }
.modelCard:hover { border-color:var(--accent); transform:translateY(-2px); box-shadow:0 4px 12px rgba(0,0,0,0.3) }
.modelCard.selected { border-color:var(--accent); background:#1f2330; box-shadow:0 0 0 2px rgba(124,58,237,0.2) }
.modelCard.recommended::before { content:'⭐ Recommended'; position:absolute; top:8px; right:8px; background:var(--accent); color:#fff; padding:4px 8px; border-radius:6px; font-size:10px; font-weight:600 }
.modelCardHeader { display:flex; align-items:flex-start; justify-content:space-between; gap:8px }
.modelCardName { font-weight:600; font-size:15px; color:var(--fg); flex:1; line-height:1.3 }
.modelCardMeta { display:flex; flex-wrap:wrap; gap:6px; margin-top:4px }
.modelCardInfo { display:flex; flex-direction:column; gap:6px; margin-top:8px; font-size:12px; color:var(--mut) }
.modelCardInfoRow { display:flex; align-items:center; gap:8px }
.modelCardInfoIcon { width:16px; text-align:center }
.modelCardActions { display:flex; gap:8px; margin-top:8px }
.modelCardBtn { flex:1; padding:8px 12px; border-radius:8px; border:none; font-weight:600; font-size:13px; cursor:pointer; transition:all 0.2s }
.modelCardBtn.primary { background:var(--accent); color:#fff }
.modelCardBtn.primary:hover { opacity:0.9; transform:scale(1.02) }
.modelCardBtn.secondary { background:transparent; border:1px solid #2a2d3a; color:var(--fg) }
.modelCardBtn.secondary:hover { background:#2a2d3a; border-color:var(--accent) }
body.light .modelCard { background:#f3f4f6; border-color:#e5e7eb }
body.light .modelCard:hover { background:#ffffff; border-color:var(--accent) }
body.light .modelCard.selected { background:#ffffff; border-color:var(--accent) }
body.light .modelCardBtn.secondary { border-color:#e5e7eb; color:#111827 }
body.light .modelCardBtn.secondary:hover { background:#e5e7eb }
#modelSearch { transition:all 0.2s }
#modelSearch:focus { border-color:var(--accent); box-shadow:0 0 0 3px rgba(124,58,237,0.1) }
body.light #modelSearch { background:#fff; border-color:#e5e7eb; color:#111827 }
body.light #modelSearch:focus { border-color:var(--accent) }
.recommendedSection { margin-bottom:24px }
.recommendedSectionTitle { font-size:16px; font-weight:600; color:var(--fg); margin-bottom:12px; display:flex; align-items:center; gap:8px }
.recommendedSectionTitle::before { content:'⭐'; font-size:18px }
</style>
</head>
<body>
<div class="app">
<div class="header">
<div class="title">Local AI</div>
<div class="sub">Private, offline-friendly</div>
<div class="toolbar">
<button id="modelSelectorBtn" class="btn ghost" style="display:flex; align-items:center; gap:6px;">
<span id="currentModelName">Select Model</span>
<span style="font-size:10px;">▼</span>
</button>
<button id="loadModel" class="load">Load</button>
<span class="status" id="engineStatus">Engine: idle</span>
<span class="badge" id="gpuWarn" style="display:none">WebGPU not available</span>
<label class="switch" title="Simple Mode">
<input type="checkbox" id="simpleToggle" checked />
<span>Simple</span>
</label>
<div id="personalityWrap" style="display:flex; align-items:center; gap:6px;">
<label id="personalityLabel" style="font-size:12px; color:var(--mut); display:none;">Personality:</label>
<select id="promptMode" class="nice" title="Change AI personality">
<option value="genius" selected>Genius</option>
<option value="default">Default</option>
<option value="teacher">Teacher</option>
<option value="creative">Creative</option>
<option value="analyst">Analyst</option>
<option value="storyteller">Storyteller</option>
<option value="coach">Coach</option>
<option value="scientist">Scientist</option>
<option value="poet">Poet</option>
<option value="critic">Critic</option>
<option value="mentor">Mentor</option>
<option value="explorer">Explorer</option>
<option value="optimist">Optimist</option>
<option value="realist">Realist</option>
<option value="philosopher">Philosopher</option>
<option value="translator">Translator</option>
<option value="summarizer">Summarizer</option>
<option value="rewriter">Rewriter</option>
<option value="programmer">Programmer</option>
<option value="buddy">Buddy</option>
</select>
</div>
<button id="systemBtn" class="btn ghost">System</button>
<button id="memoryBtn" class="btn ghost">Memory</button>
<button id="creditsBtn" class="btn ghost">Credits</button>
<button id="themeToggle" class="btn ghost">Theme: Dark</button>
<input id="accentPicker" type="color" value="#7c3aed" title="Accent color" class="badge accentPreview" style="height:28px;width:36px;padding:0;border-radius:8px" />
<select id="langSel" class="nice"><option value="en">EN</option></select>
</div>
<div class="progress" id="progressWrap">
<div class="progressTrack"><div class="progressBar" id="progressBar"></div></div>
<div class="progressText" id="progressText">0%</div>
</div>
</div>
<div id="msgs" class="messages"></div>
<div class="inputbar">
<div class="row">
<textarea id="in" rows="1" placeholder="Type a message..."></textarea>
<button id="send" class="btn">Send</button>
<button id="clear" class="btn muted">Clear</button>
</div>
<div class="ctrls">
<label class="badge">Temp <input id="temp" class="range" type="range" min="0.1" max="2.0" step="0.05" value="1" /></label>
<button id="queue" class="btn ghost">Queue</button>
<button id="stop" class="btn ghost">Stop</button>
<span id="tokStats" class="badge">Tokens: <span id="tokCount">0</span> • TPS: <span id="tpsAvg">0</span></span>
<div class="modelMenu">
<button id="modelMenuBtn" class="modelMenuBtn" title="Model import/export">
<span>☰</span>
</button>
<div id="modelMenuDropdown" class="modelMenuDropdown">
<button class="modelMenuItem" id="quickExportBtn">Export Model</button>
<button class="modelMenuItem" id="quickImportBtn">Import Model</button>
</div>
</div>
<input type="file" id="quickImportModelFile" accept=".zip" style="display:none" />
</div>
</div>
</div>
<!-- Logs/Downloads Modal -->
<div id="logModal" class="logModal">
<div class="logPanel">
<div class="logHead">
<div class="logTitle">Downloads & Logs</div>
<div class="logBtns">
<button id="closeLogs" class="btn ghost">Close</button>
<button id="clearLogs" class="btn ghost">Clear Logs</button>
</div>
</div>
<div class="panelBody">
<div class="tabs">
<button id="tabDownloads" class="tab active">Downloads</button>
<button id="tabLogs" class="tab">Logs</button>
</div>
<div id="downloadsBody">
<div id="downloadsList">
<div class="downloadsSection">
<div class="downloadsSectionTitle">Available Models</div>
<div id="availableModelsGrid" class="downloadsGrid"></div>
</div>
<div class="downloadsSection">
<div class="downloadsSectionTitle">Downloaded Models</div>
<div id="downloadedModelsGrid" class="downloadsGrid"></div>
</div>
</div>
<div class="mgrBtns">
<button id="refreshDownloads" class="btn ghost">🔄 Refresh</button>
<button id="clearAllCaches" class="btn ghost">🗑️ Clear Caches</button>
<button id="clearDownloadsTrack" class="btn ghost">Clear Track</button>
<button id="exportModelBtn" class="btn">📦 Export Model</button>
<button id="importModelBtn" class="btn">📥 Import Model</button>
<input type="file" id="importModelFile" accept=".zip" style="display:none" />
</div>
</div>
<div id="logsBody">
<pre id="logBody"></pre>
</div>
</div>
</div>
</div>
<!-- System Prompt Modal -->
<div id="sysModal" class="creditsModal">
<div class="creditsPanel">
<div class="creditsHead"><div>Edit System Prompt</div><button id="closeSys" class="btn ghost">Close</button></div>
<div class="creditsBody">
<textarea id="sysInput" rows="10" placeholder="Enter a custom system prompt..." style="width:100%; resize:vertical; padding:10px; border-radius:10px;"></textarea>
<div class="mgrBtns" style="justify-content:flex-end"><button id="saveSys" class="btn">Save</button></div>
</div>
</div>
</div>
<!-- Memory Modal -->
<div id="memModal" class="creditsModal">
<div class="creditsPanel">
<div class="creditsHead"><div>Buddy Memory</div><button id="closeMem" class="btn ghost">Close</button></div>
<div class="creditsBody">
<label style="display:flex; gap:8px; align-items:center; margin-bottom:8px;"><input type="checkbox" id="memInPrompt" /> <span class="badge">Use memory in system prompt</span></label>
<textarea id="memInput" rows="10" placeholder="{}" style="width:100%; resize:vertical; padding:10px; border-radius:10px; font-family:ui-monospace;"></textarea>
<div class="mgrBtns" style="justify-content:flex-end"><button id="saveMem" class="btn">Save</button></div>
</div>
</div>
</div>
<!-- Model Selector Modal -->
<div id="modelSelectorModal" class="creditsModal">
<div class="creditsPanel" style="width:min(900px, 96vw); max-height:85vh;">
<div class="creditsHead">
<div>Select AI Model</div>
<button id="closeModelSelector" class="btn ghost">Close</button>
</div>
<div class="creditsBody" style="padding:0; display:flex; flex-direction:column; max-height:75vh;">
<div style="padding:16px; border-bottom:1px solid #1f2230; background:#0f1117;">
<input type="text" id="modelSearch" placeholder="🔍 Search models..." style="width:100%; padding:10px; border-radius:8px; border:1px solid #2a2d3a; background:#0b0c10; color:var(--fg); font-size:14px; outline:none;" />
<div style="display:flex; gap:8px; margin-top:12px; flex-wrap:wrap;">
<button class="modelFilterBtn active" data-filter="all">All</button>
<button class="modelFilterBtn" data-filter="small">Small (Fast)</button>
<button class="modelFilterBtn" data-filter="medium">Medium</button>
<button class="modelFilterBtn" data-filter="large">Large (Quality)</button>
<button class="modelFilterBtn" data-filter="cached">Cached</button>
<button class="modelFilterBtn" data-filter="recommended">Recommended</button>
</div>
</div>
<div id="modelSelectorContent" style="flex:1; overflow:auto; padding:16px;">
<div id="recommendedModels" style="margin-bottom:24px;"></div>
<div id="allModelsGrid" class="downloadsGrid"></div>
</div>
</div>
</div>
</div>
<!-- Credits Modal -->
<div id="creditsModal" class="creditsModal">
<div class="creditsPanel">
<div class="creditsHead"><div>Credits</div><button id="closeCredits" class="btn ghost">Close</button></div>
<div class="creditsBody">
<p>Not going to say it, but made by h3 🤫. keep secrets secret, do not cheat. You only live once.</p>
</div>
</div>
</div>
<!-- Panic overlay for quick screen blackout -->
<div id="panicOverlay" class="panicOverlay" aria-hidden="true" title="Panic screen. Press Esc or click to exit."></div>
<!-- JSZip for model import/export -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<!-- Main app (module) -->
<script type="module">
import * as webllm from "https://esm.run/@mlc-ai/web-llm";
// --- UI helpers ---
const $ = (s) => document.querySelector(s);
const msgs = $('#msgs');
const input = $('#in');
const sendBtn = $('#send');
const tempEl = $('#temp');
const clearBtn = $('#clear');
const modelSel = $('#modelSel'); // Keep for compatibility
const loadBtn = $('#loadModel');
const modelSelectorBtn = $('#modelSelectorBtn');
const modelSelectorModal = $('#modelSelectorModal');
const closeModelSelector = $('#closeModelSelector');
const modelSearch = $('#modelSearch');
const currentModelName = $('#currentModelName');
const allModelsGrid = $('#allModelsGrid');
const recommendedModels = $('#recommendedModels');
let currentSelectedModel = null;
let allModelsList = [];
const statusEl = $('#engineStatus');
const gpuWarn = $('#gpuWarn');
const progressWrap = $('#progressWrap');
const progressBar = $('#progressBar');
const progressText = $('#progressText');
const logModal = $('#logModal');
const logBody = $('#logBody');
const closeLogs = $('#closeLogs');
const clearLogs = $('#clearLogs');
const tabDownloads = $('#tabDownloads');
const tabLogs = $('#tabLogs');
const downloadsBody = $('#downloadsBody');
const logsBody = $('#logsBody');
const downloadsList = $('#downloadsList');
const availableModelsGrid = $('#availableModelsGrid');
const downloadedModelsGrid = $('#downloadedModelsGrid');
const refreshDownloads = $('#refreshDownloads');
const clearAllCaches = $('#clearAllCaches');
const clearDownloadsTrack = $('#clearDownloadsTrack');
const simpleToggle = $('#simpleToggle');
const promptMode = $('#promptMode');
const themeToggle = $('#themeToggle');
const accentPicker = $('#accentPicker');
const langSel = $('#langSel');
const inputbar = document.querySelector('.inputbar');
const creditsBtn = $('#creditsBtn');
const creditsModal = $('#creditsModal');
const closeCredits = $('#closeCredits');
const systemBtn = $('#systemBtn');
const sysModal = $('#sysModal');
const sysInput = $('#sysInput');
const saveSys = $('#saveSys');
const closeSys = $('#closeSys');
const memoryBtn = $('#memoryBtn');
const memModal = $('#memModal');
const memInput = $('#memInput');
const saveMem = $('#saveMem');
const closeMem = $('#closeMem');
const memInPromptEl = $('#memInPrompt');
const queueBtn = $('#queue');
const stopBtn = $('#stop');
const tokCountEl = $('#tokCount');
const tpsAvgEl = $('#tpsAvg');
const panicOverlay = $('#panicOverlay');
// Persist chat and settings
const LS_CHAT = 'localai_chat_html_v2';
const LS_MODEL = 'localai_model_id';
const LS_DOWNLOADED = 'localai_downloaded_models';
const LS_SETTINGS = 'localai_settings';
const LS_SYSTEM = 'localai_system_prompt';
const LS_MEMORY = 'localai_buddy_memory';
const LS_CUSTOM_MODES = 'localai_custom_modes';
const LS_MEMORY_IN_PROMPT = 'localai_memory_in_prompt';
const LS_SIMPLE = 'localai_simple_mode';
let busy = false;
let stopRequested = false;
let requestQueue = [];
let history = [ { role: 'system', content: 'You are a concise, helpful AI assistant.' } ];
let buddyMemory = null;
let engine = null;
let lastChosenModel = localStorage.getItem(LS_MODEL) || '';
let activeRequestTimeout = null;
let requestStartTime = null;
const REQUEST_TIMEOUT_MS = 120000; // 2 minutes timeout
const STUCK_REQUEST_MS = 30000; // 30 seconds to detect stuck requests
// Logging
const logs = [];
function ts() { const d = new Date(); return d.toLocaleTimeString(); }
function log(msg) {
const line = `[${ts()}] ${msg}`;
logs.push(line);
if (logs.length > 2000) logs.shift();
if (logModal.style.display !== 'none') renderLogs();
}
function renderLogs(){ logBody.textContent = logs.join('\n'); logBody.scrollTop = logBody.scrollHeight; }
function toggleLogs(force) { const show = force ?? (logModal.style.display === 'none'); logModal.style.display = show ? 'grid' : 'none'; if (show) { setActiveTab(activeTab); renderLogs(); renderAvailableModels(); renderDownloads(); } }
let activeTab = 'downloads';
function setActiveTab(name){ activeTab = name; if(name==='downloads'){ tabDownloads.classList.add('active'); tabLogs.classList.remove('active'); downloadsBody.style.display='block'; logsBody.style.display='none'; } else { tabLogs.classList.add('active'); tabDownloads.classList.remove('active'); downloadsBody.style.display='none'; logsBody.style.display='block'; } }
function saveChat() {
localStorage.setItem(LS_CHAT, JSON.stringify({ html: msgs.innerHTML, history, model: modelSel.value }));
}
function loadChat() {
try {
const raw = localStorage.getItem(LS_CHAT);
if (!raw) return;
const obj = JSON.parse(raw);
if (obj?.html) msgs.innerHTML = obj.html;
if (Array.isArray(obj?.history)) history = obj.history;
if (obj?.model) lastChosenModel = obj.model;
msgs.scrollTop = msgs.scrollHeight;
} catch {}
}
function add(role, text="") {
const d = document.createElement('div');
d.className = 'msg ' + (role === 'user' ? 'user' : 'bot');
d.textContent = text;
msgs.appendChild(d);
msgs.scrollTop = msgs.scrollHeight;
saveChat();
return d;
}
function addBotRich(text, preview){
const d = document.createElement('div');
d.className = 'msg bot';
const p = document.createElement('div'); p.textContent = text; d.appendChild(p);
if (preview) d.appendChild(preview);
msgs.appendChild(d);
msgs.scrollTop = msgs.scrollHeight;
saveChat();
return d;
}
function setStatus(t) { statusEl.textContent = 'Engine: ' + t; }
// --- Tiny fallback (Markov + small helpers) ---
function pick(a){ return a[Math.floor(Math.random()*a.length)] }
function tokenize(t){ return t.toLowerCase().replace(/[^a-z0-9\.\?\!'\-\s]/g,' ').split(/\s+/).filter(Boolean) }
function markovBuild(text,n=3){ const toks=tokenize(text),map=new Map(); for(let i=0;i<=toks.length-n;i++){ const key=toks.slice(i,i+n-1).join(' '),next=toks[i+n-1]; if(!map.has(key)) map.set(key,{}); map.get(key)[next]=(map.get(key)[next]||0)+1 } return map }
function markovGen(map,seedWords,max=80,temperature=1){ const keys=[...map.keys()]; let seed=null; if(seedWords){ const s=tokenize(seedWords); for(let i=s.length;i>=2;i--){ const k=s.slice(i-2,i).join(' '); if(map.has(k)){ seed=k; break } } } if(!seed) seed=pick(keys); let parts=seed.split(' '),out=[...parts]; for(let i=0;i<max;i++){ const key=out.slice(out.length-2).join(' '),dist=map.get(key)||map.get(pick(keys)); const opts=Object.entries(dist); let tot=0; const arr=opts.map(([w,c])=>{ const val=Math.pow(c,1/Math.max(.05,temperature)); tot+=val; return [w,val] }); let r=Math.random()*tot; let next=''; for(const [w,v] of arr){ if((r-=v)<=0){ next=w; break } } out.push(next); if(/[.!?]/.test(next.slice(-1))&&out.length>8) break } let s=out.join(' '); s=s.replace(/\s([,.!?])/g,'$1'); s=s.replace(/\bi\b/g,'I'); s=s.replace(/(^|\.\s|!\s|\?\s)([a-z])/g,(m,p1,p2)=>p1+p2.toUpperCase()); return s }
function calcExpr(s){ if(!/^[\d\.\+\-\*\/\^\(\)\s]+$/.test(s))return null; const ops={'+':1,'-':1,'*':2,'/':2,'^':3},stack=[],out=[]; const toks=s.match(/(\d+\.?\d*|\.\d+|[+\-*\/\^\(\)])/g); if(!toks)return null; for(const t of toks){ if(!isNaN(t))out.push(parseFloat(t)); else if(t in ops){ while(stack.length){ const o=stack[stack.length-1]; if(o in ops&&(ops[o]>ops[t]||(ops[o]==ops[t]&&t!=='^')))out.push(stack.pop()); else break } stack.push(t) } else if(t==='(')stack.push(t); else if(t===')'){ while(stack.length&&stack[stack.length-1]!=='(')out.push(stack.pop()); if(stack.pop()!=='(')return null } } while(stack.length){ const o=stack.pop(); if(!(o in ops))return null; out.push(o) } const st=[]; for(const t of out){ if(typeof t==='number')st.push(t); else{ const b=st.pop(),a=st.pop(); if(a==null||b==null)return null; st.push(t==='+'?a+b:t==='-'?a-b:t==='*'?a*b:t==='/'?a/b:Math.pow(a,b)) } } return st.pop() }
const fallbackSeed = "Hello! I'm a tiny local AI that runs in your browser. I can answer simple questions, do small math, and generate text using a tiny Markov model. Privacy-friendly and offline by design.";
const fallbackModel = markovBuild(fallbackSeed);
function quickIntent(u){ const t=u.toLowerCase(); if(/\b(hi|hello|hey)\b/.test(t)) return "Hi! I'm your local offline AI. How can I help?"; if(/\b(time|what.*time)\b/.test(t)) return "The current time is "+new Date().toLocaleTimeString()+"."; if(/\b(date|day|today)\b/.test(t)) return "Today is "+new Date().toLocaleDateString()+"."; const m=t.match(/(?:calc(?:ulate)?|what(?:'s| is))\s+([0-9\.\+\-\*\/\^\(\)\s]+)/); if(m){ const v=calcExpr(m[1]); if(v!=null) return "Result: "+v } const only=t.match(/^[\s\(]*[0-9\.\+\-\*\/\^\(\)\s]+[\s\)]*$/); if(only){ const v=calcExpr(t); if(v!=null) return "Result: "+v } return null }
// --- Added helpers to prevent ReferenceError and enable features ---
function updateSystemPrompt(){
try {
const savedCustom = (localStorage.getItem(LS_SYSTEM)||'').trim();
const mode = (promptMode && promptMode.value) || '';
const base = 'You are a concise, helpful AI assistant. You may emit internal tool instructions like [tool:settings]{"theme":"light"} or [tool:preview]{"language":"html","code":"..."}, but these must NEVER be shown directly to the user. Silently parse and act on them, then remove any [tool:*]{...} blocks from the visible reply.';
let addon = '';
if (mode === 'genius') addon = ' Explain deeply, step-by-step, and cover edge cases.';
else if (mode === 'teacher') addon = ' Act as an educational instructor. Break down complex topics into simple, understandable parts. Use examples and analogies to help the user learn.';
else if (mode === 'creative') addon = ' Be imaginative and artistic. Think outside the box, suggest creative solutions, and inspire with original ideas.';
else if (mode === 'analyst') addon = ' Focus on data, facts, and logical analysis. Present information systematically with clear reasoning and evidence-based conclusions.';
else if (mode === 'storyteller') addon = ' Craft engaging narratives. Use vivid descriptions, build context, and make responses compelling and story-like when appropriate.';
else if (mode === 'coach') addon = ' Be motivational and goal-oriented. Encourage the user, help them set objectives, and provide actionable steps toward success.';
else if (mode === 'scientist') addon = ' Approach topics methodically and scientifically. Use precise terminology, cite methodologies, and maintain objectivity.';
else if (mode === 'poet') addon = ' Use lyrical and expressive language. Employ metaphors, rhythm, and beautiful phrasing to convey ideas artistically.';
else if (mode === 'critic') addon = ' Provide detailed evaluations and constructive feedback. Analyze strengths and weaknesses with thoughtful, balanced perspectives.';
else if (mode === 'mentor') addon = ' Offer guidance and wisdom. Share insights from experience, help navigate challenges, and support long-term growth.';
else if (mode === 'explorer') addon = ' Be curious and adventurous. Ask probing questions, explore different angles, and discover new possibilities together.';
else if (mode === 'optimist') addon = ' Maintain a positive, encouraging tone. Focus on opportunities, solutions, and the bright side of situations.';
else if (mode === 'realist') addon = ' Be practical and straightforward. Give honest, no-nonsense advice grounded in reality, without sugarcoating.';
else if (mode === 'philosopher') addon = ' Engage in deep thinking and abstract concepts. Explore fundamental questions, ethics, and the nature of things.';
else if (mode === 'translator') addon = ' Focus on language and communication. Help bridge understanding across languages, cultures, and contexts.';
else if (mode === 'summarizer') addon = ' Be concise and to-the-point. Extract key information, eliminate fluff, and deliver clear summaries.';
else if (mode === 'rewriter') addon = ' Rewrite user text to be logically correct, spell-checked, and grammatically sound while preserving intent.';
else if (mode === 'programmer') addon = ' Generate clean, minimal HTML/CSS/JS. Use a single code block with fences.';
else if (mode === 'buddy') addon = ' Act as a warm, supportive friend. Use short, caring messages and remember helpful details.';
else {
try { const list = JSON.parse(localStorage.getItem(LS_CUSTOM_MODES)||'[]'); const found = list.find(x=>x && x.name===mode); if(found && found.addon) addon = ' ' + found.addon; } catch {}
}
// Compose base or use custom
let sys = savedCustom ? savedCustom : (base + addon);
// Optionally inject memory context
const useMem = localStorage.getItem(LS_MEMORY_IN_PROMPT) === '1';
if (useMem){
try{
const m = buddyMemory || loadMemory();
const notes = (m?.notes||[]).slice(-5).map(n=>String(n.text||''));
const kv = m?.kv || {};
const memStr = `\nMemory Context (for assistant only; do not reveal directly): notes=${JSON.stringify(notes)} kv=${JSON.stringify(kv)}.`;
sys += memStr;
} catch {}
}
history[0] = { role: 'system', content: sys };
} catch(e) { log('updateSystemPrompt error: ' + (e?.message||e)); }
}
function codePreviewFromBlocks(text){
try {
const m = text.match(/```(html|javascript|js|css)\n([\s\S]*?)```/i);
if (!m) return null;
const lang = m[1].toLowerCase();
const code = m[2];
const iframe = document.createElement('iframe');
iframe.style.width='100%'; iframe.style.height='260px'; iframe.style.border='1px solid #1f2230'; iframe.style.borderRadius='10px';
iframe.setAttribute('sandbox','allow-scripts');
let srcdoc='';
if (lang==='html') srcdoc = code;
else if (lang==='css') srcdoc = `<style>${code}</style><div style="padding:12px;font-family:system-ui">CSS Preview</div>`;
else srcdoc = `<!doctype html><meta charset="utf-8"><style>body{font-family:system-ui;padding:12px}</style><div>JS Preview</div><script>${code}<\/script>`;
iframe.srcdoc = srcdoc;
return iframe;
} catch(e){ log('codePreview error: ' + (e?.message||e)); return null; }
}
function sanitizeToolCalls(text){
try{ return String(text||'').replace(/\[tool:[^\]]+\]\s*\{[\s\S]*?\}/g, '').replace(/\n{3,}/g,'\n\n').trim(); }catch{ return String(text||''); }
}
function applyToolBlocks(text){
try {
const re = /\[tool:(\w+)\]\s*\{([\s\S]*?)\}/g; let m;
while ((m = re.exec(text))){
const tool = m[1].toLowerCase();
const jsonStr = '{' + m[2] + '}';
let data = {};
try { data = JSON.parse(jsonStr); } catch(e){ log('Tool JSON parse error'); continue; }
if (tool === 'settings'){
if (data.theme){ document.body.classList.toggle('light', (''+data.theme).toLowerCase().includes('light')); }
if (data.accent){ document.documentElement.style.setProperty('--accent', data.accent); }
if (data.language){ /* placeholder: could localize */ }
} else if (tool === 'preview'){
const lang = (''+(data.language||'html')).toLowerCase();
const code = ''+(data.code||'');
const fake = `\n\`\`\`${lang}\n${code}\n\`\`\`\n`;
const ifr = codePreviewFromBlocks(fake);
if (ifr) addBotRich('Preview:', ifr);
} else if (tool === 'memory'){
const action = (''+(data.action||'')).toLowerCase();
if (action === 'append' && data.text){
try{ const count = memoryAppend(String(data.text)); const d = document.createElement('div'); d.textContent = 'Appended note to memory ('+count+' total).'; addBotRich('Memory Updated', d); }catch(e){ log('memory append error: '+(e?.message||e)); }
} else if (action === 'set' && 'key' in data){
try{ const val = ('value' in data) ? data.value : null; memorySet(String(data.key), val); const pre=document.createElement('pre'); pre.textContent = JSON.stringify({[String(data.key)]: val}, null, 2); addBotRich('Memory Set', pre); }catch(e){ log('memory set error: '+(e?.message||e)); }
} else if (action === 'get' && 'key' in data){
try{ const val = memoryGet(String(data.key)); const pre=document.createElement('pre'); pre.textContent = JSON.stringify(val, null, 2); addBotRich('Memory Read: '+String(data.key), pre); }catch(e){ log('memory get error: '+(e?.message||e)); }
} else if (action === 'clear'){
try{ memoryClear(); const d=document.createElement('div'); d.textContent='All memory cleared.'; addBotRich('Memory Cleared', d); }catch(e){ log('memory clear error: '+(e?.message||e)); }
}
} else if (tool === 'mode'){
const name = (data.name||'').toString().trim().toLowerCase();
const addon = (data.addon||'').toString();
if (name){
try{
ensureModeOption(name, addon);
if (promptMode) promptMode.value = name;
// persist addon
try {
const arr = JSON.parse(localStorage.getItem(LS_CUSTOM_MODES)||'[]');
const i = arr.findIndex(x=>x && x.name===name);
if (addon){ if (i>=0) arr[i].addon = addon; else arr.push({name, addon}); localStorage.setItem(LS_CUSTOM_MODES, JSON.stringify(arr)); }
} catch {}
updateSystemPrompt();
const d = document.createElement('div'); d.textContent = 'Switched to mode: '+name; addBotRich('Mode', d);
}catch(e){ log('mode tool error: '+(e?.message||e)); }
}
}
}
} catch(e){ log('applyToolBlocks error: ' + (e?.message||e)); }
}
// --- WebLLM Engine ---
function showProgress(show){ if (progressWrap) progressWrap.style.display = show ? 'flex' : 'none'; }
function setProgress(pct, text){ if(progressBar){ progressBar.style.width = Math.max(0, Math.min(100, pct)) + '%'; } if(progressText){ progressText.textContent = Math.round(Math.max(0, Math.min(100, pct))) + '%'; } if (text && statusEl) statusEl.textContent = 'Engine: ' + text; }
function getModelRecommendations(list) {
const downloaded = getDownloadedSet();
const recommendations = [];
// Recommend small cached models first
const smallCached = list.filter(m => {
const id = (m.model_id || '').toLowerCase();
return downloaded.has(m.model_id) && /0\.5b|1\.5b|1b|tiny|mini|small/i.test(id);
});
if (smallCached.length > 0) {
recommendations.push(...smallCached.slice(0, 2));
}
// Recommend small uncached models
const smallUncached = list.filter(m => {
const id = (m.model_id || '').toLowerCase();
return !downloaded.has(m.model_id) && /0\.5b|1\.5b|1b|tiny|mini|small/i.test(id);
});
if (smallUncached.length > 0 && recommendations.length < 3) {
recommendations.push(...smallUncached.slice(0, 3 - recommendations.length));
}
return recommendations.slice(0, 3);
}
function createSmartModelCard(modelId, isRecommended = false) {
const card = document.createElement('div');
const sizeInfo = getModelSize(modelId);
const downloaded = getDownloadedSet().has(modelId);
const isSelected = currentSelectedModel === modelId;
card.className = `modelCard ${isRecommended ? 'recommended' : ''} ${isSelected ? 'selected' : ''}`;
const header = document.createElement('div');
header.className = 'modelCardHeader';
const name = document.createElement('div');
name.className = 'modelCardName';
name.textContent = modelId;
name.title = modelId;
header.appendChild(name);
const meta = document.createElement('div');
meta.className = 'modelCardMeta';
if (downloaded) {
const cachedBadge = document.createElement('span');
cachedBadge.className = 'modelBadge cached';
cachedBadge.textContent = '✓ Cached';
meta.appendChild(cachedBadge);
}
const sizeBadge = document.createElement('span');
sizeBadge.className = `modelBadge ${sizeInfo.class}`;
sizeBadge.textContent = sizeInfo.size;
meta.appendChild(sizeBadge);
const info = document.createElement('div');
info.className = 'modelCardInfo';
// Speed indicator
const speedRow = document.createElement('div');
speedRow.className = 'modelCardInfoRow';
speedRow.innerHTML = `<span class="modelCardInfoIcon">⚡</span><span>${sizeInfo.class === 'small' ? 'Very Fast' : sizeInfo.class === 'medium' ? 'Fast' : 'Slower'}</span>`;
info.appendChild(speedRow);
// Quality indicator
const qualityRow = document.createElement('div');
qualityRow.className = 'modelCardInfoRow';
qualityRow.innerHTML = `<span class="modelCardInfoIcon">🎯</span><span>${sizeInfo.class === 'small' ? 'Good' : sizeInfo.class === 'medium' ? 'Better' : 'Best'}</span>`;
info.appendChild(qualityRow);
// Memory indicator
const memoryRow = document.createElement('div');
memoryRow.className = 'modelCardInfoRow';
const memText = sizeInfo.class === 'small' ? '<2GB' : sizeInfo.class === 'medium' ? '2-4GB' : '4GB+';
memoryRow.innerHTML = `<span class="modelCardInfoIcon">💾</span><span>${memText}</span>`;
info.appendChild(memoryRow);
const actions = document.createElement('div');
actions.className = 'modelCardActions';
const loadBtn = document.createElement('button');
loadBtn.className = 'modelCardBtn primary';
loadBtn.textContent = downloaded ? 'Load' : 'Download & Load';
loadBtn.onclick = (e) => {
e.stopPropagation();
currentSelectedModel = modelId;
if (modelSel) modelSel.value = modelId;
if (currentModelName) {
const shortName = modelId.length > 25 ? modelId.substring(0, 22) + '...' : modelId;
currentModelName.textContent = shortName;
currentModelName.title = modelId;
}
renderModelSelector();
loadSelectedModel();
if (modelSelectorModal) modelSelectorModal.style.display = 'none';
};
const selectBtn = document.createElement('button');
selectBtn.className = 'modelCardBtn secondary';
selectBtn.textContent = isSelected ? 'Selected' : 'Select';
selectBtn.onclick = (e) => {
e.stopPropagation();
currentSelectedModel = modelId;
if (modelSel) modelSel.value = modelId;
if (currentModelName) {
const shortName = modelId.length > 25 ? modelId.substring(0, 22) + '...' : modelId;
currentModelName.textContent = shortName;
currentModelName.title = modelId;
}
renderModelSelector();
};
actions.appendChild(loadBtn);
actions.appendChild(selectBtn);
card.onclick = () => {
currentSelectedModel = modelId;
if (modelSel) modelSel.value = modelId;
if (currentModelName) {
const shortName = modelId.length > 25 ? modelId.substring(0, 22) + '...' : modelId;
currentModelName.textContent = shortName;
currentModelName.title = modelId;
}
renderModelSelector();
};
card.appendChild(header);
card.appendChild(meta);
card.appendChild(info);
card.appendChild(actions);
return card;
}
function renderModelSelector() {
if (!allModelsGrid) return;
try {
const list = allModelsList.length > 0 ? allModelsList : (webllm?.prebuiltAppConfig?.model_list) || [];
if (list.length === 0) {
allModelsGrid.innerHTML = '<div class="emptyState"><div class="emptyStateIcon">📦</div><div>Loading models...</div></div>';
return;
}
const searchTerm = (modelSearch?.value || '').toLowerCase();
const activeFilter = document.querySelector('.modelFilterBtn.active')?.dataset?.filter || 'all';
const downloaded = getDownloadedSet();
// Filter models
let filtered = list.filter(m => {
const id = (m.model_id || '').toLowerCase();
if (searchTerm && !id.includes(searchTerm)) return false;
if (activeFilter === 'cached') return downloaded.has(m.model_id);
if (activeFilter === 'recommended') {
const recs = getModelRecommendations(list);
return recs.some(r => r.model_id === m.model_id);
}
if (activeFilter === 'small') {
return /0\.5b|1\.5b|1b|tiny|mini|small/i.test(id);
}
if (activeFilter === 'medium') {
return /2b|3b/i.test(id);
}
if (activeFilter === 'large') {
return /7b|8b|13b|14b/i.test(id);
}
return true;
});
// Sort: recommended first, then cached, then by size
filtered.sort((a, b) => {
const recs = getModelRecommendations(list);
const aRec = recs.some(r => r.model_id === a.model_id);
const bRec = recs.some(r => r.model_id === b.model_id);
if (aRec && !bRec) return -1;
if (!aRec && bRec) return 1;
const aCached = downloaded.has(a.model_id);
const bCached = downloaded.has(b.model_id);
if (aCached && !bCached) return -1;
if (!aCached && bCached) return 1;
const aSize = getModelSize(a.model_id);
const bSize = getModelSize(b.model_id);
const sizeOrder = { small: 0, medium: 1, large: 2 };
return (sizeOrder[aSize.class] || 1) - (sizeOrder[bSize.class] || 1);
});
allModelsGrid.innerHTML = '';
if (filtered.length === 0) {
allModelsGrid.innerHTML = '<div class="emptyState"><div class="emptyStateIcon">🔍</div><div>No models found</div></div>';
return;
}
filtered.forEach(rec => {
const recs = getModelRecommendations(list);
const isRecommended = recs.some(r => r.model_id === rec.model_id);
const card = createSmartModelCard(rec.model_id, isRecommended);
allModelsGrid.appendChild(card);
});
// Render recommended section if showing all
if (activeFilter === 'all' || activeFilter === 'recommended') {
const recs = getModelRecommendations(list);
if (recs.length > 0 && !searchTerm) {
recommendedModels.innerHTML = '<div class="recommendedSection"><div class="recommendedSectionTitle">Recommended for You</div><div class="downloadsGrid" id="recommendedGrid"></div></div>';
const recGrid = $('#recommendedGrid');
if (recGrid) {
recs.forEach(r => {
const card = createSmartModelCard(r.model_id, true);
recGrid.appendChild(card);
});
}
} else {
recommendedModels.innerHTML = '';
}
} else {
recommendedModels.innerHTML = '';
}
} catch(e) {
log('renderModelSelector error: ' + (e?.message||e));
}
}
async function populateModels() {
try {
const list = (webllm?.prebuiltAppConfig?.model_list) || [];
allModelsList = list;
modelSel.innerHTML = '';
const isSimple = (simpleToggle ? simpleToggle.checked : (localStorage.getItem(LS_SIMPLE) === '1'));
// In Simple mode, show only tiny/small models to reduce noise
const filtered = isSimple ? list.filter(rec => /0\.5b|1\.5b|tiny|mini|small/i.test((rec?.model_id||'')+'')) : list;
const sorted = [...filtered].sort((a,b)=>{
const wa = (a.model_id||'').toLowerCase();
const wb = (b.model_id||'').toLowerCase();
const ra = wa.includes('0.5b') ? 0 : wa.includes('1.5b') ? 1 : 2;
const rb = wb.includes('0.5b') ? 0 : wb.includes('1.5b') ? 1 : 2;
return ra - rb;
});
const maxItems = isSimple ? 10 : 40;
for (const rec of sorted.slice(0, maxItems)){
const opt = document.createElement('option');
opt.value = rec.model_id; opt.textContent = rec.model_id;
modelSel.appendChild(opt);
}
let def = [...modelSel.options].find(o=>/qwen.*0\.5b/i.test(o.value))?.value || modelSel.options[0]?.value;
if (lastChosenModel && [...modelSel.options].some(o=>o.value===lastChosenModel)) def = lastChosenModel;
if (def) {
modelSel.value = def;
currentSelectedModel = def;
if (currentModelName) {
const shortName = def.length > 25 ? def.substring(0, 22) + '...' : def;
currentModelName.textContent = shortName;
currentModelName.title = def;
}
}
renderModelSelector();
log(`Models loaded (${filtered.length} shown of ${list.length} total). Default: ${modelSel.value}`);
} catch(e){ log('Populate models failed: ' + (e?.message||e)); }
}
async function loadSelectedModel(){
const id = modelSel?.value;
if (!id) return;
// If offline, skip trying to fetch remote model shards and fall back gracefully
if (typeof navigator !== 'undefined' && navigator && navigator.onLine === false){
setStatus('offline');
showProgress(false);
add('bot', 'You appear to be offline. I will use the tiny local fallback instead.');
log('Offline detected: skipping WebLLM model load');
saveChat();
return;
}
setStatus('preparing');
showProgress(true);
setProgress(0, 'preparing');
log('Loading model: ' + id);
try {
engine = await webllm.CreateMLCEngine(id, {
initProgressCallback: (p)=>{
try{
const frac = typeof p?.progress === 'number' ? p.progress : (typeof p === 'number' ? p : 0);
const pct = Math.round(frac * 100);
const stage = (p && (p.text || p.stage || p.status)) ? (p.text || p.stage || p.status) : 'loading';
setProgress(pct, `${stage} ${pct}%`);
log(`Progress: ${pct}% - ${stage}`);
}catch{ setProgress(0, 'loading'); }
}
});
setStatus('ready (' + id + ')');
showProgress(false);
localStorage.setItem(LS_MODEL, id);
lastChosenModel = id;
currentSelectedModel = id;
if (currentModelName) {
const shortName = id.length > 25 ? id.substring(0, 22) + '...' : id;
currentModelName.textContent = shortName;
currentModelName.title = id;
}
markDownloaded(id);
renderAvailableModels();
renderDownloads();
updateModelBadges();
renderModelSelector();
log('Model ready: ' + id);
} catch(e){
// Avoid noisy stack traces in console; provide friendly fallback
// console.error(e);
setStatus('failed to load');
showProgress(false);
add('bot', 'Model failed to load (likely network/cache). Using tiny local fallback instead.');
log('Model failed to load: ' + (e?.message||e));
}
saveChat();
}
async function ensureEngine(){
// Better Chrome WebGPU detection
if (!('gpu' in navigator)) {
// Try to request adapter for better detection
try {
const adapter = await navigator.gpu?.requestAdapter();
if (!adapter) {
log('WebGPU adapter not available');
return null;
}
} catch(e) {
log('WebGPU check failed: ' + (e?.message||e));
return null;
}
}
if (engine) return engine;
try {
await Promise.race([
loadSelectedModel(),
new Promise((_, reject) => setTimeout(() => reject(new Error('Model load timeout')), 60000))
]);
} catch(e) {
log('Engine initialization failed: ' + (e?.message||e));
return null;
}
return engine;
}
async function replyLLM(userText, retryCount = 0){
const t = ((tempEl && !Number.isNaN(tempEl.valueAsNumber)) ? tempEl.valueAsNumber : (parseFloat(tempEl ? tempEl.value : '1') || 1));
const node = add('bot', '');
// reset token stats
if (tokCountEl) tokCountEl.textContent = '0';
if (tpsAvgEl) tpsAvgEl.textContent = '0';
let emitted = 0; const t0 = performance.now();
stopRequested = false;
requestStartTime = Date.now();
// Clear any existing timeout
if (activeRequestTimeout) {
clearTimeout(activeRequestTimeout);
activeRequestTimeout = null;
}
// Set timeout to detect stuck requests
activeRequestTimeout = setTimeout(() => {
if (node.textContent.trim() === '') {
log('Request appears stuck, attempting recovery...');
node.textContent = 'Response is taking longer than expected. Trying fallback...';
stopRequested = true;
// Force fallback after timeout