-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathcodec_chat.html
More file actions
1943 lines (1848 loc) · 129 KB
/
codec_chat.html
File metadata and controls
1943 lines (1848 loc) · 129 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="/favicon.png">
<link rel="apple-touch-icon" href="/favicon.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: #18181b; --surface-2: #1f1f22; --surface-3: #27272a;
--border: #2a2a2f; --border-hover: #3a3a40;
--text: #ececec; --text-muted: #9a9aa0; --text-dim: #6a6a70;
/* 2026 refresh: keep CODEC orange identity but warmer + calmer (was pure #E8711A) */
--accent: #d97757; --accent-hover: #e08766; --accent-dim: rgba(217,119,87,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:#faf8f5;--surface:#fff;--surface-2:#f2eee8;--surface-3:#ebe6df;--border:#e2ddd5;--border-hover:#c8c2b8;--text:#18181b;--text-muted:#52525b;--text-dim:#71717a;--bg2:#fff;--bg3:#f2eee8;--bg4:#ebe6df;--fg:#18181b;--fg2:#52525b;--fg3:#71717a;--bd:#e2ddd5;--accent:#b85a3a;--accent-hover:#a04d31;--accent-dim:rgba(184,90,58,0.08)}
*{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{display:flex;align-items:center;border-bottom:1px solid var(--border);transition:background .15s}
.sidebar-item:hover{background:var(--surface-2)}
.sidebar-item .si-main{flex:1;min-width:0;padding:10px 8px 10px 16px;cursor:pointer}
.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}
.si-del{flex-shrink:0;background:none;border:none;cursor:pointer;padding:8px 12px 8px 4px;font-size:14px;opacity:0;transition:opacity .15s;color:var(--text-dim)}
.sidebar-item:hover .si-del{opacity:1}
.si-del:hover{color:#e55;opacity:1!important}
.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"/><line id="muteX1" x1="4" y1="4" x2="20" y2="20" stroke-width="2.5" style="display:none"/><line id="muteX2" x1="4" y1="20" x2="20" y2="4" stroke-width="2.5" style="display:none"/></svg><span class="sp-item-label" style="flex:none">Voice Replies</span><span id="voiceState" style="font-size:11px;font-weight:700;padding:2px 8px;border-radius:4px"></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>
<button class="mode-btn" onclick="setMode('project')" id="modeProjectBtn" title="Drop a project — autonomous plan-and-build mode"><svg class="ico" viewBox="0 0 24 24" style="width:14px;height:14px"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="5"/><line x1="12" y1="2" x2="12" y2="22"/><line x1="2" y1="12" x2="22" y2="12"/></svg>Project</button>
<button class="mode-btn" id="speakToggle" onclick="toggleVoiceReply();updateSpeakToggle()" title="Voice replies — CODEC speaks responses back via Kokoro"><svg class="ico ico-sm" 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"/><line id="speakMuteX1" x1="4" y1="4" x2="20" y2="20" stroke-width="2.5" style="display:none"/></svg>Speak</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){var bytes=new Uint8Array(buf),CHUNK=8192,str='';for(var i=0;i<bytes.length;i+=CHUNK){str+=String.fromCharCode.apply(null,bytes.subarray(i,i+CHUNK))}return btoa(str)}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 9 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 _copyFallback(text){
try{
var ta=document.createElement('textarea');
ta.value=text;
ta.setAttribute('readonly','');
ta.style.position='fixed';
ta.style.top='0';ta.style.left='0';
ta.style.opacity='0';ta.style.pointerEvents='none';
document.body.appendChild(ta);
ta.focus();ta.select();ta.setSelectionRange(0,ta.value.length);
var ok=document.execCommand('copy');
document.body.removeChild(ta);
return ok;
}catch(e){return false}
}
function copyMsgText(text,btn){
function ok(){btn.classList.add('copied');showToast('Copied');setTimeout(function(){btn.classList.remove('copied')},1500)}
function fail(){if(_copyFallback(text)){ok()}else{showToast('Copy failed')}}
if(navigator.clipboard&&navigator.clipboard.writeText){
navigator.clipboard.writeText(text).then(ok,fail).catch(fail)
}else{fail()}
}
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 pBtn=document.getElementById('modeProjectBtn');
if(pBtn)pBtn.classList.toggle('active',mode==='project');
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...'};
// If the user toggles to chat mode AFTER an agent already produced a
// report, the report sits in chatHist as the last assistant message —
// any follow-up chat call carries it forward via the messages[] array
// sent to /api/chat, so the LLM has the full report as context. Hint
// that explicitly in the placeholder so the user knows they can ask
// follow-up questions.
var hasAgentReport=mode==='chat'&&chatHist.some(function(m){return m.role==='assistant'&&typeof m.content==='string'&&m.content.indexOf('Complete!')!==-1});
var ph;
if(mode==='research')ph=hints[crew]||'Enter crew task...';
else if(mode==='project')ph='Drop your project here — describe what you want CODEC to build...';
else ph=hasAgentReport?'Ask follow-up about the report...':'Message CODEC...';
document.getElementById('chatInput').placeholder=ph;
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')}
// Phase 3.5 Step 11: Project-mode on-screen instructions panel
var pPanel=document.getElementById('projectModePanel');
if(mode==='project'){
if(!pPanel){
pPanel=document.createElement('div');
pPanel.id='projectModePanel';
pPanel.style.cssText='margin:12px 16px 8px;padding:14px 16px;background:rgba(167,139,250,0.08);border:1px solid var(--accent,#a78bfa);border-radius:10px;font-size:13px;line-height:1.5';
pPanel.innerHTML=
'<div style="font-weight:600;color:var(--accent,#a78bfa);margin-bottom:6px">Project mode — autonomous plan-and-build</div>'+
'<div style="color:var(--text-dim);margin-bottom:8px">Drop a project below. CODEC drafts a plan + permission manifest, you approve once, then codec-agent-runner works through it autonomously (Qwen-3.6 + skills). Updates post back to this thread.</div>'+
'<div style="color:var(--text-dim);font-size:12px">Examples: <em>"Build a Telegram bot that monitors Marbella property listings under €500k"</em> · <em>"Watch EUR/USD intraday vol and ping me when 30-min realized vol crosses 0.4%"</em> · <em>"Plan the launch of [product] over 6 weeks with weekly milestones"</em></div>';
}
var msgsEl=document.getElementById('messages');
if(msgsEl&&!document.getElementById('projectModePanel')){
msgsEl.parentNode.insertBefore(pPanel,msgsEl);
}
}else if(pPanel){
pPanel.remove();
}
// Live-switch behaviour: only wipe the session when the chat is EMPTY.
// If there's already a conversation (e.g. an agent just returned a deep-
// research report), keep chatHist intact so the user can flip into chat
// mode and continue asking follow-up questions about the report. The
// explicit "+" / new-chat button remains the way to start fresh.
if(changed&&!isProcessing&&chatHist.length===0)startNewSession();
// One-shot toast on first toggle to chat mode after a report — helps
// the user discover that context is preserved.
if(changed&&mode==='chat'&&hasAgentReport){
try{showToast('Context preserved — ask follow-up questions about the report')}catch(e){}
}
}
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();localStorage.setItem('codec-chat-session',sessionId);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>'}
// PR #39: persist sessionId across page reloads. If a previous session
// exists, load it on boot so the user lands back on the same chat (with
// any project plan cards rehydrated). Falls back to a fresh session if
// the previous one's GET returns empty.
(function bootSession(){
var saved=localStorage.getItem('codec-chat-session');
if(!saved){startNewSession();return}
// Optimistically load \u2014 if the session is empty/missing, we'll start fresh
fetch('/api/qchat/session/'+saved).then(function(r){
return r.ok?r.json():[];
}).then(function(data){
if(data&&data.length>0){
// Use the saved id and replay history through the same code path
// sidebar uses (so the plan-card rehydration runs once the messages
// are in the DOM).
sessionId=saved;
var es=document.getElementById('emptyState');if(es)es.remove();
document.getElementById('messages').innerHTML='';
chatHist=[];
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||''});
}
rehydrateAgentPlanCards().then(scrollBottom);
}else{
startNewSession();
}
}).catch(function(){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+'><div class="si-main" onclick="loadSession(\''+s.id+'\')"><div class="si-title">'+escHtml(s.title)+'</div><div class="si-time">'+ts+'</div></div><button class="si-del" onclick="deleteSession(event,\''+s.id+'\')" title="Delete">🗑</button></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;localStorage.setItem('codec-chat-session',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||''})}
// PR #39: any assistant message with [CODEC_AGENT_PLAN:<id>] marker
// gets replaced by the live plan card (fetched from /api/agents/<id>).
await rehydrateAgentPlanCards();
scrollBottom()
}catch(e){}
}
function newChat(){closeSidebar();startNewSession()}
async function deleteSession(evt, sid){
evt.stopPropagation();
if(!confirm('Delete this conversation?'))return;
try{
await fetch('/api/qchat/session/'+sid,{method:'DELETE'});
if(sid===sessionId){startNewSession()}
loadSidebarHistory();
}catch(e){console.error('deleteSession failed',e)}
}
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>':'';
// ── Speak button per assistant message — manual TTS playback regardless of global toggle
var speakBtn=role==='assistant'?'<button class="msg-speak" onclick="speakMessage(decodeURIComponent(\''+enc+'\'),this)" title="Speak"><svg class="ico ico-sm" 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></button>':'';
div.innerHTML=copyBtn+editBtn+regenBtn+speakBtn+'<div class="msg-bubble">'+formatMsg(content)+'</div><div class="msg-time">'+time+'</div>';
document.getElementById('messages').appendChild(div);
scrollBottom();
// ── Auto-speak via Kokoro when global "Voice Replies" toggle is ON
if (role === 'assistant' && voiceReplyEnabled) {
var plain = String(content).replace(/[`*_#>\[\]()]/g,'').replace(/\s+/g,' ').trim();
if (plain) speakMessage(plain);
}
}
// Play Kokoro TTS for any text — used by per-message Speak button + voice-reply autoplay
var _ttsAudio = null;
function speakMessage(text, btn){
if (!text) return;
// Stop any in-flight playback (prevents pile-up)
if (_ttsAudio) { try { _ttsAudio.pause(); } catch(e){} _ttsAudio = null; }
// Trim to ~500 chars (TTS endpoint caps internally too)
var snippet = String(text).slice(0, 500);
var url = '/api/tts?text=' + encodeURIComponent(snippet);
_ttsAudio = new Audio(url);
if (btn) btn.classList.add('speaking');
_ttsAudio.onended = function(){ if (btn) btn.classList.remove('speaking'); _ttsAudio = null; };
_ttsAudio.onerror = function(){ if (btn) btn.classList.remove('speaking'); _ttsAudio = null; };
_ttsAudio.play().catch(function(){ if (btn) btn.classList.remove('speaking'); });
}
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
// ───────────────────────────────────────────────────────────────────────────
// PR #39 — Agent plan persistence (Project mode)
// ───────────────────────────────────────────────────────────────────────────
// Why this exists: Phase 3.5 saved only the bare string "Project drafted:
// agent_xxx" to chat history; the inline card with approve/reject/view-plan
// buttons lived only in the DOM. Reloading the chat lost the card.
//
// Approach: persist a marker token `[CODEC_AGENT_PLAN:<id>]` inside the
// assistant message content. On chat session load, scan rendered messages,
// detect the marker, fetch the agent state, and replace the text bubble
// with the same card the live flow renders.
//
// The card's button callbacks (approveAgentInChat / rejectAgentInChat /
// viewAgentPlan) only need agent_id, so reload-time rendering matches the
// live render exactly. Status-aware buttons (e.g. "Resume" on
// blocked_on_qwen) come for free via the agent state object.
var AGENT_PLAN_MARKER_RE=/\[CODEC_AGENT_PLAN:(agent_[a-z0-9]+)\]/;
function extractAgentIdFromMessage(content){
if(!content||typeof content!=='string')return null;
var m=content.match(AGENT_PLAN_MARKER_RE);
return m?m[1]:null;
}
function renderAgentPlanCard(agentId,agentInfo){
// agentInfo accepts two shapes:
// - POST /api/agents result: {agent_id, status, project_dir} (flat)
// - GET /api/agents/<id>: {manifest: {agent_id, status, ...}, plan, state, grants}
// Normalize both into the same view-model.
agentInfo=agentInfo||{};
var manifest=agentInfo.manifest||agentInfo; // GET wraps in .manifest, POST is flat
var status=manifest.status||'';
var reason=manifest.status_reason||'';
var projectDir=manifest.project_dir||'';
var folderHtml='';
if(projectDir){
folderHtml='<div style="margin:6px 0 8px;padding:8px 10px;background:rgba(167,139,250,0.08);border:1px solid var(--accent,#a78bfa);border-radius:6px;font-size:12px">'+
'<div style="font-weight:600;color:var(--accent,#a78bfa);margin-bottom:2px">Project folder</div>'+
'<code style="font-size:11px;word-break:break-all">'+escHtml(projectDir)+'</code>'+
'<div style="color:var(--text-dim);margin-top:4px;font-size:11px">Open this folder in your IDE to see the agent\'s files as they\'re created. (cmd+click to open in Finder)</div>'+
'</div>';
}
// Status-aware action buttons. draft_pending / awaiting_approval =
// approve+reject+view; running/done/aborted = view-only; blocked_* =
// resume+abort+view.
var buttonsHtml='';
var isPendingApproval=(!status)||status==='draft_pending'||status==='awaiting_approval';
var isBlocked=status&&status.indexOf('blocked_')===0;
var isTerminal=status==='done'||status==='aborted'||status==='plan_failed';
if(isPendingApproval){
buttonsHtml=
'<button onclick="approveAgentInChat(\''+agentId+'\',event)" style="padding:6px 14px;background:var(--accent,#a78bfa);color:#000;border:none;border-radius:6px;cursor:pointer;font-size:12px;font-weight:600">Approve plan</button>'+
'<button onclick="rejectAgentInChat(\''+agentId+'\',event)" style="padding:6px 14px;background:transparent;color:var(--text);border:1px solid var(--border,#2a2a30);border-radius:6px;cursor:pointer;font-size:12px">Reject</button>'+
'<button onclick="viewAgentPlan(\''+agentId+'\',event)" style="padding:6px 14px;background:transparent;color:var(--text);border:1px solid var(--border,#2a2a30);border-radius:6px;cursor:pointer;font-size:12px">View plan</button>';
}else if(isBlocked){
buttonsHtml=
'<button onclick="viewAgentPlan(\''+agentId+'\',event)" style="padding:6px 14px;background:var(--accent,#a78bfa);color:#000;border:none;border-radius:6px;cursor:pointer;font-size:12px;font-weight:600">View plan + resolve</button>'+
'<button onclick="rejectAgentInChat(\''+agentId+'\',event)" style="padding:6px 14px;background:transparent;color:var(--text);border:1px solid var(--border,#2a2a30);border-radius:6px;cursor:pointer;font-size:12px">Abort</button>';
}else{
buttonsHtml=
'<button onclick="viewAgentPlan(\''+agentId+'\',event)" style="padding:6px 14px;background:transparent;color:var(--text);border:1px solid var(--border,#2a2a30);border-radius:6px;cursor:pointer;font-size:12px">View plan</button>';
}
var statusLine='';
if(status){
var color=isTerminal?'var(--text-dim)':(isBlocked?'#f87171':'#10b981');
var label=status.replace(/_/g,' ');
statusLine='<div style="margin-bottom:6px;font-size:11px;color:'+color+'">status: <strong>'+escHtml(label)+'</strong>'+(reason?' ('+escHtml(reason)+')':'')+'</div>';
}
var subline=isPendingApproval
?'A plan with a permission manifest has been written. Review and approve to let the agent run autonomously.'
:(isTerminal?'Agent finished. View plan to see what ran.':'Agent state shown above; click View plan for live progress.');
return'<div style="font-weight:600;margin-bottom:6px">Project drafted</div>'+
'<div style="margin-bottom:6px">agent_id: <code>'+escHtml(agentId)+'</code></div>'+
statusLine+
folderHtml+
'<div style="color:var(--text-dim);font-size:12px;margin-bottom:8px">'+subline+'</div>'+
'<div style="display:flex;gap:8px;flex-wrap:wrap">'+buttonsHtml+'</div>';
}
async function rehydrateAgentPlanCards(){
// Called after loadSession finishes rendering text messages. Scan
// assistant bubbles for the marker, fetch each agent in parallel,
// replace the bubble with the rendered card. Failures fall back
// to leaving the marker text visible (so the user knows something
// is missing rather than seeing nothing).
var msgs=document.querySelectorAll('#messages .msg.assistant .msg-bubble');
var jobs=[];
for(var i=0;i<msgs.length;i++){
var bubble=msgs[i];
var agentId=extractAgentIdFromMessage(bubble.textContent||'');
if(!agentId)continue;
jobs.push((function(b,id){
return fetch('/api/agents/'+id).then(function(r){
return r.ok?r.json():null;
}).then(function(info){
// GET /api/agents/<id> returns {manifest, plan, state, grants}.
// Treat presence of manifest.agent_id as "agent exists".
var ok=info&&info.manifest&&info.manifest.agent_id;
if(ok){
b.innerHTML=renderAgentPlanCard(id,info);
var st=(info.manifest||{}).status||'';
if(['running','approved','paused','blocked_on_permission','blocked_on_qwen'].indexOf(st)>=0){
// Resume live polling if agent is still running
_startAgentPoller(id);
} else if(['completed','aborted','crashed'].indexOf(st)>=0){
// Agent finished — catch up on any messages the poller may have missed
_injectMissedAgentMessages(id);
}
}else{
// Agent missing (e.g. manifest deleted); show inline notice
// but keep the agent_id visible so the user knows what's gone.
b.innerHTML='<div style="font-weight:600;margin-bottom:4px">Project: '+escHtml(id)+'</div>'+
'<div style="color:var(--text-dim);font-size:12px">Agent state not found — manifest may have been removed.</div>';
}
}).catch(function(){/* keep raw text on error */});
})(bubble,agentId));
}
if(jobs.length){await Promise.all(jobs)}
}
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';
// Project mode → POST /api/agents (Step 8 plan dispatch)
// OR if there's an active agent in this thread, route the message to that agent
// (status queries, mid-run instructions). User explicitly exits with × on chip.
if(chatMode==='project'){
if(!text)return;
addMessage('user',text);
chatHist.push({role:'user',content:text});
saveMessages([{role:'user',content:text}]);
isProcessing=true;document.getElementById('sendBtn').disabled=true;
// ── Continuity branch: route to active agent if one is bound to this thread
if(_activeAgentId){
var replyDiv=document.createElement('div');
replyDiv.className='msg assistant';
replyDiv.innerHTML='<div class="msg-bubble" style="opacity:.7"><em>Sending to '+escHtml(_activeAgentId.slice(0,12))+'…</em></div>';
document.getElementById('messages').appendChild(replyDiv);
scrollBottom();
try{
var rr=await fetch('/api/agents/'+encodeURIComponent(_activeAgentId)+'/messages',{
method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({body:text})
});
if(rr.status===404){
// Agent vanished (deleted / not found) — clear binding, fall through
replyDiv.querySelector('.msg-bubble').innerHTML='<span style="color:var(--text-muted)">Agent no longer exists — exited conversation.</span>';
setActiveAgent(null);
isProcessing=false;document.getElementById('sendBtn').disabled=false;_showSend();
return;
}
var rd=await rr.json();
if(rd.ok){
replyDiv.querySelector('.msg-bubble').innerHTML=