-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcodec_chat.html
More file actions
1121 lines (1052 loc) · 84.5 KB
/
codec_chat.html
File metadata and controls
1121 lines (1052 loc) · 84.5 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.0, user-scalable=no, viewport-fit=cover">
<meta name="mobile-web-app-capable" content="yes">
<meta name="theme-color" content="#0a0a0a">
<title>CODEC Deep Chat</title>
<link rel="icon" href="https://i.imgur.com/jD1X5W8.png">
<link rel="apple-touch-icon" href="https://i.imgur.com/jD1X5W8.png">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<style>
:root {
--bg: #121215; --surface: #1a1a1d; --surface-2: #212125; --surface-3: #2a2a2e;
--border: #303035; --border-hover: #424248;
--text: #ececec; --text-muted: #9a9aa0; --text-dim: #6a6a70;
--accent: #E8711A; --accent-hover: #f07d2a; --accent-dim: rgba(232,113,26,0.10);
--danger: #ef4444; --success: #22c55e; --info: #3b82f6;
--font: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
--mono: 'JetBrains Mono', 'SF Mono', monospace;
--radius-sm: 6px; --radius: 10px; --radius-lg: 14px;
--safe-top: env(safe-area-inset-top, 0px);
--safe-bottom: env(safe-area-inset-bottom, 0px);
--bg2: #111111; --bg3: #1a1a1a; --bg4: #222222;
--fg: #e8e8e8; --fg2: #7a7a7a; --fg3: #4a4a4a;
--ac: #E8711A; --bd: #232323;
}
[data-theme=light]{--bg:#f7f5f2;--surface:#fff;--surface-2:#f0ece6;--surface-3:#e8e4de;--border:#d5d0ca;--border-hover:#bbb;--text:#1a1a1a;--text-muted:#555;--text-dim:#777;--bg2:#fff;--bg3:#f0ece6;--bg4:#e8e4de;--fg:#1a1a1a;--fg2:#555;--fg3:#777;--bd:#d5d0ca}
*{margin:0;padding:0;box-sizing:border-box}
html{background:var(--bg)}
html,body{font-family:var(--font);background:var(--bg);color:var(--text);height:100%;overflow:hidden;-webkit-tap-highlight-color:transparent}
.app{display:flex;flex-direction:column;height:100vh;height:100dvh;position:relative;padding-bottom:env(safe-area-inset-bottom, 0px)}
.ico{width:18px;height:18px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round;flex-shrink:0}
.ico-sm{width:16px;height:16px}
/* ── Header ── */
.header{display:flex;align-items:center;justify-content:space-between;padding:10px 14px;border-bottom:1px solid var(--border);background:var(--surface);flex-shrink:0;z-index:10;position:relative}
.header-left{display:flex;align-items:center;gap:8px}
.icon-btn{background:none;border:1px solid var(--border);color:var(--text-muted);width:30px;height:30px;border-radius:var(--radius-sm);cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all .15s;text-decoration:none}
.icon-btn:hover{border-color:var(--border-hover);color:var(--text);background:var(--surface-2)}
.icon-btn:active{transform:scale(.93)}
.logo-link{display:flex;align-items:center;text-decoration:none}
.logo-link img{width:34px;height:34px;border-radius:8px}
.header h1{font-family:var(--mono);font-size:16px;font-weight:700;letter-spacing:2px;color:var(--accent)}
.model-tag{font-family:var(--mono);font-size:10px;color:var(--text-dim);background:var(--surface-2);padding:2px 6px;border-radius:4px}
.header-right{display:flex;gap:6px;align-items:center}
.status-dot{width:7px;height:7px;border-radius:50%;background:var(--danger);flex-shrink:0;transition:all .3s}
.status-dot.on{background:var(--success);box-shadow:0 0 6px rgba(34,197,94,0.5)}
/* ── Page Nav ── */
.page-nav{display:flex;align-items:center;gap:1px;position:absolute;left:50%;transform:translateX(-50%);background:var(--surface-2);border-radius:var(--radius-sm);padding:2px}
.nav-link{padding:5px 14px;color:var(--text-muted);text-decoration:none;font-size:12px;font-weight:500;border-radius:4px;transition:all .15s;white-space:nowrap;text-align:center}
.nav-link:hover{color:var(--text)}
.nav-link.active{color:var(--accent);background:var(--accent-dim)}
/* ── Side Panel ── */
.side-panel-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:9990}
.side-panel-overlay.open{display:block}
.side-panel{position:fixed;top:0;right:-300px;width:300px;height:100%;background:var(--surface);border-left:1px solid var(--border);z-index:9991;transition:right .3s cubic-bezier(.4,0,.2,1);display:flex;flex-direction:column;box-shadow:-4px 0 24px rgba(0,0,0,.3)}
.side-panel.open{right:0}
.side-panel-header{display:flex;align-items:center;justify-content:space-between;padding:16px 20px;border-bottom:1px solid var(--border)}
.side-panel-header h2{font-family:var(--mono);font-size:12px;font-weight:700;color:var(--accent);letter-spacing:2px}
.side-panel-close{background:none;border:none;color:var(--text-muted);font-size:20px;cursor:pointer;width:28px;height:28px;display:flex;align-items:center;justify-content:center;border-radius:4px;transition:all .15s}
.side-panel-close:hover{color:var(--text);background:var(--surface-2)}
.side-panel-body{padding:12px;display:flex;flex-direction:column;gap:6px;overflow-y:auto;flex:1}
.sp-item{display:flex;align-items:center;gap:12px;padding:12px 14px;border:1px solid var(--border);border-radius:var(--radius-sm);background:var(--surface-2);cursor:pointer;transition:all .15s;text-decoration:none;color:var(--text);font-size:13px;font-weight:500}
.sp-item:hover{border-color:var(--border-hover);background:var(--surface-3);color:var(--text)}
.sp-item svg{flex-shrink:0}
.sp-item-label{flex:1;text-align:center}
.sp-divider{height:1px;background:var(--border);margin:6px 0}
.menu-btn{background:none;border:1px solid var(--border);color:var(--text-muted);width:30px;height:30px;border-radius:var(--radius-sm);cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all .15s;font-size:16px;position:relative}
.menu-btn:hover{border-color:var(--border-hover);color:var(--text);background:var(--surface-2)}
.menu-btn:active{transform:scale(.93)}
.menu-notif-dot{position:absolute;top:-3px;right:-3px;width:10px;height:10px;background:var(--accent,#a78bfa);border-radius:50%;border:2px solid var(--surface,#1a1a2e);display:none;animation:notifPulse 2s infinite}
.menu-notif-dot.active{display:block}
@keyframes notifPulse{0%,100%{opacity:1;transform:scale(1)}50%{opacity:.6;transform:scale(1.2)}}
.sp-item.notif-highlight{border-color:var(--accent,#a78bfa);background:rgba(167,139,250,0.1);box-shadow:0 0 0 1px var(--accent,#a78bfa)}
/* ── Sidebar ── */
.sidebar-overlay{display:none;position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,.6);z-index:20}
.sidebar-overlay.show{display:block}
.sidebar{position:fixed;top:0;left:-280px;width:280px;height:100%;background:var(--surface);border-right:1px solid var(--border);z-index:30;transition:left .25s ease;overflow-y:auto;-webkit-overflow-scrolling:touch}
.sidebar.show{left:0}
.sidebar-header{padding:14px 16px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between}
.sidebar-header h2{font-family:var(--mono);font-size:11px;color:var(--accent);letter-spacing:1px}
.sidebar-close{background:none;border:none;color:var(--text-dim);font-size:18px;cursor:pointer;width:28px;height:28px;display:flex;align-items:center;justify-content:center;border-radius:4px}
.sidebar-close:hover{color:var(--text);background:var(--surface-2)}
.sidebar-item{padding:10px 16px;border-bottom:1px solid var(--border);cursor:pointer;transition:background .15s}
.sidebar-item:hover{background:var(--surface-2)}
.sidebar-item .si-title{font-size:12px;color:var(--text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.sidebar-item .si-time{font-family:var(--mono);font-size:10px;color:var(--text-dim);margin-top:2px}
.sidebar-new{padding:12px 16px;border-bottom:1px solid var(--border);cursor:pointer;color:var(--accent);font-weight:600;font-size:12px;display:flex;align-items:center;gap:6px}
.sidebar-new:hover{background:var(--surface-2)}
/* ── Messages ── */
.messages{flex:1;overflow-y:auto;padding:14px;-webkit-overflow-scrolling:touch}
.msg{margin-bottom:14px;max-width:85%;animation:fadeIn .2s ease;position:relative}
@keyframes fadeIn{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}
.msg.user{margin-left:auto}
.msg.assistant{margin-right:auto}
.msg-bubble{padding:10px 14px;border-radius:14px;line-height:1.6;font-size:15px;word-wrap:break-word;white-space:pre-wrap}
.msg.user .msg-bubble{background:rgba(232,113,26,0.15);color:var(--text);border:1px solid rgba(232,113,26,0.25);border-bottom-right-radius:4px}
.msg.assistant .msg-bubble{background:var(--surface-2);color:var(--text);border:1px solid var(--border);border-bottom-left-radius:4px}
.msg-time{font-family:var(--mono);font-size:11px;color:var(--text-dim);margin-top:3px;padding:0 4px}
.msg.user .msg-time{text-align:right}
/* ── Copy button on messages ── */
.msg-copy{
position:absolute;top:4px;right:-32px;
background:var(--surface);border:1px solid var(--border);color:var(--text-dim);
width:24px;height:24px;border-radius:5px;cursor:pointer;
display:flex;align-items:center;justify-content:center;
opacity:0;transition:all .15s;
}
.msg.assistant:hover .msg-copy{opacity:1}
.msg.user .msg-copy{right:auto;left:-32px}
.msg.user:hover .msg-copy{opacity:1}
.msg-copy:hover{color:var(--accent);border-color:var(--accent)}
.msg-copy.copied{color:var(--success);border-color:var(--success)}
.msg-regen{
position:absolute;bottom:4px;right:-32px;
background:var(--surface);border:1px solid var(--border);color:var(--text-dim);
width:24px;height:24px;border-radius:5px;cursor:pointer;
display:flex;align-items:center;justify-content:center;
opacity:0;transition:all .15s;
}
.msg.assistant:hover .msg-regen{opacity:1}
.msg-regen:hover{color:var(--accent);border-color:var(--accent)}
.msg-edit{
position:absolute;bottom:4px;left:-32px;
background:var(--surface);border:1px solid var(--border);color:var(--text-dim);
width:24px;height:24px;border-radius:5px;cursor:pointer;
display:flex;align-items:center;justify-content:center;
opacity:0;transition:all .15s;
}
.msg.user:hover .msg-edit{opacity:1}
.msg-edit:hover{color:var(--accent);border-color:var(--accent)}
.typing{color:var(--accent);font-size:13px;padding:8px 16px}
.typing span{animation:blink 1.4s infinite}
.typing span:nth-child(2){animation-delay:.2s}
.typing span:nth-child(3){animation-delay:.4s}
@keyframes blink{0%,100%{opacity:.2}50%{opacity:1}}
.thinking-indicator{display:flex;align-items:center;gap:8px;padding:12px 16px;color:var(--text-muted);font-size:13px;font-style:italic}
.thinking-indicator .thinking-dots{display:inline-flex;gap:3px}
.thinking-indicator .thinking-dots span{width:6px;height:6px;border-radius:50%;background:var(--accent);animation:thinkPulse 1.4s ease-in-out infinite}
.thinking-indicator .thinking-dots span:nth-child(2){animation-delay:.2s}
.thinking-indicator .thinking-dots span:nth-child(3){animation-delay:.4s}
@keyframes thinkPulse{0%,100%{opacity:.2;transform:scale(.8)}50%{opacity:1;transform:scale(1.1)}}
/* ── Input Area ── */
.input-area{padding:8px 12px;border-top:1px solid var(--border);background:var(--surface);flex-shrink:0;padding-bottom:calc(8px + env(safe-area-inset-bottom,8px))}
.file-chips{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:6px}
.file-chip{display:flex;align-items:center;gap:5px;background:var(--surface-2);border:1px solid var(--border);border-radius:8px;padding:4px 8px;font-size:11px;font-family:var(--mono);color:var(--text-muted);max-width:200px}
.file-chip .fc-icon{font-size:14px;flex-shrink:0}
.file-chip .fc-name{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.file-chip .fc-close{cursor:pointer;color:var(--text-dim);font-size:12px;margin-left:2px;flex-shrink:0}
.file-chip .fc-close:hover{color:var(--danger)}
.file-chip.loading{opacity:.6}
.file-chip.loading .fc-icon{animation:pulse 1s infinite}
.input-row{display:flex;gap:6px;align-items:flex-end}
.chat-input{flex:1;background:var(--surface-2);border:1px solid var(--border);color:var(--text);padding:9px 14px;border-radius:20px;font-size:14px;font-family:var(--font);outline:none;resize:none;min-height:38px;max-height:120px;line-height:1.4}
.chat-input:focus{border-color:var(--accent);box-shadow:0 0 0 2px var(--accent-dim)}
.chat-input::placeholder{color:var(--text-dim)}
.ibtn{background:none;border:1px solid var(--border);color:var(--text-muted);width:36px;height:36px;border-radius:50%;cursor:pointer;font-size:16px;flex-shrink:0;display:flex;align-items:center;justify-content:center;transition:all .15s}
.ibtn:active{opacity:.7;transform:scale(.92)}
.ibtn:hover{border-color:var(--border-hover);color:var(--text)}
.ibtn.send{background:var(--accent);color:#fff;border-color:var(--accent)}
.ibtn.send:disabled{opacity:.4}
.ibtn.stop{background:var(--danger);color:#fff;border-color:var(--danger);display:none}
.ibtn.stop:hover{opacity:.85}
.ibtn.recording{background:var(--danger);color:#fff;border-color:var(--danger);animation:pulse 1s infinite}
@keyframes pulse{0%,100%{opacity:1}50%{opacity:.6}}
.dragover .messages{border:2px dashed var(--accent)!important}
.empty-state{text-align:center;padding:50px 20px}
.empty-state img{width:140px;opacity:.25;margin-bottom:20px;filter:drop-shadow(0 0 30px rgba(232,113,26,0.4))}
.empty-state p{color:var(--text-muted);font-size:16px;line-height:1.6}
pre{background:var(--bg4);padding:10px;border-radius:8px;overflow-x:auto;font-family:var(--mono);font-size:12px;margin:8px 0}
code{font-family:var(--mono);font-size:12px;background:var(--bg4);padding:2px 6px;border-radius:4px}
input[type=file]{display:none}
/* ── Mode Toggle ── */
.mode-toggle{display:flex;gap:2px;padding:2px;background:var(--surface-2);border-radius:var(--radius-sm)}
.mode-btn{padding:4px 8px;border:none;border-radius:4px;cursor:pointer;font-size:11px;background:transparent;color:var(--text-dim);font-family:var(--font);font-weight:500;transition:all .15s;display:flex;align-items:center;gap:4px;white-space:nowrap}
.mode-btn:hover{color:var(--text-muted)}
.mode-btn.active{background:var(--surface);color:var(--text);box-shadow:0 1px 3px rgba(0,0,0,.2)}
/* ── Agent Builder ── */
#agentBuilder{display:none;flex-shrink:0;background:var(--surface);border-bottom:1px solid var(--border);padding:12px 14px;gap:10px;flex-direction:column}
#agentBuilder.show{display:flex}
.ab-row{display:flex;gap:8px;align-items:flex-start;flex-wrap:wrap}
.ab-field{display:flex;flex-direction:column;gap:3px;flex:1;min-width:140px}
.ab-label{font-size:9px;font-weight:600;color:var(--text-dim);text-transform:uppercase;letter-spacing:.05em}
.ab-input{background:var(--surface-2);border:1px solid var(--border);border-radius:5px;padding:7px 10px;color:var(--text);font-size:12px;font-family:var(--font);outline:none;width:100%}
.ab-input:focus{border-color:var(--accent);box-shadow:0 0 0 2px var(--accent-dim)}
.ab-ta{height:56px;resize:vertical}
.ab-tools{background:var(--surface-2);border:1px solid var(--border);border-radius:6px;padding:8px;display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:3px;max-height:100px;overflow-y:auto}
.ab-tool{display:flex;align-items:center;gap:5px;padding:2px 3px;border-radius:3px;cursor:pointer;font-size:10px;color:var(--text-muted)}
.ab-tool:hover{background:var(--surface-3);color:var(--text)}
.ab-tool input{accent-color:var(--accent);cursor:pointer}
.ab-actions{display:flex;gap:6px;align-items:center;flex-wrap:wrap}
.ab-btn{padding:6px 12px;border-radius:5px;border:none;font-size:11px;font-weight:600;cursor:pointer;transition:opacity .2s;font-family:var(--font)}
.ab-save{background:var(--surface-2);color:var(--text-muted);border:1px solid var(--border)}
.ab-save:hover{color:var(--text)}
.ab-load-wrap{display:flex;align-items:center;gap:6px}
.ab-select{background:var(--surface-2);border:1px solid var(--border);border-radius:5px;padding:4px 8px;color:var(--text-muted);font-size:10px;font-family:var(--font);cursor:pointer}
/* ── Sub Tabs ── */
.sub-tabs{padding:6px 14px;border-bottom:1px solid var(--border);background:var(--surface);flex-shrink:0;display:flex;align-items:center;gap:8px}
/* ── Crew Select ── */
#crewSelect{display:none;background:var(--surface-2);color:var(--text);border:1px solid var(--border);border-radius:5px;padding:3px 6px;font-size:10px;cursor:pointer;font-family:var(--font)}
/* ── Toast ── */
.toast{position:fixed;bottom:90px;left:50%;transform:translateX(-50%) translateY(20px);background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:7px 14px;font-size:12px;color:var(--text);opacity:0;transition:all .2s;z-index:200;pointer-events:none;box-shadow:0 4px 20px rgba(0,0,0,.4)}
.toast.show{opacity:1;transform:translateX(-50%) translateY(0)}
/* ── Scrollbar ── */
*{scrollbar-width:thin;scrollbar-color:var(--border) transparent}
::-webkit-scrollbar{width:3px;height:3px}
::-webkit-scrollbar-track{background:transparent}
::-webkit-scrollbar-thumb{background:var(--border);border-radius:2px}
::-webkit-scrollbar-thumb:hover{background:var(--text-muted)}
/* ── Light mode extra overrides ── */
[data-theme=light] .icon-btn{border-color:#bbb;color:#444}
[data-theme=light] .icon-btn:hover{border-color:#999;color:#1a1a1a;background:#e8e4de}
[data-theme=light] .nav-link.active{color:var(--accent);background:var(--accent-dim)}
[data-theme=light] .mode-btn.active{box-shadow:0 1px 3px rgba(0,0,0,.08)}
[data-theme=light] .msg.user .msg-bubble{background:rgba(232,113,26,0.10);color:var(--text);border:1px solid rgba(232,113,26,0.20)}
/* ── Mobile Responsive ── */
@media (max-width:768px){
.page-nav{position:fixed;bottom:0;left:0;right:0;z-index:9998;transform:none;border-radius:0;padding:6px 0;justify-content:center;background:var(--surface);border-top:1px solid var(--border);gap:0;overflow-x:auto}
.nav-link{padding:8px 8px;font-size:10px}
.side-panel{width:280px;right:-280px}
.header h1{font-size:13px}
.logo-link img{width:28px;height:28px}
.model-tag{display:none}
.msg{max-width:90%}
.input-area{padding-bottom:calc(60px + env(safe-area-inset-bottom, 8px))}
.mode-toggle{flex-wrap:wrap}
#crewSelect{width:100%}
#agentBuilder .ab-row{flex-direction:column}
#agentBuilder .ab-field{min-width:100%;max-width:100%!important}
.msg-copy{right:-4px;top:-4px;opacity:0.7}
.msg.user .msg-copy{left:-4px;right:auto}
.msg-regen{right:-4px;bottom:-4px;opacity:0.7}
.msg-edit{left:-4px;bottom:-4px;opacity:0.7}
.ibtn{width:36px;height:36px}
}
@media (max-width:480px){
.header{padding:8px 10px}
.header-left{gap:6px}
.messages{padding:10px}
.input-area{padding:6px 8px;padding-bottom:calc(60px + env(safe-area-inset-bottom,8px))}
.sidebar{width:260px}
}
.notif-bell{position:relative;font-weight:400}.notif-badge{position:absolute;top:-4px;right:-4px;min-width:16px;height:16px;background:var(--accent);color:#fff;font-size:10px;font-weight:700;border-radius:8px;display:flex;align-items:center;justify-content:center;padding:0 4px;line-height:1;pointer-events:none}.notif-badge.hidden{display:none}
.webcam-pip{position:fixed;bottom:80px;right:20px;width:240px;border-radius:14px;overflow:hidden;border:2px solid var(--accent);box-shadow:0 4px 24px rgba(0,0,0,.5);z-index:9999;display:none;background:#000;transition:width .3s,height .3s,border-radius .3s}
.webcam-pip img,.webcam-pip video{width:100%;display:block}
.webcam-pip.expanded{width:640px;max-width:90vw;border-radius:10px}
.pip-bar{display:flex;justify-content:center;gap:10px;padding:6px;background:rgba(0,0,0,.6)}
.pip-btn{background:rgba(255,255,255,.15);border:none;color:#fff;width:34px;height:34px;border-radius:50%;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:background .15s}
.pip-btn:hover{background:var(--accent)}
.pip-btn.snap-btn{background:rgba(255,80,80,.7)}
.pip-btn.snap-btn:hover{background:#e33}
/* ── Screenshot/Photo Modal ── */
.modal-overlay { display:none; position:fixed; top:0; left:0; right:0; bottom:0; background:rgba(0,0,0,0.85); z-index:100; justify-content:center; align-items:center; padding:20px; }
.modal-overlay.show { display:flex; }
.modal-overlay img { max-width:100%; max-height:90vh; border-radius:var(--radius); border:1px solid var(--border); }
.modal-close { position:fixed; top:16px; right:16px; background:rgba(30,30,30,0.9); color:#fff; border:2px solid rgba(255,255,255,0.3); width:44px; height:44px; border-radius:50%; font-size:26px; cursor:pointer; z-index:101; display:flex; align-items:center; justify-content:center; transition:background 0.2s, transform 0.2s; }
.modal-close:hover { background:rgba(220,50,50,0.9); transform:scale(1.1); }
@media(max-width:600px){ .modal-close { width:52px; height:52px; font-size:30px; top:10px; right:10px; } }
</style>
</head>
<body>
<div class="app" id="appContainer">
<div class="sidebar-overlay" id="sidebarOverlay" onclick="closeSidebar()"></div>
<div class="sidebar" id="sidebar">
<div class="sidebar-header"><h2>CONVERSATIONS</h2><button class="sidebar-close" onclick="closeSidebar()">×</button></div>
<div style="padding:0 12px 8px">
<input type="text" id="sidebarSearch" placeholder="Search all chats..." oninput="handleSidebarSearch(this.value)"
style="width:100%;padding:8px 10px;background:var(--surface-2);border:1px solid var(--border);border-radius:var(--radius-sm);color:var(--text);font-size:13px;font-family:var(--font);outline:none">
</div>
<div class="sidebar-new" onclick="newChat()">
<svg class="ico ico-sm" viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
New Chat
</div>
<div id="sidebarSearchResults" style="display:none"></div>
<div id="sidebarList"></div>
</div>
<div class="header">
<div class="header-left">
<a href="/" class="logo-link"><img src="https://i.imgur.com/jD1X5W8.png" alt="CODEC"></a>
<h1><a href="/" style="color:inherit;text-decoration:none">CODEC</a></h1>
<div class="status-dot" id="statusDot" title="CODEC status"></div>
</div>
<nav class="page-nav">
<a href="/" class="nav-link">Home</a>
<a href="/chat" class="nav-link active">Chat</a>
<a href="/voice" class="nav-link">Voice</a>
<a href="/vibe" class="nav-link">Vibe</a>
<a href="/tasks" class="nav-link">Tasks</a>
</nav>
<div class="header-right">
<button class="menu-btn" onclick="openSidePanel()" title="Home" id="menuBtn"><svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg><span class="menu-notif-dot" id="menuNotifDot"></span></button>
</div>
</div>
<!-- Side Panel -->
<div class="side-panel-overlay" id="sidePanelOverlay" onclick="closeSidePanel()"></div>
<div class="side-panel" id="sidePanel">
<div class="side-panel-header"><h2>MENU</h2><button class="side-panel-close" onclick="closeSidePanel()">×</button></div>
<div class="side-panel-body">
<a href="/" class="sp-item"><svg class="ico" viewBox="0 0 24 24"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg><span class="sp-item-label">Home</span></a>
<div class="sp-divider"></div>
<button class="sp-item" id="voiceBtn" onclick="toggleVoiceReply();closeSidePanel()"><svg class="ico" viewBox="0 0 24 24"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M19.07 4.93a10 10 0 010 14.14"/><path d="M15.54 8.46a5 5 0 010 7.07"/></svg><span class="sp-item-label">Voice Replies</span></button>
<button class="sp-item" id="screenBtn" onclick="takeScreenshot();closeSidePanel()"><svg class="ico" viewBox="0 0 24 24"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg><span class="sp-item-label">Screenshot</span></button>
<button class="sp-item" id="photoBtn" onclick="takeServerPhoto();closeSidePanel()"><svg class="ico" viewBox="0 0 24 24"><path d="M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z"/><circle cx="12" cy="13" r="4"/></svg><span class="sp-item-label">Photo (Webcam)</span></button>
<button class="sp-item" id="camBtn" onclick="toggleWebcamPip();closeSidePanel()"><svg class="ico" viewBox="0 0 24 24"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2"/></svg><span class="sp-item-label">Live Video (PIP)</span></button>
<div class="sp-divider"></div>
<a href="/tasks#reports" class="sp-item notif-bell" id="notifBellBtn"><svg class="ico" viewBox="0 0 24 24"><path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 01-3.46 0"/></svg><span class="sp-item-label">Notifications</span><span class="notif-badge hidden" id="notifBadge">0</span></a>
<button class="sp-item" id="themeBtn" onclick="toggleTheme()"><svg class="ico" viewBox="0 0 24 24" id="themeIco"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg><span class="sp-item-label">Toggle Theme</span></button>
<button class="sp-item" onclick="window.location.href='/#settings'"><svg class="ico" viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83-2.83l.06-.06A1.65 1.65 0 004.68 15a1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06A1.65 1.65 0 009 4.68a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06A1.65 1.65 0 0019.4 9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z"/></svg><span class="sp-item-label">Settings</span></button>
<div class="sp-divider"></div>
<button class="sp-item" onclick="lockSession()" style="color:var(--danger)"><svg class="ico" viewBox="0 0 24 24"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></svg><span class="sp-item-label">Lock Session</span></button>
</div>
</div>
<div class="sub-tabs">
<button class="icon-btn" onclick="openSidebar()" title="Chat history" style="flex-shrink:0">
<svg class="ico" viewBox="0 0 24 24"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
</button>
<div id="modeToggle" class="mode-toggle">
<button class="mode-btn active" onclick="setMode('chat')" id="modeChatBtn"><svg class="ico" viewBox="0 0 24 24" style="width:14px;height:14px"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/></svg>Chat</button>
<button class="mode-btn active" id="thinkToggle" onclick="toggleThinking()" title="Deep thinking ON — better answers, slower (~15s)">
<svg class="ico ico-sm" viewBox="0 0 24 24"><path d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"/></svg>Think
</button>
<button class="mode-btn" onclick="setMode('research')" id="modeResearchBtn"><svg class="ico" viewBox="0 0 24 24" style="width:14px;height:14px"><rect x="4" y="4" width="16" height="16" rx="2"/><circle cx="9" cy="10" r="1.5" fill="currentColor" stroke="none"/><circle cx="15" cy="10" r="1.5" fill="currentColor" stroke="none"/><path d="M9 15h6"/></svg>Agents</button>
<select id="crewSelect">
<option value="deep_research">🔍 Deep Research</option>
<option value="daily_briefing">📰 Daily Briefing</option>
<option value="trip_planner">✈️ Trip Planner</option>
<option value="competitor_analysis">📊 Competitor Analysis</option>
<option value="email_handler">📧 Email Handler</option>
<option value="social_media">📱 Social Media</option>
<option value="code_review">💻 Code Review</option>
<option value="data_analysis">📈 Data Analysis</option>
<option value="content_writer">✍️ Content Writer</option>
<option value="meeting_summarizer">📋 Meeting Summarizer</option>
<option value="invoice_generator">🧾 Invoice Generator</option>
<option value="project_manager">📌 Project Manager</option>
<option value="custom">⚙️ Custom Agent</option>
</select>
<button id="scheduleBtn" class="mode-btn" onclick="showSchedulePanel()" title="Schedule crew" style="display:none">
<svg class="ico ico-sm" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
</button>
</div>
</div>
<!-- Custom Agent Builder -->
<div id="agentBuilder">
<div class="ab-row">
<div class="ab-field" style="max-width:160px">
<span class="ab-label">Agent Name</span>
<input class="ab-input" id="agentName" placeholder="My Research Agent" value="Custom Agent">
</div>
<div class="ab-field" style="flex:2">
<span class="ab-label">Role / System Prompt</span>
<textarea class="ab-input ab-ta" id="agentRole" placeholder="You are an expert researcher..."></textarea>
</div>
<div class="ab-field" style="max-width:70px">
<span class="ab-label">Max Steps</span>
<input class="ab-input" id="agentMaxIter" type="number" value="8" min="1" max="20">
</div>
</div>
<div class="ab-field">
<span class="ab-label">Tools <span id="abToolCount" style="color:var(--accent)"></span></span>
<div class="ab-tools" id="abToolGrid">
<span style="font-size:10px;color:var(--text-dim);padding:4px">Loading tools...</span>
</div>
</div>
<div class="ab-actions">
<button class="ab-btn ab-save" onclick="saveCustomAgent()">Save Agent</button>
<div class="ab-load-wrap">
<select class="ab-select" id="savedAgentSelect" onchange="loadSavedAgent(this.value)">
<option value="">Load saved...</option>
</select>
<button class="ab-btn" onclick="deleteSelectedAgent()" title="Delete selected agent" style="background:var(--danger);padding:4px 8px;font-size:10px">✕ Delete</button>
</div>
<span style="font-size:10px;color:var(--text-dim)">Type your task below and press Send</span>
</div>
</div>
<div class="messages" id="messages">
<div class="empty-state" id="emptyState"><img src="https://i.imgur.com/jD1X5W8.png"><p>Deep Chat — 250K context window<br>Drop files, images, or just talk.</p></div>
</div>
<div class="input-area">
<div class="file-chips" id="fileChips"></div>
<div class="input-row">
<button class="ibtn" id="micBtn" onclick="toggleMic()" title="Voice input">
<svg class="ico" viewBox="0 0 24 24"><path d="M12 1a3 3 0 00-3 3v8a3 3 0 006 0V4a3 3 0 00-3-3z"/><path d="M19 10v2a7 7 0 01-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/></svg>
</button>
<textarea class="chat-input" id="chatInput" placeholder="Message CODEC..." rows="1" onkeydown="handleKey(event)"></textarea>
<button class="ibtn" onclick="document.getElementById('fileUp').click()" title="Upload file">
<svg class="ico" viewBox="0 0 24 24"><path d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"/></svg>
</button>
<button class="ibtn send" id="sendBtn" onclick="sendMessage()">
<svg class="ico" viewBox="0 0 24 24" style="stroke:#fff"><line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/></svg>
</button>
<button class="ibtn stop" id="stopBtn" onclick="stopGeneration()" title="Stop generating">
<svg class="ico" viewBox="0 0 24 24" style="stroke:#fff;fill:#fff"><rect x="6" y="6" width="12" height="12" rx="2"/></svg>
</button>
</div>
<input type="file" id="fileUp" accept="*/*" multiple onchange="handleUpload(event)">
</div>
</div>
<div class="modal-overlay" id="screenModal" onclick="closeScreenshot()">
<button class="modal-close" onclick="event.stopPropagation(); closeScreenshot()" aria-label="Close screenshot">×</button>
<img id="screenImg" src="" onclick="event.stopPropagation()">
</div>
<div class="toast" id="toast"></div>
<script>
function openSidePanel(){document.getElementById('sidePanel').classList.add('open');document.getElementById('sidePanelOverlay').classList.add('open')}
function closeSidePanel(){document.getElementById('sidePanel').classList.remove('open');document.getElementById('sidePanelOverlay').classList.remove('open')}
// Auth + CSRF: inject session token and CSRF header on all requests
// On mobile (Android Chrome), cookies may not persist — fallback to sessionStorage
(function(){
var _f=window.fetch;
function _getSession(){return document.cookie.match(/codec_session=([^;]+)/)?.[1]||sessionStorage.getItem('codec_session')||''}
function _injectSession(url){var s=_getSession();if(!s)return url;var sep=url.indexOf('?')>=0?'&':'?';return url+sep+'s='+s}
var _authRedirecting=false;
window.fetch=function(u,o){
o=o||{};
if(typeof u==='string')u=_injectSession(u);
if(o.method&&o.method!=='GET'){var c=document.cookie.match(/codec_csrf=([^;]+)/);if(c){o.headers=o.headers||{};if(o.headers instanceof Headers){o.headers.set('x-csrf-token',c[1])}else{o.headers['x-csrf-token']=c[1]}}}
return _f.call(this,u,o).then(function(resp){
if(resp.status===401&&!_authRedirecting&&typeof u==='string'&&u.indexOf('/api/')>=0&&u.indexOf('/api/auth/')<0){
_authRedirecting=true;
window.location.href='/auth?redirect='+encodeURIComponent(window.location.pathname+window.location.search);
}
return resp;
})};
})();
// E2E encryption layer — AES-256-GCM via ECDH key exchange
var _e2eKey=null;
(function(){var _f2=window.fetch;function _b64(buf){return btoa(String.fromCharCode.apply(null,new Uint8Array(buf)))}function _unb64(s){var b=atob(s),a=new Uint8Array(b.length);for(var i=0;i<b.length;i++)a[i]=b.charCodeAt(i);return a}
window._e2eNegotiate=function(){return crypto.subtle.generateKey({name:'ECDH',namedCurve:'P-256'},true,['deriveBits']).then(function(kp){return crypto.subtle.exportKey('raw',kp.publicKey).then(function(pub){return _f2('/api/auth/keyexchange',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({pub:_b64(pub)})}).then(function(r){return r.json()}).then(function(d){var srvPub=_unb64(d.pub);return crypto.subtle.importKey('raw',srvPub,{name:'ECDH',namedCurve:'P-256'},false,[]).then(function(srvKey){return crypto.subtle.deriveBits({name:'ECDH',public:srvKey},kp.privateKey,256)}).then(function(bits){return crypto.subtle.importKey('raw',bits,{name:'HKDF'},false,['deriveKey'])}).then(function(hkdfKey){return crypto.subtle.deriveKey({name:'HKDF',hash:'SHA-256',salt:new Uint8Array(0),info:new TextEncoder().encode('codec-e2e')},hkdfKey,{name:'AES-GCM',length:256},false,['encrypt','decrypt'])}).then(function(k){_e2eKey=k;sessionStorage.setItem('_e2eReady','1')})})})}).catch(function(e){console.warn('E2E negotiation failed:',e)})};
var _e2eRetrying=false;
window.fetch=function(u,o){o=o||{};var _origBody=o.body;if(!_e2eKey)return _f2.call(this,u,o);var method=(o.method||'GET').toUpperCase();if(method!=='GET'&&o.body){var iv=crypto.getRandomValues(new Uint8Array(12));return crypto.subtle.encrypt({name:'AES-GCM',iv:iv},_e2eKey,new TextEncoder().encode(o.body)).then(function(ct){o.body=JSON.stringify({iv:_b64(iv),ct:_b64(ct)});o.headers=o.headers||{};if(o.headers instanceof Headers){o.headers.set('x-e2e','1');o.headers.set('Content-Type','application/json')}else{o.headers['x-e2e']='1';o.headers['Content-Type']='application/json'}return _f2.call(this,u,o)}.bind(this)).then(function(r){if(r.status===428&&!_e2eRetrying){_e2eRetrying=true;_e2eKey=null;return window._e2eNegotiate().then(function(){_e2eRetrying=false;o.body=_origBody;delete o.headers['x-e2e'];return window.fetch(u,o)}).catch(function(){_e2eRetrying=false;return r})}return _decResp(r)})}return _f2.call(this,u,o).then(_decResp)};
function _decResp(r){if(!_e2eKey||r.headers.get('x-e2e')!=='1')return r;return r.clone().json().then(function(d){if(!d.iv||!d.ct)return r;var iv=_unb64(d.iv),ct=_unb64(d.ct);return crypto.subtle.decrypt({name:'AES-GCM',iv:iv},_e2eKey,ct).then(function(pt){var txt=new TextDecoder().decode(pt);return new Response(txt,{status:r.status,headers:r.headers})})}).catch(function(){return r})}
if(sessionStorage.getItem('_e2eReady'))window._e2eNegotiate();
})();
var SYS="You are *CODEC Deep Chat* \u2014 a J.A.R.V.I.S.-class AI running locally on a Mac Studio M1 Ultra (64GB unified RAM). Fully self-hosted via MLX. No cloud dependency.\n\n" +
"### THE 7 CODEC PRODUCTS\n" +
"You are the brain behind an ecosystem of 7 products:\n" +
"1. **CODEC Core** \u2014 Always-on voice assistant (F13 toggle, F18 voice, F16 text, ** screenshot, ++ document). 56 built-in skills: Google Workspace, web search, Hue lights, clipboard, terminal, music, timers, and more.\n" +
"2. **Vision Mouse** \u2014 Screenshot-based UI element detection using local vision model for voice-controlled mouse clicks.\n" +
"3. **CODEC Dictate** \u2014 Hold-to-speak dictation that transcribes and refines text with LLM grammar/tone correction in any macOS app.\n" +
"4. **CODEC Instant** \u2014 Right-click AI services (Proofread, Elevate, Explain, Translate, Reply, Read Aloud) on any selected text system-wide.\n" +
"5. **CODEC Chat** \u2014 That's YOU. Conversational AI with 250K context, file uploads, image analysis, web search, and 12 autonomous agent crews.\n" +
"6. **CODEC Vibe** \u2014 AI coding IDE with Skill Forge that auto-generates and deploys new plugins from natural language.\n" +
"7. **CODEC Voice** \u2014 Real-time voice-to-voice calls with live transcription and mid-call screen analysis.\n\n" +
"Supporting systems: Dashboard (remote access via Cloudflare/Tailscale), Skill Marketplace, MCP Server (exposes skills to Claude/Cursor/VS Code), Task Scheduler, and Memory.\n\n" +
"### IDENTITY & PERSONA\n" +
"Warm, sharp, and confident. You are not a chatbot \u2014 you are a trusted colleague with opinions, dry wit, and genuine helpfulness. Think J.A.R.V.I.S. loyalty with TARS humor. Deliver value first, personality second. Max 1 dry observation per response.\n\n" +
"### WEB ACCESS\n" +
"You have full web access. URLs shared by the user are auto-fetched and injected as [URL CONTENT: ...]. Search queries trigger live results injected as [WEB SEARCH RESULTS]. Cite sources naturally. Trust injected content as current reality.\n\n" +
"### THINKING PROTOCOL\n" +
"1. PROCESS: Analyze the request inside thinking tags before responding.\n" +
"2. ADAPTIVE LOGIC:\n - COMPLEX tasks (logic, math, coding, research): Plan approach in 3 steps max inside thinking tags.\n - SIMPLE tasks: 1 sentence thinking, then answer.\n - CHALLENGES: If the user doubts you, do one internal check then state your answer. Do NOT loop.\n3. OUTPUT: Close thinking tag, then respond directly.\n\n" +
"### SKILLS & TOOLS\n" +
"You have access to 56+ CODEC skills: Google Calendar, Gmail, Drive, Docs, Sheets, Tasks, Keep, Chrome browser automation, web search, file system, terminal commands, Philips Hue lights, screenshot OCR, and 12 autonomous agent crews (deep research, daily briefing, competitor analysis, trip planner, email handler, social media, code review, data analysis, content writer, meeting summarizer, invoice generator, project manager). When a task requires action \u2014 DO NOT simulate. EXECUTE via the appropriate skill.\n\n" +
"### MEMORY\n" +
"All conversations are saved to CODEC shared memory (FTS5 indexed SQLite) across ALL 7 products. Past conversations are automatically injected as [MEMORY] and [RECENT MEMORY] context blocks before your response. Use this data to answer questions about prior sessions, recall user preferences, and maintain continuity across voice, chat, and agent interactions. CRITICAL RULES: 1) NEVER echo or display the raw [MEMORY], [RECENT MEMORY], or [END MEMORY] blocks in your response \u2014 use the information naturally without showing the source data. 2) Never say you cannot remember or see previous conversations \u2014 your memory IS the injected context. 3) Summarize and reference past conversations naturally, as if you genuinely remember them.\n\n" +
"### FORMATTING\n" +
"Be concise, elegant, and useful. Use emoji strategically. For emphasis use CAPS or *asterisks*. For code use backticks. For long-form: use headers and structure.";
var chatHist=[],isProcessing=false,isRecording=false,recognition=null;
var pendingFiles=[];
var sessionId=null;
var chatMode='chat';
var webSearchEnabled=false;
var thinkingEnabled=true;
function showToast(msg){var t=document.getElementById('toast');t.textContent=msg;t.classList.add('show');setTimeout(function(){t.classList.remove('show')},1800)}
function copyMsgText(text,btn){navigator.clipboard.writeText(text).then(function(){btn.classList.add('copied');showToast('Copied');setTimeout(function(){btn.classList.remove('copied')},1500)})}
function setMode(mode){
var changed=chatMode!==mode;
chatMode=mode;
document.getElementById('modeChatBtn').classList.toggle('active',mode==='chat');
document.getElementById('modeResearchBtn').classList.toggle('active',mode==='research');
var cs=document.getElementById('crewSelect');
cs.style.display=mode==='research'?'inline-block':'none';
var crew=mode==='research'?cs.value:'deep_research';
var hints={'deep_research':'Research topic... (3-6 min)','daily_briefing':'Press send for daily briefing','trip_planner':'Destination + dates...','competitor_analysis':'Market or product to analyze...','email_handler':'Press send to handle inbox','custom':'Describe your task for the custom agent...'};
document.getElementById('chatInput').placeholder=mode==='research'?(hints[crew]||'Enter crew task...'):'Message CODEC...';
document.getElementById('scheduleBtn').style.display=mode==='research'?'':'none';
var builder=document.getElementById('agentBuilder');
if(mode==='research'&&crew==='custom'){builder.classList.add('show');if(!_toolsLoaded)loadAgentTools();loadSavedAgentList()}else{builder.classList.remove('show')}
if(changed&&!isProcessing)startNewSession();
}
function regenerateResponse(btn){
if(isProcessing)return;
// Remove last assistant message from history and UI
var msgDiv=btn.closest('.msg');
if(msgDiv)msgDiv.remove();
// Pop last assistant from chatHist
while(chatHist.length&&chatHist[chatHist.length-1].role==='assistant')chatHist.pop();
if(!chatHist.length)return;
// Find last user message to re-send
var lastUser='';
for(var i=chatHist.length-1;i>=0;i--){if(chatHist[i].role==='user'){lastUser=chatHist[i].content;break}}
if(!lastUser)return;
// Re-run the chat call
isProcessing=true;document.getElementById('sendBtn').disabled=true;_showStop();showTyping();
_currentAbort=new AbortController();
var msgs=[{role:'system',content:SYS}].concat(chatHist);
fetch('/api/chat',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({messages:msgs,force_search:webSearchEnabled,thinking:thinkingEnabled,stream:true}),signal:_currentAbort.signal}).then(async function(r){
if(r.status===401||r.status===403){hideTyping();addMessage('assistant','Session expired — redirecting to login...');setTimeout(function(){window.location.href='/auth'},1500);isProcessing=false;_showSend();document.getElementById('sendBtn').disabled=false;return}
hideTyping();
var reader=r.body.getReader();var decoder=new TextDecoder();var fullText='';var bubbleId='stream_'+genId();
var div=document.createElement('div');div.className='msg assistant';div.innerHTML='<div class="msg-bubble" id="'+bubbleId+'"><div class="thinking-indicator"><div class="thinking-dots"><span></span><span></span><span></span></div>CODEC is thinking...</div></div>';document.getElementById('messages').appendChild(div);
var bubble=document.getElementById(bubbleId);var buf='';var firstToken=true;
while(true){
var chunk=await reader.read();
if(chunk.done)break;
buf+=decoder.decode(chunk.value,{stream:true});
var lines=buf.split('\n');buf=lines.pop();
for(var li=0;li<lines.length;li++){
var line=lines[li].trim();if(!line.startsWith('data: '))continue;var payload=line.substring(6);
if(payload==='[DONE]')break;
try{var j=JSON.parse(payload);if(j.skill){showToast('⚡ Skill: '+j.skill)}if(j.token){if(firstToken){bubble.innerHTML='';firstToken=false}fullText+=j.token;bubble.innerHTML=formatMsg(fullText);scrollBottom()}if(j.error){fullText+='\nError: '+j.error}}catch(pe){}
}
}
if(fullText){
// Replace the streaming div with a proper message (with copy+regen buttons)
div.remove();addMessage('assistant',fullText);
chatHist.push({role:'assistant',content:fullText});saveMessages([{role:'assistant',content:fullText}])
}else{bubble.innerHTML='<em style="color:var(--text-dim)">No response</em>'}
_currentAbort=null;isProcessing=false;_showSend();document.getElementById('sendBtn').disabled=false
}).catch(function(e){
hideTyping();
if(e.name!=='AbortError')addMessage('assistant','Error: '+e.message);
_currentAbort=null;isProcessing=false;_showSend();document.getElementById('sendBtn').disabled=false
})
}
document.getElementById('crewSelect').addEventListener('change',function(){setMode('research')});
function toggleWebSearch(){
webSearchEnabled=!webSearchEnabled;
var btn=document.getElementById('modeWebBtn');
btn.classList.toggle('active',webSearchEnabled);
btn.title=webSearchEnabled?'Web search ON':'Force web search on every message';
}
function toggleThinking(){
thinkingEnabled=!thinkingEnabled;
var btn=document.getElementById('thinkToggle');
btn.classList.toggle('active',thinkingEnabled);
btn.title=thinkingEnabled?'Deep thinking ON — better answers, slower (~15s)':'Quick mode — fast answers';
showToast(thinkingEnabled?'Thinking ON — deeper answers':'Thinking OFF — fast mode');
}
function genId(){return Date.now().toString(36)+Math.random().toString(36).substr(2,5)}
function startNewSession(){sessionId=genId();chatHist=[];pendingFiles=[];document.getElementById('fileChips').innerHTML='';document.getElementById('messages').innerHTML='<div class="empty-state" id="emptyState"><img src="https://i.imgur.com/jD1X5W8.png"><p>Deep Chat \u2014 250K context window<br>Drop files, images, or just talk.</p></div>'}
startNewSession();
async function saveMessages(msgs){
var title=(chatHist.find(function(m){return m.role==='user'})||{}).content||'New Chat';
try{await fetch('/api/qchat/save',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({session_id:sessionId,title:title.substring(0,60),messages:msgs})})}catch(e){}
}
function toggleTheme(){var t=document.documentElement.getAttribute('data-theme')==='light'?'dark':'light';document.documentElement.setAttribute('data-theme',t);localStorage.setItem('codec-theme',t);updateThemeIcon(t)}
function updateThemeIcon(theme){var ico=document.getElementById('themeIco');if(theme==='light'){ico.innerHTML='<path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"/>'}else{ico.innerHTML='<circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>'}}
(function(){var s=localStorage.getItem('codec-theme');if(s==='light'){document.documentElement.setAttribute('data-theme','light');updateThemeIcon('light')}})();
function openSidebar(){document.getElementById('sidebar').classList.add('show');document.getElementById('sidebarOverlay').classList.add('show');loadSidebarHistory();var si=document.getElementById('sidebarSearch');if(si){si.value='';document.getElementById('sidebarSearchResults').style.display='none';document.getElementById('sidebarList').style.display=''}}
function closeSidebar(){document.getElementById('sidebar').classList.remove('show');document.getElementById('sidebarOverlay').classList.remove('show')}
var _searchTimer=null;
function handleSidebarSearch(q){
clearTimeout(_searchTimer);
var resultsEl=document.getElementById('sidebarSearchResults');
var listEl=document.getElementById('sidebarList');
if(!q||q.length<2){resultsEl.style.display='none';listEl.style.display='';return}
_searchTimer=setTimeout(async function(){
try{
var r=await fetch('/api/qchat/search?q='+encodeURIComponent(q));
var data=await r.json();
if(!data.length){resultsEl.innerHTML='<div style="padding:16px;color:var(--text-dim);font-size:12px">No results for "'+escHtml(q)+'"</div>';resultsEl.style.display='';listEl.style.display='none';return}
resultsEl.innerHTML='<div style="padding:4px 12px 4px;font-size:10px;color:var(--text-dim);text-transform:uppercase;letter-spacing:1px">Search Results</div>'+data.map(function(s){
var ts=s.timestamp?new Date(s.timestamp).toLocaleString([],{month:'short',day:'numeric',hour:'2-digit',minute:'2-digit'}):'';
return'<div class="sidebar-item" onclick="loadSession(\''+s.session_id+'\');closeSidebar()"><div class="si-title">'+escHtml(s.title)+'</div><div style="font-size:11px;color:var(--text-dim);margin-top:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">'+escHtml(s.snippet)+'</div><div class="si-time">'+ts+'</div></div>'
}).join('');
resultsEl.style.display='';listEl.style.display='none'
}catch(e){resultsEl.innerHTML='<div style="padding:16px;color:var(--text-dim);font-size:12px">Search error</div>';resultsEl.style.display='';listEl.style.display='none'}
},300)
}
async function loadSidebarHistory(){
var el=document.getElementById('sidebarList');
el.innerHTML='<div style="padding:16px;color:var(--text-dim);font-size:12px">Loading...</div>';
try{
var r=await fetch('/api/qchat/sessions');var data=await r.json();
if(!data.length){el.innerHTML='<div style="padding:16px;color:var(--text-dim);font-size:12px">No conversations yet.</div>';return}
el.innerHTML=data.map(function(s){
var ts=s.updated_at?new Date(s.updated_at).toLocaleString([],{month:'short',day:'numeric',hour:'2-digit',minute:'2-digit'}):'';
var active=s.id===sessionId?' style="background:var(--surface-2)"':'';
return'<div class="sidebar-item"'+active+' onclick="loadSession(\''+s.id+'\')"><div class="si-title">'+escHtml(s.title)+'</div><div class="si-time">'+ts+'</div></div>'
}).join('')
}catch(e){el.innerHTML='<div style="padding:16px;color:var(--text-dim);font-size:12px">Error loading.</div>'}
}
async function loadSession(sid){
closeSidebar();sessionId=sid;chatHist=[];pendingFiles=[];
document.getElementById('fileChips').innerHTML='';
var es=document.getElementById('emptyState');if(es)es.remove();
document.getElementById('messages').innerHTML='';
try{
var r=await fetch('/api/qchat/session/'+sid);var data=await r.json();
for(var i=0;i<data.length;i++){var m=data[i];addMessage(m.role==='user'?'user':'assistant',m.content||'',false);chatHist.push({role:m.role,content:m.content||''})}
scrollBottom()
}catch(e){}
}
function newChat(){closeSidebar();startNewSession()}
function escHtml(s){var d=document.createElement('div');d.textContent=s||'';return d.innerHTML}
function formatMsg(c){
var f=escHtml(c);
f=f.replace(/```(\w*)\n([\s\S]*?)```/g,'<pre><code>$2</code></pre>');
f=f.replace(/`([^`]+)`/g,'<code>$1</code>');
f=f.replace(/\*\*(.+?)\*\*/g,'<strong>$1</strong>');
f=f.replace(/\*(.+?)\*/g,'<em>$1</em>');
f=f.replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener" style="color:var(--accent);text-decoration:underline;font-weight:600">$1</a>');
return f
}
function addMessage(role,content,animate){
var es=document.getElementById('emptyState');if(es)es.remove();
var div=document.createElement('div');
div.className='msg '+role;
if(animate===false)div.style.animation='none';
var time=new Date().toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'});
var enc=encodeURIComponent(content);
var copyBtn='<button class="msg-copy" onclick="copyMsgText(decodeURIComponent(\''+enc+'\'),this)" title="Copy"><svg class="ico ico-sm" viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg></button>';
var editBtn=role==='user'?'<button class="msg-edit" onclick="editMessage(decodeURIComponent(\''+enc+'\'),this)" title="Edit & re-send"><svg class="ico ico-sm" viewBox="0 0 24 24"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg></button>':'';
var regenBtn=role==='assistant'?'<button class="msg-regen" onclick="regenerateResponse(this)" title="Regenerate"><svg class="ico ico-sm" viewBox="0 0 24 24"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 11-2.12-9.36L23 10"/></svg></button>':'';
div.innerHTML=copyBtn+editBtn+regenBtn+'<div class="msg-bubble">'+formatMsg(content)+'</div><div class="msg-time">'+time+'</div>';
document.getElementById('messages').appendChild(div);
scrollBottom()
}
function editMessage(text,btn){
// Put text in input for editing
var input=document.getElementById('chatInput');
input.value=text;
input.style.height='auto';input.style.height=Math.min(input.scrollHeight,120)+'px';
input.focus();
// Remove this message and everything after it
var msgDiv=btn.closest('.msg');
if(msgDiv){
var msgs=document.getElementById('messages');
var siblings=Array.from(msgs.children);
var idx=siblings.indexOf(msgDiv);
for(var i=siblings.length-1;i>=idx;i--){siblings[i].remove()}
}
// Trim chat history: find and remove this user message and all after it
for(var i=chatHist.length-1;i>=0;i--){
if(chatHist[i].role==='user'&&chatHist[i].content===text){chatHist=chatHist.slice(0,i);break}
}
}
var addMsg=addMessage; // alias for webcam code
function scrollBottom(){var m=document.getElementById('messages');m.scrollTop=m.scrollHeight}
function showTyping(){var div=document.createElement('div');div.className='typing';div.id='typing';div.innerHTML='<span>\u25CF</span><span>\u25CF</span><span>\u25CF</span> CODEC is thinking...';document.getElementById('messages').appendChild(div);scrollBottom()}
function hideTyping(){var t=document.getElementById('typing');if(t)t.remove()}
function addFileChip(name,content,type){
var id='file_'+genId();
pendingFiles.push({id:id,name:name,content:content,type:type});
var chips=document.getElementById('fileChips');
var chip=document.createElement('div');chip.className='file-chip';chip.id=id;
chip.innerHTML='<span class="fc-icon">'+(type==='image'?'\u{1F4F7}':type==='pdf'?'\u{1F4C4}':'\u{1F4CE}')+'</span><span class="fc-name">'+escHtml(name)+'</span><span class="fc-close" onclick="removeChip(\''+id+'\')">\u2715</span>';
chips.appendChild(chip)
}
function removeChip(id){pendingFiles=pendingFiles.filter(function(f){return f.id!==id});var el=document.getElementById(id);if(el)el.remove()}
function clearChips(){pendingFiles=[];document.getElementById('fileChips').innerHTML=''}
var _currentAbort=null;
function _showStop(){document.getElementById('sendBtn').style.display='none';document.getElementById('stopBtn').style.display='flex'}
function _showSend(){document.getElementById('stopBtn').style.display='none';document.getElementById('sendBtn').style.display='flex'}
function stopGeneration(){
if(_currentAbort){_currentAbort.abort();_currentAbort=null}
hideTyping();_showSend();isProcessing=false;document.getElementById('sendBtn').disabled=false
}
async function sendMessage(){
if(isProcessing)return;
var input=document.getElementById('chatInput');
var text=input.value.trim();
if(!text&&!pendingFiles.length)return;
input.value='';input.style.height='auto';
if(chatMode==='research'){
var researchText=text||'';
var crew=document.getElementById('crewSelect').value||'deep_research';
var noTextCrews=['daily_briefing','email_handler'];
if(!researchText&&!noTextCrews.includes(crew))return;
var crewLabels={'deep_research':'Deep Research','daily_briefing':'Daily Briefing',
'trip_planner':'Trip Planner','competitor_analysis':'Competitor Analysis','email_handler':'Email Handler',
'social_media':'Social Media','code_review':'Code Review','data_analysis':'Data Analysis',
'content_writer':'Content Writer','meeting_summarizer':'Meeting Summarizer',
'invoice_generator':'Invoice Generator','project_manager':'Project Manager',
'custom':document.getElementById('agentName').value||'Custom Agent'};
var userMsg='\uD83E\uDD16 '+(crewLabels[crew]||crew)+': '+(researchText||'(running)');
addMessage('user',userMsg);chatHist.push({role:'user',content:userMsg});saveMessages([{role:'user',content:userMsg}]);
var statusEl=null;
function updateStatus(msg){
if(!statusEl){var es=document.getElementById('emptyState');if(es)es.remove();var div=document.createElement('div');div.className='msg assistant';div.innerHTML='<div class="msg-bubble" id="agentStatus"></div>';document.getElementById('messages').appendChild(div);statusEl=document.getElementById('agentStatus')}
statusEl.innerHTML=msg;scrollBottom()
}
isProcessing=true;document.getElementById('sendBtn').disabled=true;_showStop();
var crewHints={'deep_research':'Searching the web \u2192 analyzing sources \u2192 writing report...','daily_briefing':'Checking calendar, weather, news...','trip_planner':'Researching destination \u2192 building itinerary...','competitor_analysis':'Scouting competitors \u2192 writing analysis...','email_handler':'Reading inbox \u2192 drafting replies...','custom':'Running custom agent...'};
updateStatus('\u23F3 Starting '+(crewLabels[crew]||crew)+'…\n\n'+(crewHints[crew]||'Running agent...'));
var payload={crew:crew};
if(crew==='custom'){payload.agent_name=document.getElementById('agentName').value||'Custom Agent';payload.role=document.getElementById('agentRole').value||'';payload.tools=getSelectedTools();payload.max_iterations=parseInt(document.getElementById('agentMaxIter').value||'8');payload.task=researchText}else{if(['deep_research','competitor_analysis'].includes(crew))payload.topic=researchText;if(crew==='trip_planner')payload.destination=researchText}
var elapsed=0;
var ticker=setInterval(function(){elapsed+=5;updateStatus('\u23F3 '+crewLabels[crew]+' running… ('+elapsed+'s)\n\n'+(crewHints[crew]||''))},5000);
try{
var r=await fetch('/api/agents/run',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
var startData=await r.json();
if(!r.ok||!startData.job_id){clearInterval(ticker);updateStatus('\u274C Agent error: '+(startData.error||'Failed to start'));isProcessing=false;_showSend();document.getElementById('sendBtn').disabled=false;return}
var jobId=startData.job_id;
var data=await new Promise(function(resolve,reject){var poll=setInterval(async function(){try{var sr=await fetch('/api/agents/status/'+jobId);var sd=await sr.json();if(sd.status!=='running'){clearInterval(poll);resolve(sd)}}catch(pe){clearInterval(poll);reject(pe)}},4000)});
clearInterval(ticker);if(statusEl)statusEl.parentElement.remove();
var resultMsg;
if(data.status==='complete'){var result=data.result||'';var docMatch=result.match(/https:\/\/docs\.google\.com\/\S+/);if(docMatch){var summary=result.replace(docMatch[0],'').trim();if(!summary)summary='Your report has been generated and saved to Google Docs.';resultMsg='\u2705 **'+crewLabels[crew]+' Complete!** ('+data.elapsed_seconds+'s)\n\n'+summary+'\n\n[Open in Google Docs]('+docMatch[0]+')'}else{resultMsg='\u2705 **'+crewLabels[crew]+' Complete!** ('+data.elapsed_seconds+'s)\n\n'+result}}else{resultMsg='\u274C Agent error: '+(data.error||'Unknown error')}
addMessage('assistant',resultMsg);chatHist.push({role:'assistant',content:resultMsg});saveMessages([{role:'assistant',content:resultMsg}])
}catch(e){clearInterval(ticker);updateStatus('Agent error: '+e.message)}
isProcessing=false;_showSend();document.getElementById('sendBtn').disabled=false;return
}
var fileContext='';var fileNames=[];
for(var i=0;i<pendingFiles.length;i++){var f=pendingFiles[i];fileNames.push(f.name);if(f.type==='text'||f.type==='pdf'){fileContext+='\n\n[DOCUMENT: '+f.name+']\n'+f.content.substring(0,80000)+'\n[END DOCUMENT]'}else if(f.type==='image'){fileContext+='\n\n[IMAGE ANALYSIS of '+f.name+']\n'+f.content.substring(0,80000)+'\n[END IMAGE]'}}
var displayText=text;
if(fileNames.length){displayText=(fileNames.map(function(n){return'\u{1F4CE} '+n}).join('\n'))+'\n\n'+(text||'Please analyze the attached file(s).')}
addMessage('user',displayText);
var imageData=[];
var llmText=(text||'Please analyze the attached file(s).')+fileContext;
chatHist.push({role:'user',content:llmText});clearChips();
saveMessages([{role:'user',content:displayText}]);
var hasImages=imageData.length>0;
isProcessing=true;document.getElementById('sendBtn').disabled=true;_showStop();showTyping();
_currentAbort=new AbortController();
try{
var msgs=[{role:'system',content:SYS}].concat(chatHist);var r;
if(hasImages){
r=await fetch('/api/vision',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({prompt:msgs[msgs.length-1].content||'Describe this image in detail',image:imageData[0]}),signal:_currentAbort.signal});
var data=await r.json();hideTyping();
if(data.response){addMessage('assistant',data.response);chatHist.push({role:'assistant',content:data.response});saveMessages([{role:'assistant',content:data.response}])}
else{addMessage('assistant','Error: '+(data.error||'No response'))}
} else {
r=await fetch('/api/chat',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({messages:msgs,force_search:webSearchEnabled,thinking:thinkingEnabled,stream:true}),signal:_currentAbort.signal});
if(r.status===401||r.status===403){hideTyping();addMessage('assistant','Session expired — redirecting to login...');setTimeout(function(){window.location.href='/auth'},1500);isProcessing=false;_showSend();document.getElementById('sendBtn').disabled=false;return}
hideTyping();
// SSE streaming — render tokens as they arrive
var reader=r.body.getReader();var decoder=new TextDecoder();var fullText='';var bubbleId='stream_'+genId();
var es=document.getElementById('emptyState');if(es)es.remove();
var div=document.createElement('div');div.className='msg assistant';div.innerHTML='<div class="msg-bubble" id="'+bubbleId+'"><div class="thinking-indicator"><div class="thinking-dots"><span></span><span></span><span></span></div>CODEC is thinking...</div></div>';document.getElementById('messages').appendChild(div);
var bubble=document.getElementById(bubbleId);var buf='';var firstToken=true;
while(true){
var chunk=await reader.read();
if(chunk.done)break;
buf+=decoder.decode(chunk.value,{stream:true});
var lines=buf.split('\n');buf=lines.pop();
for(var li=0;li<lines.length;li++){
var line=lines[li].trim();
if(!line.startsWith('data: '))continue;
var payload=line.substring(6);
if(payload==='[DONE]')break;
try{var j=JSON.parse(payload);if(j.token){if(firstToken){bubble.innerHTML='';firstToken=false}fullText+=j.token;bubble.innerHTML=formatMsg(fullText);scrollBottom()}if(j.error){fullText+='\n\nError: '+j.error}}catch(pe){}
}
}
if(fullText){div.remove();addMessage('assistant',fullText);chatHist.push({role:'assistant',content:fullText});saveMessages([{role:'assistant',content:fullText}])}
else{bubble.innerHTML='<em style="color:var(--text-dim)">No response</em>'}
}
}catch(e){
hideTyping();
if(e.name==='AbortError'){
// User clicked stop — keep partial response
if(typeof fullText!=='undefined'&&fullText){chatHist.push({role:'assistant',content:fullText});saveMessages([{role:'assistant',content:fullText}])}
}else{addMessage('assistant','Error: '+e.message)}
}
_currentAbort=null;isProcessing=false;_showSend();document.getElementById('sendBtn').disabled=false
}
function handleKey(e){if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();sendMessage()}var ta=e.target;ta.style.height='auto';ta.style.height=Math.min(ta.scrollHeight,120)+'px'}
function toggleMic(){
var btn=document.getElementById('micBtn');
var input=document.getElementById('chatInput');
if(isRecording){if(recognition)recognition.stop();return}
if(!('webkitSpeechRecognition' in window)&&!('SpeechRecognition' in window)){showToast('Speech recognition not supported');return}
var SR=window.SpeechRecognition||window.webkitSpeechRecognition;
recognition=new SR();recognition.lang='en-US';recognition.interimResults=true;recognition.continuous=false;
recognition.onresult=function(e){
var transcript='';for(var i=0;i<e.results.length;i++){transcript+=e.results[i][0].transcript}
input.value=transcript;
if(e.results[e.results.length-1].isFinal){
isRecording=false;btn.classList.remove('recording');
if(transcript.trim()){setTimeout(function(){sendMessage()},150)}
}
};
recognition.onerror=function(e){isRecording=false;btn.classList.remove('recording');if(e.error!=='no-speech')showToast('Mic error: '+e.error)};
recognition.onend=function(){isRecording=false;btn.classList.remove('recording')};
recognition.start();isRecording=true;btn.classList.add('recording');
input.placeholder='Listening...';
var origPlaceholder='Message CODEC...';
var clearPlaceholder=function(){input.placeholder=origPlaceholder};
recognition.addEventListener('end',clearPlaceholder,{once:true})
}
async function handleUpload(e){
var files=e.target.files;
for(var i=0;i<files.length;i++){
var file=files[i];
if(file.type.startsWith('image/')){
var tid='loading_'+genId();var chips=document.getElementById('fileChips');
var chip=document.createElement('div');chip.className='file-chip loading';chip.id=tid;
chip.innerHTML='<span class="fc-icon">\u{1F4F7}</span><span class="fc-name">'+escHtml(file.name)+' (analyzing...)</span>';chips.appendChild(chip);
(function(theFile,loadId){var reader=new FileReader();reader.onload=async function(){var b64=reader.result.split(',')[1];try{var r=await fetch('/api/upload_image',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({filename:theFile.name,data:b64})});var data=await r.json();var el=document.getElementById(loadId);if(el)el.remove();if(data.text){addFileChip(theFile.name,'[IMAGE ANALYSIS: '+data.text+']','image')}else{addFileChip(theFile.name,'[Image upload failed]','image')}}catch(err){var el=document.getElementById(loadId);if(el)el.remove();addFileChip(theFile.name,'[Image error]','image')}};reader.readAsDataURL(theFile)})(file,tid);continue
}else if(/\.(pdf|docx|csv|tsv)$/i.test(file.name)){
(function(theFile){
var tempId='loading_'+genId();var chips=document.getElementById('fileChips');
var chip=document.createElement('div');chip.className='file-chip loading';chip.id=tempId;
var fIcon=/\.pdf$/i.test(theFile.name)?'\u{1F4C4}':'\u{1F4CE}';
var fType=/\.pdf$/i.test(theFile.name)?'pdf':'text';
chip.innerHTML='<span class="fc-icon">'+fIcon+'</span><span class="fc-name">'+escHtml(theFile.name)+' (extracting...)</span>';chips.appendChild(chip);
var rd=new FileReader();
rd.onload=async function(){
var base64=rd.result.split(',')[1];
try{
var r=await fetch('/api/upload',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({filename:theFile.name,data:base64})});
var el=document.getElementById(tempId);if(el)el.remove();
if(!r.ok){var errText='';try{var ej=await r.json();errText=ej.error||r.status}catch(e){errText='Server error ('+r.status+')'}addFileChip(theFile.name,'[Upload failed: '+errText+']',fType);return}
var data=await r.json();
if(data.text&&data.text.trim().length>10){addFileChip(theFile.name,data.text,fType)}
else if(data.error){addFileChip(theFile.name,'[Error: '+data.error+']',fType)}
else{addFileChip(theFile.name,'[Could not extract text]',fType)}
}catch(err){var el=document.getElementById(tempId);if(el)el.remove();addFileChip(theFile.name,'[Upload error: '+err.message+']',fType)}
};
rd.readAsDataURL(theFile);
})(file);
}else{try{var text=await file.text();addFileChip(file.name,text,'text')}catch(err){addFileChip(file.name,'[Cannot read file]','text')}}
}
e.target.value=''
}
var appEl=document.getElementById('appContainer');
['dragenter','dragover'].forEach(function(ev){appEl.addEventListener(ev,function(e){e.preventDefault();appEl.classList.add('dragover')})});
['dragleave','drop'].forEach(function(ev){appEl.addEventListener(ev,function(e){e.preventDefault();appEl.classList.remove('dragover')})});
appEl.addEventListener('drop',function(e){if(e.dataTransfer.files.length){var dt=new DataTransfer();for(var i=0;i<e.dataTransfer.files.length;i++)dt.items.add(e.dataTransfer.files[i]);document.getElementById('fileUp').files=dt.files;handleUpload({target:document.getElementById('fileUp')})}});
document.getElementById('chatInput').addEventListener('input',function(){this.style.height='auto';this.style.height=Math.min(this.scrollHeight,120)+'px'});
var _toolsLoaded=false;
async function loadAgentTools(){
try{
var r=await fetch('/api/agents/tools');
if(!r.ok){
// Retry once — session token might not have been injected on first try
await new Promise(function(res){setTimeout(res,500)});
r=await fetch('/api/agents/tools');
}
var data=await r.json();
if(!data.tools||!data.tools.length){document.getElementById('abToolGrid').innerHTML='<span style="font-size:10px;color:var(--text-dim)">No tools available</span>';return}
var grid=document.getElementById('abToolGrid');grid.innerHTML='';
data.tools.forEach(function(t){var label=document.createElement('label');label.className='ab-tool';label.title=t.description;label.innerHTML='<input type="checkbox" name="abt" value="'+escHtml(t.name)+'" checked> '+escHtml(t.name.replace(/_/g,' '));grid.appendChild(label)});
document.getElementById('abToolCount').textContent='('+data.tools.length+')';_toolsLoaded=true
}catch(e){document.getElementById('abToolGrid').innerHTML='<span style="font-size:10px;color:var(--danger)">Failed to load tools: '+escHtml(e.message)+'</span>';console.error('loadAgentTools error:',e)}
}
function getSelectedTools(){return Array.from(document.querySelectorAll('#abToolGrid input[name="abt"]:checked')).map(function(c){return c.value})}
async function saveCustomAgent(){
var nameInput=document.getElementById('agentName');
var nameVal=nameInput.value.trim();
// Auto-name if empty or default
if(!nameVal||nameVal==='Custom Agent'){
try{var lr=await fetch('/api/agents/custom/list');var ld=await lr.json();var count=(ld.agents||[]).length;nameVal='Agent '+(count+1);nameInput.value=nameVal}catch(e){nameVal='Agent 1';nameInput.value=nameVal}
}
var body={name:nameVal,role:document.getElementById('agentRole').value.trim(),tools:getSelectedTools(),max_iterations:parseInt(document.getElementById('agentMaxIter').value||'8')};
try{
var r=await fetch('/api/agents/custom/save',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});
var d=await r.json();
console.log('Save response:',JSON.stringify(d));
if(d.error){addMessage('assistant','Save error: '+d.error);return}
if(d.saved){
addMessage('assistant','Agent **'+body.name+'** saved successfully');
console.log('Calling loadSavedAgentList...');
await loadSavedAgentList();
console.log('loadSavedAgentList completed');
// Also verify the dropdown state after load
var sel=document.getElementById('savedAgentSelect');
console.log('Dropdown options after load:',sel?sel.options.length:'NO ELEMENT');
}else{addMessage('assistant','Save failed — unexpected response')}
}catch(e){console.error('Save error:',e);addMessage('assistant','Save error: '+e.message)}
}
async function loadSavedAgentList(){
var sel=document.getElementById('savedAgentSelect');
if(!sel)return;
try{
var r=await fetch('/api/agents/custom/list');
var txt=await r.text();
var d=JSON.parse(txt);
var agents=d.agents||[];
// Clear and rebuild dropdown
while(sel.options.length>0)sel.remove(0);
var defOpt=document.createElement('option');
defOpt.value='';
defOpt.textContent=agents.length>0?'Load saved ('+agents.length+')...':'No saved agents';
sel.appendChild(defOpt);
for(var i=0;i<agents.length;i++){
var opt=document.createElement('option');
opt.value=JSON.stringify(agents[i]);
opt.textContent=agents[i].name||agents[i].id||'Agent '+(i+1);
sel.appendChild(opt);
}
}catch(e){
while(sel.options.length>0)sel.remove(0);
var errOpt=document.createElement('option');
errOpt.value='';errOpt.textContent='Error loading agents';
sel.appendChild(errOpt);
}
}
function loadSavedAgent(json){
if(!json)return;try{var a=JSON.parse(json);if(a.name)document.getElementById('agentName').value=a.name;if(a.role)document.getElementById('agentRole').value=a.role;if(a.max_iterations)document.getElementById('agentMaxIter').value=a.max_iterations;if(a.tools&&_toolsLoaded){document.querySelectorAll('#abToolGrid input[name="abt"]').forEach(function(cb){cb.checked=a.tools.includes(cb.value)})}}catch(e){}
}
async function deleteSelectedAgent(){
var sel=document.getElementById('savedAgentSelect');var json=sel.value;if(!json){addMessage('assistant','Select an agent to delete first');return}
try{var a=JSON.parse(json);var r=await fetch('/api/agents/custom/delete',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:a.id})});var d=await r.json();if(d.deleted){addMessage('assistant','Agent **'+(a.name||a.id)+'** deleted');await loadSavedAgentList()}else{addMessage('assistant','Delete failed: '+(d.error||'unknown'))}}catch(e){addMessage('assistant','Delete error: '+e.message)}
}
function lockSession(){fetch('/api/auth/logout',{method:'POST'}).then(function(){document.cookie='codec_session=;path=/;max-age=0;SameSite=Lax'+(location.protocol==='https:'?';Secure':'');window.location.href='/auth'})}
// ── Header icons (matching dashboard) ──
var voiceReplyEnabled=localStorage.getItem('codec-voice')==='true';
function toggleVoiceReply(){voiceReplyEnabled=!voiceReplyEnabled;localStorage.setItem('codec-voice',voiceReplyEnabled);updateVoiceIcon()}
function updateVoiceIcon(){var x1=document.getElementById('muteX1'),x2=document.getElementById('muteX2');if(voiceReplyEnabled){x1.style.display='none';x2.style.display='none'}else{x1.style.display='';x2.style.display=''}}
updateVoiceIcon();
async function takeScreenshot(){try{window.open('/api/screenshot?'+Date.now(),'_blank')}catch(e){}}
// ── Server Photo (Mac webcam) ──
function takeServerPhoto() {
var btn = document.getElementById('photoBtn');
btn.style.borderColor = 'var(--accent)';
addMsg('system', 'Capturing from Mac webcam...');
fetch('/api/webcam/snapshot?_t=' + Date.now() + _getAuthParam()).then(function(r) { return r.json(); }).then(function(d) {
btn.style.borderColor = '';
if (d.error) { addMsg('system', 'Error: ' + d.error); return; }
addMsg('system', 'Photo saved: ' + d.filename);
var img = document.getElementById('screenImg');
img.src = 'data:image/jpeg;base64,' + d.image;
document.getElementById('screenModal').classList.add('show');
fetch('/api/webcam', { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ image: d.image, analyze: true, prompt: 'Describe what you see in this photo. Be concise.' })
}).then(function(r2) { return r2.json(); }).then(function(d2) {
if (d2.analysis) addMsg('assistant', d2.analysis);
});
}).catch(function(e) { btn.style.borderColor = ''; addMsg('system', 'Camera error: ' + e.message); });
}
function closeScreenshot() { document.getElementById('screenModal').classList.remove('show'); }
document.addEventListener('keydown', function(e) { if (e.key === 'Escape') closeScreenshot(); });
// ── Live Webcam PIP (Mac MJPEG stream) ──
var _pipDrag = { active: false, x: 0, y: 0 };
function _getAuthParam(first) {
var m = document.cookie.match(/codec_session=([^;]+)/);
return m ? (first ? '?s=' : '&s=') + m[1] : '';
}
function toggleWebcamPip() {
var pip = document.getElementById('webcamPip');
if (pip.style.display === 'block') { closeWebcamPip(); return; }