Repository navigation
Expand file tree
/
Copy pathcodec_chat.html
More file actions
3556 lines (3445 loc) · 251 KB
/
Copy pathcodec_chat.html
File metadata and controls
3556 lines (3445 loc) · 251 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="theme-color" content="#121215">
<script>/* Theme before first paint, so the page never flashes dark: same key and attribute as applyTheme() below. */try{(function(){function _lsGet(k){try{return localStorage.getItem(k)}catch(e){return null}}var t=_lsGet('codec-theme');if(t!=='light'&&t!=='dark'){try{t=matchMedia('(prefers-color-scheme: light)').matches?'light':'dark'}catch(e){t='dark'}}document.documentElement.setAttribute('data-theme',t);var m=document.querySelector('meta[name="theme-color"]');if(m)m.content=t==='light'?(m.getAttribute('data-light')||'#faf8f5'):'#121215'})()}catch(e){}</script>
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
<meta name="mobile-web-app-capable" content="yes">
<title>CODEC Deep Chat</title>
<!-- Tab icon inline: behind Cloudflare Access a /favicon.png request gets the login page. -->
<link rel="icon" type="image/png" href="data:image/png;base64,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">
<link rel="apple-touch-icon" href="/static/icons/apple-touch-icon.png">
<link rel="manifest" href="/manifest.json" crossorigin="use-credentials">
<link rel="stylesheet" href="/static/codec.css?v=69a2bc56">
<style>
:root {
--bg: #121215; --surface: #18181b; --surface-2: #1f1f22; --surface-3: #27272a;
--border: #2a2a2f; --border-strong: #3a3a40;
--text: #ececec; --text-muted: #9a9aa0; --text-dim: #8b8b92;
/* 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); --on-accent: #121215;
--danger: #ef4444; --success: #22c55e; --warning: #f59e0b; --info: #60a5fa;
/* Muted sage green for agent "running" states — pairs with the warm orange theme instead of the harsh bright green */
--running: #4f9a7d; --blocked: #d98a5a;
--font-sans: 'IBM Plex Sans', -apple-system, BlinkMacSystemFont, sans-serif;
--font-mono: 'IBM Plex 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);
}
[data-theme=light]{--bg:#faf8f5;--surface:#fff;--surface-2:#f2eee8;--surface-3:#ebe6df;--border:#e2ddd5;--border-strong:#c8c2b8;--text:#18181b;--text-muted:#52525b;--text-dim:#71717a;--accent:#b85a3a;--accent-hover:#a04d31;--accent-dim:rgba(184,90,58,0.08);--on-accent:#ffffff;--success:#15803d;--danger:#dc2626;--warning:#b45309;--info:#2563eb}
*{margin:0;padding:0;box-sizing:border-box}
html{background:var(--bg)}
html,body{font-family:var(--font-sans);background:var(--bg);color:var(--text);height:100%;overflow:hidden;-webkit-tap-highlight-color:transparent}
/* The shell (static/codec-shell.js) sizes this column: it is the page's .cs-main. */
.app{display:flex;flex-direction:column;position:relative;overflow:hidden}
.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}
/* ── Messages ── */
/* Reading column: 760px, centred. The side padding (16px on the phone) keeps the scrollbar at the window edge. */
.messages{flex:1;min-height:0;overflow-y:auto;padding:14px max(16px,calc((100% - 760px) / 2));-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}}
/* The user's text is a soft right-aligned bubble. An assistant reply (.md, rendered Markdown) has no
bubble and fills the column; cards (plans, questions, status, images) keep theirs. */
.msg.user{max-width:none;display:flex;flex-direction:column;align-items:flex-end}
.msg.assistant{margin-right:auto;max-width:100%}
.msg-bubble{padding:10px 14px;border-radius:14px;line-height:var(--lh-16);font-size:var(--fs-16);word-wrap:break-word;white-space:pre-wrap}
.msg-bubble.md{white-space:normal}
.msg.user .msg-bubble{max-width:80%;padding:10px 16px;border-radius:var(--radius-20);background:var(--surface-2);color:var(--text)}
.msg.assistant .msg-bubble{background:var(--surface-2);color:var(--text);border:1px solid var(--border);border-bottom-left-radius:4px}
.msg.assistant .msg-bubble.md{background:transparent;border:0;border-radius:0;padding:0}
.msg-bubble.md>.thinking-indicator{padding:4px 0}
.gen-img{display:block;max-width:100%;height:auto;border-radius:10px;margin-top:8px;border:1px solid var(--border)}
.gen-dl{display:inline-block;margin-top:6px;font-size:calc(12px * var(--fs-scale));color:var(--accent);text-decoration:none}
.img-status{font-size:calc(13px * var(--fs-scale));color:var(--text-muted);white-space:normal}
.img-cancel{margin-top:6px;padding:3px 10px;font-size:calc(12px * var(--fs-scale));border:1px solid var(--border);border-radius:6px;background:transparent;color:var(--text-dim);cursor:pointer}
#imageOpts{display:none;align-items:center;gap:6px}
#imageOpts select{background:var(--surface-2);border:1px solid var(--border);color:var(--text-muted);font-family:var(--font-mono);font-size:calc(12px * var(--fs-scale));border-radius:var(--radius-sm);padding:5px 9px;}
#imageOpts label{display:flex;align-items:center;gap:4px;font-size:calc(12px * var(--fs-scale));color:var(--text-dim);cursor:pointer}
.msg-stats{font-size:var(--fs-12);color:var(--text-dim);letter-spacing:.3px;margin-left:8px;cursor:default}
.msg-time{font-family:var(--font-mono);font-size:var(--fs-12);color:var(--text-dim);margin-top:3px;padding:0 4px}
.msg.user .msg-time{text-align:right}
/* ── Message action row: timestamp + regenerate / edit / copy / speak ──
One inline row beneath each bubble (replaces the old corner-floating
absolute buttons that clipped off-screen and left .msg-speak unstyled). */
.msg-meta{display:flex;align-items:center;gap:1px;margin-top:4px;
opacity:.5;transition:opacity .15s}
.msg:hover .msg-meta{opacity:1}
.msg.user .msg-meta{justify-content:flex-end}
.msg-meta .msg-time{margin-top:0}
.msg-act{
background:none;border:none;color:var(--text-dim);cursor:pointer;
width:32px;height:32px;border-radius:8px;padding:0;
display:inline-flex;align-items:center;justify-content:center;
transition:color .12s,background .12s;
}
.msg-act .ico{width:18px;height:18px;stroke-width:1.75}
.msg-act:hover{color:var(--text);background:var(--surface-2)}
.msg-act:active{transform:scale(.9)}
.msg-act.copied{color:var(--success)}
.msg-act.speaking{color:var(--accent)}
/* P2.7: thumbs, version pager, thumbs-down reasons */
.msg-act[aria-pressed="true"]{color:var(--accent)}
.msg-ver{display:inline-flex;align-items:center;gap:0;margin:0 2px;font-family:var(--font-mono);font-size:var(--fs-12);color:var(--text-muted)}
.msg-ver .msg-act{width:28px}
.msg-ver .msg-act:disabled{opacity:.35;cursor:default;background:none}
.msg-ver-n{min-width:38px;text-align:center}
.fb-reasons{display:flex;flex-wrap:wrap;gap:6px;margin:6px 0 0 4px}
.fb-reasons[hidden]{display:none}
.fb-reason{height:28px;padding:0 12px;border-radius:var(--radius-pill);border:1px solid var(--border);background:none;color:var(--text-muted);font:inherit;font-size:var(--fs-12);cursor:pointer}
.fb-reason:hover{color:var(--text);background:var(--surface-2)}
.fb-reason[aria-pressed="true"]{color:var(--accent);border-color:var(--accent)}
.typing{color:var(--accent);font-size:calc(13px * var(--fs-scale));padding:8px 16px}
.typing span{display:inline-block;width:6px;height:6px;margin-right:4px;border-radius:50%;background:currentColor;vertical-align:middle;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:calc(13px * var(--fs-scale));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)}}
/* ── Composer card (UI phase 1 PR-D) ──
One card in the reading column: queued messages, attachments and the working
folder above the textarea, then a toolbar row: + menu, mode pill and chips on
the left; model pill, mic and send (stop while a reply streams) on the right. */
.input-area{position:relative;flex-shrink:0;padding:8px max(12px,calc((100% - 760px) / 2)) calc(10px + env(safe-area-inset-bottom,0px));background:var(--bg)}
/* P2.11: a temporary chat — dashed composer border, an eye-off chip, a note in the empty chat */
.composer.temp{border-style:dashed;border-color:var(--text-dim)}
.temp-note{display:flex;align-items:center;gap:8px;justify-content:center;margin:12px auto 0;max-width:46ch;text-align:center;font-size:var(--fs-13);color:var(--text-muted)}
.temp-chat .msg-up,.temp-chat .msg-down{display:none}
.composer{position:relative;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-24);box-shadow:var(--shadow-composer);padding:12px 12px 8px 16px;transition:border-color .15s,box-shadow .15s}
.composer:focus-within{border-color:var(--border-strong)}
.composer:has(.chat-input:focus-visible){box-shadow:var(--shadow-composer),var(--focus-ring)}
.chat-input{display:block;width:100%;background:transparent;border:0;color:var(--text);padding:4px 0;font-size:max(16px,var(--fs-16));font-family:var(--font-sans);line-height:1.5;outline:none;resize:none;min-height:32px;max-height:40vh;overflow-y:auto}
.chat-input:focus-visible{outline:none}
.chat-input::placeholder{color:var(--text-dim);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.file-chips{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:8px}
.ibtn{background:none;border:0;border-radius:50%;color:var(--text-dim);cursor:pointer;display:inline-flex;align-items:center;justify-content:center}
.ibtn:hover{color:var(--text)}
.file-chips:empty{display:none}
.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:var(--fs-13);font-family:var(--font-mono);color:var(--text-muted);max-width:200px}
.file-chip .fc-icon{font-size:calc(14px * var(--fs-scale));flex-shrink:0}
.file-chip .fc-name{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.file-chip .fc-close{cursor:pointer;background:none;border:0;padding:4px;border-radius:6px;color:var(--text-dim);font-size:calc(12px * var(--fs-scale));margin-left:2px;flex-shrink:0}
.file-chip .fc-close:hover{color:var(--danger)}
.file-chip.loading{opacity:.75}
/* P2.12: tiles — a 56px thumbnail, or an icon with name and size; a ring while uploading */
.file-chip.tile{padding:4px 8px 4px 4px;max-width:240px;font-family:var(--font-sans)}
.fc-thumb{width:56px;height:56px;border-radius:6px;object-fit:cover;flex-shrink:0;display:block;border:1px solid var(--border)}
.fc-meta{display:flex;flex-direction:column;min-width:0}
.fc-size{font-size:var(--fs-12);color:var(--text-dim)}
.fc-ring{width:16px;height:16px;border-radius:50%;border:2px solid var(--border);border-top-color:var(--accent);flex-shrink:0;animation:fcspin .8s linear infinite}
@keyframes fcspin{to{transform:rotate(360deg)}}
@media (prefers-reduced-motion: reduce){.fc-ring{animation:none;border-top-color:var(--border)}}
.msg-atts{display:flex;flex-wrap:wrap;gap:6px;justify-content:flex-end;margin-bottom:6px}
.msg-att{display:inline-flex;align-items:center;gap:6px;max-width:220px;padding:4px 8px 4px 4px;border:1px solid var(--border);border-radius:8px;background:var(--surface-2);color:var(--text-muted);font:inherit;font-size:var(--fs-12);text-align:left}
button.msg-att{cursor:zoom-in}
.msg-att .fc-name{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.msg-att .ico{width:18px;height:18px;flex-shrink:0;margin-left:4px}
.msg-saw{margin:6px 0 0;font-size:var(--fs-13);color:var(--text-muted);text-align:left}
.msg-saw summary{cursor:pointer;color:var(--text-dim)}
.msg-saw div{white-space:pre-wrap;margin-top:4px}
.gen-img{cursor:zoom-in}
@keyframes pulse{0%,100%{opacity:1}50%{opacity:.6}}
.dragover .messages{border:2px dashed var(--accent)!important}
#dropOverlay{position:fixed;inset:0;z-index:9999;display:none;align-items:center;justify-content:center;background:rgba(217,119,87,0.10);backdrop-filter:blur(2px)}
#dropOverlay.show{display:flex}
#dropOverlay .drop-inner{display:flex;flex-direction:column;align-items:center;gap:14px;color:var(--accent);font-size:calc(16px * var(--fs-scale));font-weight:600;padding:40px 60px;border:2px dashed var(--accent);border-radius:18px;background:var(--surface);box-shadow:0 10px 40px rgba(0,0,0,.25);pointer-events:none}
.composer-bar{display:flex;align-items:center;justify-content:space-between;gap:8px;min-height:40px;margin-top:4px}
.cb-left,.cb-right{display:flex;align-items:center;gap:6px;min-width:0}
.cb-left{flex:1;flex-wrap:wrap}
.cb-right{flex-shrink:0}
.cb-btn,.cb-send{width:36px;height:36px;border-radius:50%;border:0;cursor:pointer;flex-shrink:0;display:inline-flex;align-items:center;justify-content:center;transition:background .12s,color .12s}
.cb-btn{background:transparent;color:var(--text-muted)}
.cb-btn:hover,.cb-btn[aria-expanded="true"]{background:var(--surface-2);color:var(--text)}
.cb-btn .ico{width:20px;height:20px;stroke-width:1.75}
.cb-btn.recording{background:var(--danger);color:#fff;animation:pulse 1s infinite}
.cb-send{background:var(--accent);color:var(--on-accent)}
.cb-send:hover{background:var(--accent-hover)}
.cb-send.empty{background:var(--surface-3);color:var(--text-dim)}
.cb-send .ico{width:18px;height:18px}
.cb-send.stop{display:none;background:var(--text);color:var(--bg)}
.cb-btn:active,.cb-send:active{transform:scale(.94)}
.mode-pill,.cb-chip{height:32px;display:inline-flex;align-items:center;gap:6px;border-radius:var(--radius-pill);font-family:var(--font-sans);font-weight:500;white-space:nowrap;cursor:pointer;max-width:100%}
.mode-pill{padding:0 10px 0 9px;border:0;background:var(--surface-2);color:var(--text);font-size:var(--fs-14)}
.mode-pill:hover,.mode-pill[aria-expanded="true"]{background:var(--surface-3)}
.mode-pill .mp-ico{display:inline-flex}
.mode-pill .ico{width:16px;height:16px;stroke-width:1.75}
.mode-pill .chev{width:14px;height:14px;color:var(--text-dim)}
.cb-chip{padding:0 10px;border:1px solid var(--border);background:transparent;color:var(--text-muted);font-size:var(--fs-13)}
.cb-chip:hover{border-color:var(--border-strong);color:var(--text)}
.cb-chip .ico{width:14px;height:14px;stroke-width:1.75}
.cb-chip .cc-label{overflow:hidden;text-overflow:ellipsis}
.cb-chip.static{padding-right:4px;cursor:default}
.cb-chip .x{width:24px;height:24px;border-radius:50%;border:0;background:none;color:inherit;cursor:pointer;display:inline-flex;align-items:center;justify-content:center}
.cb-chip .x:hover{background:var(--surface-2);color:var(--text)}
/* Model pill: sans, never mono (design brief). Accent while a non-everyday model is active. */
#modelSelect{height:32px;background:var(--surface-2);border:0;color:var(--text-muted);font-family:var(--font-sans);font-size:var(--fs-13);font-weight:500;border-radius:var(--radius-pill);padding:0 12px;cursor:pointer;max-width:200px;transition:color .15s,box-shadow .15s}
#modelSelect:hover{color:var(--text)}
#modelSelect.alt{color:var(--accent);box-shadow:inset 0 0 0 1px rgba(217,119,87,.45)}
#modelSelect:disabled{opacity:.5;cursor:progress}
/* P2.6: the styled picker's button takes the pill look the model select had. */
.cs-menu-btn.cs-menu-pill{height:32px;border:0;border-radius:var(--radius-pill);background:var(--surface-2);color:var(--text-muted);font-size:var(--fs-13);max-width:200px;padding:0 10px 0 12px}
.cs-menu-btn.cs-menu-pill:hover{color:var(--text)}
.cs-menu-btn.cs-menu-pill.alt{color:var(--accent);box-shadow:inset 0 0 0 1px rgba(217,119,87,.45)}
.cs-menu-btn.cs-menu-small{height:28px;font-size:var(--fs-12)}
.img-switch{position:relative}
.img-switch input{position:absolute;opacity:0;width:1px;height:1px}
.img-switch-track{position:relative;flex:none;width:28px;height:16px;border-radius:999px;background:var(--surface-3);border:1px solid var(--border);transition:background .15s}
.img-switch-track::after{content:'';position:absolute;top:1px;left:1px;width:12px;height:12px;border-radius:50%;background:var(--text-muted);transition:transform .15s,background .15s}
.img-switch input:checked+.img-switch-track{background:var(--accent);border-color:var(--accent)}
.img-switch input:checked+.img-switch-track::after{transform:translateX(12px);background:var(--on-accent)}
.img-switch input:focus-visible+.img-switch-track{box-shadow:var(--focus-ring)}
.ab-stepper{display:inline-flex;align-items:stretch;border:1px solid var(--border);border-radius:var(--radius-8);overflow:hidden}
.ab-stepper .ab-input{width:40px;text-align:center;border:0;border-radius:0;-moz-appearance:textfield;appearance:textfield}
.ab-stepper .ab-input::-webkit-outer-spin-button,.ab-stepper .ab-input::-webkit-inner-spin-button{-webkit-appearance:none;margin:0}
.ab-step{width:30px;border:0;background:var(--surface-2);color:var(--text);font-size:var(--fs-16);cursor:pointer}
.ab-step:hover{background:var(--surface-3)}
.ab-step:focus-visible{outline:none;box-shadow:var(--focus-ring)}
/* Menus: one popover component, above the composer. */
.msg-memory{border:0;background:none;padding:0 2px;margin-left:6px;font:inherit;font-size:var(--fs-12);color:var(--text-muted);text-decoration:underline;text-underline-offset:2px;cursor:pointer}
.msg-memory:hover{color:var(--accent)}
.msg-memory-panel{margin:4px 0 0;padding:8px 12px;border:1px solid var(--border);border-radius:var(--radius-8);background:var(--surface);font-size:var(--fs-13);color:var(--text-muted);max-width:420px}
.msg-memory-panel ul{margin:0 0 6px;padding-left:18px}
.msg-memory-panel a{color:var(--accent)}
.pop-menu{position:absolute;bottom:calc(100% + 8px);left:8px;z-index:60;min-width:240px;max-width:min(340px,calc(100vw - 24px));background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-12);box-shadow:var(--shadow-popover);padding:6px;display:none}
.pop-menu.open{display:block}
.pop-item{width:100%;display:flex;align-items:center;gap:10px;min-height:36px;padding:6px 10px;border:0;border-radius:var(--radius-8);background:none;color:var(--text);font-family:var(--font-sans);font-size:var(--fs-14);line-height:1.3;text-align:left;cursor:pointer}
.pop-item:hover,.pop-item:focus-visible{background:var(--surface-2)}
.pop-item .ico{width:18px;height:18px;stroke-width:1.75;color:var(--text-muted)}
.pop-item .pi-text{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}
.pop-item .pi-desc{font-size:var(--fs-12);color:var(--text-muted)}
.pop-item .pi-tag{font-size:var(--fs-12);color:var(--text-dim)}
/* '/' commands and '@' picks (P2.3): a list above the composer; the caret stays in the box. */
.mention-menu{position:absolute;bottom:calc(100% + 8px);left:8px;right:8px;z-index:61;max-width:460px;max-height:min(360px,50vh);overflow-y:auto;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-12);box-shadow:var(--shadow-popover);padding:6px;display:none}
.mention-menu.open{display:block}
.mention-menu .mm-group{padding:8px 10px 4px;font-size:var(--fs-12);font-weight:var(--fw-semibold);color:var(--text-muted)}
.mention-menu .mm-item{width:100%;display:flex;align-items:baseline;gap:10px;min-height:34px;padding:6px 10px;border:0;border-radius:var(--radius-8);background:none;color:var(--text);font-family:var(--font-sans);font-size:var(--fs-14);line-height:1.3;text-align:left;cursor:pointer}
.mention-menu .mm-item[aria-selected="true"],.mention-menu .mm-item:hover{background:var(--surface-2)}
.mention-menu .mm-name{flex:none;font-weight:var(--fw-medium);white-space:nowrap}
.mention-menu .mm-desc{flex:1;min-width:0;font-size:var(--fs-12);color:var(--text-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.mention-menu .mm-empty{padding:8px 10px;font-size:var(--fs-13);color:var(--text-muted)}
.pop-item .pi-check{width:16px;height:16px;color:var(--accent);visibility:hidden}
.pop-item[aria-checked="true"] .pi-check{visibility:visible}
.pop-sep{height:1px;background:var(--border);margin:4px 6px}
.touch-only{display:none}
@media (hover:none) and (pointer:coarse){.touch-only{display:flex}}
/* Messages sent while a reply streams wait here and send when it ends. */
.queue-chips{display:flex;flex-direction:column;gap:6px;margin-bottom:8px}
.queue-chips:empty{display:none}
/* P3.10: Compare models, from a reply's more menu */
.cs-dialog.cmp-dialog{width:min(980px,100%)}
.cmp-note{font-size:var(--fs-14);color:var(--text-muted);padding:6px 0;line-height:1.5}
.cmp-a{font-size:var(--fs-14);margin-bottom:10px}
.cmp-k{font-weight:600;color:var(--text-muted);margin-right:4px}
.cmp-pick{border:0;padding:0;margin:0 0 6px}
.cmp-pick legend{font-weight:600;color:var(--text-muted);font-size:var(--fs-14);margin-bottom:4px}
.cmp-cost{color:var(--text-muted);font-size:var(--fs-12)}
.cmp-cols{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.cmp-col{display:flex;flex-direction:column;gap:8px;min-width:0;padding:12px;border:1px solid var(--border);border-radius:var(--radius-12);background:var(--surface-2)}
.cmp-h{font-weight:600;font-size:var(--fs-14);overflow-wrap:anywhere}
.cmp-meta{font-size:var(--fs-12);color:var(--text-muted)}
.cmp-ans{font-size:var(--fs-14);line-height:1.55;max-height:50vh;overflow-y:auto;overflow-wrap:anywhere}
.cmp-err{font-size:var(--fs-13);color:var(--danger-text);overflow-wrap:anywhere}
.cmp-col .cs-dbtn{align-self:flex-start}
@media(max-width:767px){.cmp-cols{grid-template-columns:1fr}.cmp-ans{max-height:none}}
/* P3.8: the running-task rail above the composer (active projects, running crew runs) */
.run-rail{display:flex;flex-direction:column;gap:6px;flex-shrink:0;padding:0 max(12px,calc((100% - 760px) / 2)) 6px;background:var(--bg)}
.run-rail[hidden]{display:none}
.run-item{display:flex;align-items:center;flex-wrap:wrap;gap:6px 10px;padding:7px 8px 7px 12px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-12);font-size:var(--fs-13)}
.run-name{min-width:0;max-width:45%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:600}
.run-state{font-size:var(--fs-12);font-weight:600;color:var(--text-muted);white-space:nowrap}
.run-state.ok{color:var(--success-text)}.run-state.warn{color:var(--warning-text)}.run-state.bad{color:var(--danger-text)}.run-state.info{color:var(--info-text)}
.run-bar{flex:1 1 60px;min-width:40px;height:4px;border-radius:2px;background:var(--surface-3);overflow:hidden}
.run-bar>span{display:block;height:100%;min-width:2px;background:var(--accent)}
.run-count{font-size:var(--fs-12);color:var(--text-muted);white-space:nowrap}
.run-acts{display:flex;gap:6px;margin-left:auto}
.run-btn{height:28px;padding:0 10px;border:1px solid var(--border);border-radius:var(--radius-pill);background:var(--surface-2);color:var(--text);font:600 var(--fs-12)/1 var(--font-sans);cursor:pointer}
.run-btn:hover{border-color:var(--border-hover)}
.run-btn.danger{color:var(--danger-text)}
.run-all{align-self:flex-end;font-size:var(--fs-12);color:var(--text-muted);text-decoration:underline}
@media(max-width:767px){.run-name{max-width:60%}.run-btn{height:32px}}
.queue-chip{display:flex;align-items:center;gap:8px;padding:4px 4px 4px 12px;border-radius:var(--radius-12);background:var(--surface-2);font-size:var(--fs-14);color:var(--text)}
.queue-chip .qc-label{flex-shrink:0;font-size:var(--fs-12);font-weight:600;color:var(--text-muted)}
.queue-chip .qc-text{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.queue-chip button{width:28px;height:28px;flex-shrink:0;border-radius:var(--radius-8);border:0;background:none;color:var(--text-muted);cursor:pointer;display:inline-flex;align-items:center;justify-content:center}
.queue-chip button:hover{background:var(--surface-3);color:var(--text)}
.queue-chip .ico{width:16px;height:16px;stroke-width:1.75}
.jump-latest{position:absolute;left:50%;bottom:calc(100% + 4px);transform:translateX(-50%);z-index:50;display:none;align-items:center;gap:6px;height:32px;padding:0 14px 0 10px;border-radius:var(--radius-pill);border:1px solid var(--border);background:var(--surface);color:var(--text);font-family:var(--font-sans);font-size:var(--fs-13);font-weight:500;box-shadow:var(--shadow-popover);cursor:pointer;white-space:nowrap}
.jump-latest.show{display:inline-flex}
.jump-latest .ico{width:16px;height:16px;stroke-width:1.75}
/* Agents sheet: centred card on desktop, bottom sheet on the phone. */
.sheet-overlay{position:fixed;inset:0;z-index:10005;display:none;align-items:center;justify-content:center;padding:16px;background:rgba(0,0,0,.5)}
.sheet-overlay.open{display:flex}
.sheet{width:min(600px,100%);max-height:min(84vh,760px);overflow-y:auto;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-20);box-shadow:var(--shadow-popover);padding:16px 18px}
.sheet-head{display:flex;align-items:center;justify-content:space-between;gap:12px}
.sheet-head h2{font-family:var(--font-sans);font-size:var(--fs-16);font-weight:600;color:var(--text)}
.sheet-x{width:32px;height:32px;border-radius:50%;border:0;background:none;color:var(--text-muted);cursor:pointer;display:inline-flex;align-items:center;justify-content:center}
.sheet-x:hover{background:var(--surface-2);color:var(--text)}
.sheet-x .ico{width:18px;height:18px;stroke-width:1.75}
.sheet-sub{margin:4px 0 12px;font-size:var(--fs-13);color:var(--text-muted)}
.crew-list{display:grid;grid-template-columns:repeat(auto-fill,minmax(170px,1fr));gap:6px}
.crew-item{display:flex;flex-direction:column;align-items:flex-start;gap:2px;padding:9px 12px;border:1px solid var(--border);border-radius:var(--radius-12);background:transparent;color:var(--text);font-family:var(--font-sans);text-align:left;cursor:pointer;min-width:0}
.crew-item:hover{border-color:var(--border-strong);background:var(--surface-2)}
.crew-item.active{border-color:var(--accent);background:var(--accent-dim)}
.crew-item .ci-title{font-size:var(--fs-14);font-weight:500}
.crew-item .ci-desc{font-size:var(--fs-12);color:var(--text-muted)}
.crew-item .ci-desc:empty{display:none}
.sheet-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-top:12px}
.sheet-label{font-size:var(--fs-13);color:var(--text-muted)}
#researchModelSelect{height:32px;background:var(--surface-2);border:1px solid var(--border);color:var(--text);font-family:var(--font-sans);font-size:var(--fs-13);border-radius:var(--radius-8);padding:0 10px;cursor:pointer}
.sheet-foot{display:flex;justify-content:flex-end;gap:8px;margin-top:16px}
.sheet-btn{height:36px;display:inline-flex;align-items:center;gap:6px;padding:0 16px;border-radius:var(--radius-pill);border:1px solid var(--border);background:transparent;color:var(--text);font-family:var(--font-sans);font-size:var(--fs-14);font-weight:500;cursor:pointer}
.sheet-btn:hover{background:var(--surface-2)}
.sheet-btn.primary{background:var(--accent);border-color:var(--accent);color:var(--on-accent)}
.sheet-btn.primary:hover{background:var(--accent-hover)}
.sheet-btn .ico{width:16px;height:16px;stroke-width:1.75}
/* New chat: greeting, starter cards, recent chats. On desktop the composer sits
under them, centred in the window, and docks at the bottom after the first message. */
.empty-state{padding:32px 0 16px}
.greet-title{font-family:var(--font-sans);font-size:var(--fs-30);line-height:var(--lh-30);font-weight:400;color:var(--text)}
.greet-sub{margin-top:6px;font-size:var(--fs-16);line-height:var(--lh-16);color:var(--text-muted)}
.starters{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:24px}
.starter{display:flex;align-items:flex-start;gap:10px;min-width:0;padding:12px 14px;border:1px solid var(--border);border-radius:var(--radius-12);background:var(--surface);color:var(--text);font-family:var(--font-sans);text-align:left;cursor:pointer;transition:border-color .12s,background .12s}
.starter:hover{border-color:var(--border-strong);background:var(--surface-2)}
.starter .ico{width:18px;height:18px;stroke-width:1.75;color:var(--accent);margin-top:1px}
.starter .st-text{min-width:0;display:flex;flex-direction:column;gap:2px}
.starter .st-title{font-size:var(--fs-14);font-weight:500;line-height:1.3;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.starter .st-desc{font-size:var(--fs-12);color:var(--text-muted)}
.recent{margin-top:20px}
.recent-h{margin:0 0 4px 10px;font-size:var(--fs-12);font-weight:600;color:var(--text-dim)}
.recent-item{display:flex;justify-content:space-between;align-items:baseline;gap:12px;width:100%;padding:8px 10px;border:0;border-radius:var(--radius-8);background:none;color:var(--text-muted);font-family:var(--font-sans);font-size:var(--fs-14);text-align:left;cursor:pointer}
.recent-item:hover{background:var(--surface-2);color:var(--text)}
.recent-item .ri-title{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.recent-item .ri-time{flex-shrink:0;font-size:var(--fs-12);color:var(--text-dim)}
.app.is-empty .messages{flex:0 1 auto;margin-top:auto}
.app.is-empty .input-area{margin-bottom:auto}
pre{background:var(--surface-3);padding:10px;border-radius:8px;overflow-x:auto;font-family:var(--font-mono);font-size:var(--fs-code);margin:8px 0}
pre code{font-size:1em}
code{font-family:var(--font-mono);font-size:var(--fs-code-inline);background:var(--surface-3);padding:2px 6px;border-radius:4px}
input[type=file]{display:none}
.discuss-report-btn{margin-top:2px;padding:9px 16px;border:1px solid var(--accent);border-radius:8px;cursor:pointer;font-size:calc(13px * var(--fs-scale));font-family:var(--font-sans);font-weight:600;background:var(--accent);color:var(--on-accent);transition:all .15s;display:inline-flex;align-items:center;gap:6px}
.discuss-report-btn:hover:not(:disabled){background:var(--accent-hover);border-color:var(--accent-hover)}
.discuss-report-btn:disabled{cursor:default;opacity:.7;background:transparent;color:var(--accent)}
/* Train-of-thought panel — reveals reasoning (chat) / agent steps, collapsed by default */
/* Train-of-thought: a reveal control + a fixed-size continuously-scrolling window (like public LLM "thinking") */
.tot{margin:2px 0 6px}
.tot-toggle{display:inline-flex;align-items:center;gap:6px;cursor:pointer;color:var(--text-dim);font-size:calc(12px * var(--fs-scale));user-select:none;padding:2px 0}
.tot-toggle:hover{color:var(--text-muted)}
.tot-toggle .chev{font-size:calc(12px * var(--fs-scale));transition:transform .15s;color:var(--accent)}
.tot.open .tot-toggle .chev{transform:rotate(90deg)}
.tot-window{display:none;margin-top:6px;height:150px;overflow-y:auto;background:var(--surface-2);border:1px solid var(--border);border-radius:8px;padding:8px 12px;font-size:calc(12px * var(--fs-scale));line-height:1.6;color:var(--text-dim);word-break:break-word;font-family:var(--font-sans)}
.tot-window.md h1,.tot-window.md h2,.tot-window.md h3{font-size:1em}
.tot.open .tot-window{display:block}
.tot-live .tot-toggle .chev{animation:totPulse 1.2s ease-in-out infinite}
@keyframes totPulse{0%,100%{opacity:.4}50%{opacity:1}}
/* small inline stop button under the agent status message */
.status-stop{margin-top:8px;display:inline-flex;align-items:center;gap:6px;padding:5px 12px;border:1px solid var(--border);border-radius:14px;background:transparent;color:var(--text-muted);font-size:calc(12px * var(--fs-scale));font-family:var(--font-sans);cursor:pointer;transition:all .15s}
.status-stop:hover{border-color:#e55;color:#e55}
/* ── Agent Builder ── */
#agentBuilder{display:none;margin-top:12px;background:var(--surface-2);border:1px solid var(--border);border-radius:var(--radius-12);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:var(--fs-13);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:calc(12px * var(--fs-scale));font-family:var(--font-sans);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:var(--fs-14);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:var(--fs-14);font-weight:600;cursor:pointer;transition:opacity .2s;font-family:var(--font-sans)}
.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:var(--fs-14);font-family:var(--font-sans);cursor:pointer}
/* ── Crew Select ── */
#crewSelect{display:none}
/* ── 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:var(--fs-14);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)}
/* ── Mobile Responsive ── */
@media (max-width: 768px), (max-height: 600px) and (pointer: coarse){
.msg{max-width:90%}
#agentBuilder .ab-row{flex-direction:column}
#agentBuilder .ab-field{min-width:100%;max-width:100%!important}
.msg-meta{opacity:.7}
}
@media (max-width:480px){
.messages{padding:10px 16px}
}
.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:84vh; border-radius:var(--radius); border:1px solid var(--border); }
.modal-overlay { flex-direction:column; gap:12px; }
.modal-dl { display:inline-flex; align-items:center; gap:6px; height:36px; padding:0 16px; border-radius:var(--radius-pill); background:rgba(30,30,30,0.9); color:#fff; border:1px solid rgba(255,255,255,0.3); text-decoration:none; font-size:var(--fs-14); }
.modal-dl[hidden] { display:none; }
.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:calc(26px * var(--fs-scale)); 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:calc(30px * var(--fs-scale)); top:10px; right:10px; } }
@media (max-width: 768px), (max-height: 600px) and (pointer: coarse){
/* Phone (P2.1): the composer sits in the flow above the shell's tab bar, full
width minus 12px gutters (no position:fixed, no measured padding). The model
pill lives in the top bar; the Agents sheet is a bottom sheet; toasts show
under the top bar, clear of the composer. */
.modal-overlay{z-index:10002}
.modal-close{z-index:10003}
.toast{z-index:10004;bottom:auto;top:calc(60px + env(safe-area-inset-top,0px))}
.input-area{padding:6px 12px 8px;background:var(--bg)}
.app.is-empty .messages{flex:1;margin-top:0}
.app.is-empty .input-area{margin-bottom:0}
#hdrModelSlot #modelSelect{max-width:136px;height:30px;padding:0 10px}
#hdrModelSlot .cs-menu-btn.cs-menu-pill{max-width:136px;height:30px;padding:0 8px 0 10px}
.starters{grid-template-columns:1fr}
.empty-state{padding-top:16px}
.greet-title{font-size:var(--fs-24);line-height:var(--lh-24)}
.sheet-overlay{align-items:flex-end;padding:0}
.sheet{width:100%;max-height:88vh;border-radius:var(--radius-20) var(--radius-20) 0 0;padding-bottom:calc(16px + env(safe-area-inset-bottom,0px))}
}
</style>
</head>
<body>
<script src="/static/codec-shell.js?v=95fbf3b8" data-page="chat" data-title="Chat" data-status data-model-slot></script>
<div class="app cs-main" id="appContainer">
<div class="messages" id="messages" role="log" aria-live="polite" aria-label="Conversation"></div>
<div class="input-area">
<button type="button" class="jump-latest" id="jumpLatest" onclick="jumpToLatest()"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><line x1="12" y1="5" x2="12" y2="19"/><polyline points="19 12 12 19 5 12"/></svg>Jump to latest</button>
<div class="composer" id="composer">
<div class="mention-menu" id="mentionMenu" role="listbox" aria-label="Commands, skills and agents"></div>
<div class="pop-menu" id="plusMenu" role="menu" aria-label="Add to your message">
<button type="button" class="pop-item" role="menuitem" onclick="closeMenus();document.getElementById('fileUp').click()"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><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><span class="pi-text">Attach files</span></button>
<button type="button" class="pop-item touch-only" role="menuitem" onclick="closeMenus();document.getElementById('photoUp').click()"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/></svg><span class="pi-text">Photo or camera</span></button>
<button type="button" class="pop-item" role="menuitem" onclick="closeMenus();takeScreenshot()"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><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="pi-text">Screenshot of Mac</span></button>
<button type="button" class="pop-item" role="menuitem" onclick="closeMenus();takeServerPhoto()"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><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="pi-text">Webcam snapshot</span></button>
<button type="button" class="pop-item" id="folderBtn" role="menuitem" onclick="closeMenus();pickWorkingFolder()" title="Give this chat a working folder on the Mac"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M22 19a2 2 0 01-2 2H4a2 2 0 01-2-2V5a2 2 0 012-2h5l2 3h9a2 2 0 012 2z"/><line x1="12" y1="11" x2="12" y2="17"/><line x1="9" y1="14" x2="15" y2="14"/></svg><span class="pi-text">Working folder</span><span class="pi-tag">on Mac</span></button>
<div class="pop-sep" role="separator"></div>
<button type="button" class="pop-item" id="webSearchItem" role="menuitemcheckbox" aria-checked="false" onclick="toggleWebSearch()"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 014 10 15.3 15.3 0 01-4 10 15.3 15.3 0 01-4-10 15.3 15.3 0 014-10z"/></svg><span class="pi-text">Search the web</span><svg class="ico pi-check" viewBox="0 0 24 24" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg></button>
<button type="button" class="pop-item" id="tempChatItem" role="menuitemcheckbox" aria-checked="false" onclick="toggleTemporary()"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.53 13.53 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/><line x1="2" y1="2" x2="22" y2="22"/></svg><span class="pi-text">Temporary chat<span class="pi-desc">Not saved to history or memory</span></span><svg class="ico pi-check" viewBox="0 0 24 24" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg></button>
</div>
<div class="pop-menu" id="modeMenu" role="menu" aria-label="Mode">
<button type="button" class="pop-item" role="menuitemradio" aria-checked="false" data-mode="chat" id="modeChatBtn" onclick="chooseMode('chat')"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/></svg><span class="pi-text">Chat<span class="pi-desc">Fast answers</span></span><svg class="ico pi-check" viewBox="0 0 24 24" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg></button>
<button type="button" class="pop-item" role="menuitemradio" aria-checked="false" data-mode="think" id="modeThinkBtn" onclick="chooseMode('think')"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><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><span class="pi-text">Think<span class="pi-desc">Reasons first: better answers, slower</span></span><svg class="ico pi-check" viewBox="0 0 24 24" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg></button>
<button type="button" class="pop-item" role="menuitemradio" aria-checked="false" data-mode="research" id="modeResearchBtn" onclick="chooseMode('research')"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><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><span class="pi-text">Agents<span class="pi-desc">Run a crew: research, briefing, trips and more</span></span><svg class="ico pi-check" viewBox="0 0 24 24" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg></button>
<button type="button" class="pop-item" role="menuitemradio" aria-checked="false" data-mode="project" id="modeProjectBtn" onclick="chooseMode('project')"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><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><span class="pi-text">Project<span class="pi-desc">Plan and build a bigger job in the background</span></span><svg class="ico pi-check" viewBox="0 0 24 24" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg></button>
<button type="button" class="pop-item" role="menuitemradio" aria-checked="false" data-mode="image" id="modeImageBtn" onclick="chooseMode('image')" style="display:none"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/></svg><span class="pi-text">Image<span class="pi-desc">Create an image on this Mac</span></span><svg class="ico pi-check" viewBox="0 0 24 24" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg></button>
</div>
<div class="queue-chips" id="queueChips"></div>
<div class="file-chips" id="fileChips"></div>
<div id="workdirChip" style="display:none;align-items:center;gap:6px;margin:0 0 6px 2px;font-size:calc(12px * var(--fs-scale));color:var(--text-dim)">
<svg class="ico" viewBox="0 0 24 24" style="width:13px;height:13px"><path d="M22 19a2 2 0 01-2 2H4a2 2 0 01-2-2V5a2 2 0 012-2h5l2 3h9a2 2 0 012 2z"/></svg>
<span id="workdirPath" style="max-width:60ch;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"></span>
<button class="ibtn" onclick="clearWorkingFolder()" title="Remove working folder" style="width:16px;height:16px;padding:0" aria-label="Remove working folder">
<svg class="ico" viewBox="0 0 24 24" style="width:11px;height:11px"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
</button>
</div>
<textarea class="chat-input" id="chatInput" placeholder="Message CODEC" rows="1" aria-label="Message CODEC" aria-autocomplete="list" aria-controls="mentionMenu" aria-expanded="false" onkeydown="handleKey(event)"></textarea>
<div class="composer-bar">
<div class="cb-left">
<button type="button" class="cb-btn" id="plusBtn" onclick="toggleMenu('plusMenu',this)" title="Add files and more" aria-label="Add files and more" aria-haspopup="menu" aria-expanded="false"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg></button>
<button type="button" class="mode-pill" id="modePill" onclick="toggleMenu('modeMenu',this)" title="Mode" aria-haspopup="menu" aria-expanded="false"><span class="mp-ico"></span><span class="mp-label">Think</span><svg class="ico chev" viewBox="0 0 24 24" aria-hidden="true"><polyline points="6 9 12 15 18 9"/></svg></button>
<button type="button" class="cb-chip" id="crewChip" onclick="openAgentSheet()" title="Choose the crew" style="display:none"><span class="cc-label">Deep Research</span><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><polyline points="6 9 12 15 18 9"/></svg></button>
<span class="cb-chip static" id="webChip" style="display:none"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 014 10 15.3 15.3 0 01-4 10 15.3 15.3 0 01-4-10 15.3 15.3 0 014-10z"/></svg>Web search<button type="button" class="x" onclick="toggleWebSearch()" title="Turn off web search" aria-label="Turn off web search"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"/></svg></button></span>
<span class="cb-chip static temp-chip" id="tempChip" style="display:none" title="Not saved to history or memory. The audit log still records what CODEC does."><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.53 13.53 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/><line x1="2" y1="2" x2="22" y2="22"/></svg>Temporary<button type="button" class="x" onclick="toggleTemporary()" title="Turn off temporary chat" aria-label="Turn off temporary chat"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"/></svg></button></span>
<span class="cb-chip static" id="pickChip" style="display:none"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.8-3.8a6 6 0 0 1-7.9 7.9l-6.9 6.9a2.1 2.1 0 0 1-3-3l6.9-6.9a6 6 0 0 1 7.9-7.9z"/></svg><span class="pk-label"></span><button type="button" class="x" onclick="setPick(null)" title="Remove the pick" aria-label="Remove the pick"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"/></svg></button></span>
<span id="imageOpts"><select id="imageSize" title="Image size — the first image takes about 2 min at 512 px"><option value="512">512 px (~2 min)</option><option value="768">768 px</option><option value="1024">1024 px</option></select><label class="img-switch" title="Transparent background"><input type="checkbox" role="switch" id="imageTransparent"><span class="img-switch-track" aria-hidden="true"></span>Transparent</label></span>
</div>
<div class="cb-right">
<span id="cbModelSlot"><select id="modelSelect" onchange="switchModel()" title="Local model — switching unloads the current one and loads the new one" style="display:inline-block">
<option value="">model…</option>
</select></span>
<button type="button" class="cb-btn" id="micBtn" onclick="toggleMic()" title="Voice input" aria-label="Voice input"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><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>
<button type="button" class="cb-send empty" id="sendBtn" onclick="sendMessage()" title="Send" aria-label="Send"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/></svg></button>
<button type="button" class="cb-send stop" id="stopBtn" onclick="stopGeneration()" title="Stop generating" aria-label="Stop generating"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><rect x="6" y="6" width="12" height="12" rx="2" fill="currentColor"/></svg></button>
</div>
</div>
</div>
<input type="file" id="fileUp" accept="*/*" multiple onchange="handleUpload(event)">
<input type="file" id="photoUp" accept="image/*" capture="environment" onchange="handleUpload(event)">
</div>
<!-- Agents: the crew picker and the custom-agent builder open in a sheet from the mode pill -->
<div class="sheet-overlay" id="agentSheet" onclick="if(event.target===this)closeAgentSheet()" data-dialog="open">
<div class="sheet" role="dialog" aria-modal="true" aria-labelledby="agentSheetTitle">
<div class="sheet-head"><h2 id="agentSheetTitle">Agents</h2><button type="button" class="sheet-x" onclick="closeAgentSheet()" aria-label="Close" data-dialog-close><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"/></svg></button></div>
<p class="sheet-sub">Pick a crew, then type its task in the message box and press Send.</p>
<div class="crew-list" id="crewList"></div>
<select id="crewSelect" hidden>
<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>
<div class="sheet-row" id="researchModelRow" style="display:none"><span class="sheet-label">Research model</span><select id="researchModelSelect" title="Deep Research model — 35B (default) or 27B. Other models are not used for research.">
<option value="mlx-community/Qwen3.6-35B-A3B-4bit" selected>35B (default)</option>
<option value="mlx-community/Qwen3.8-27B-4bit">27B</option>
</select></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:120px">
<span class="ab-label">Max Steps</span>
<span class="ab-stepper"><button type="button" class="ab-step" onclick="_stepMaxIter(-1)" aria-label="Fewer steps">−</button><input class="ab-input" id="agentMaxIter" type="number" value="8" min="1" max="20" inputmode="numeric" aria-label="Max steps"><button type="button" class="ab-step" onclick="_stepMaxIter(1)" aria-label="More steps">+</button></span>
</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:calc(12px * var(--fs-scale));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:calc(12px * var(--fs-scale))">Delete</button>
</div>
<span style="font-size:calc(12px * var(--fs-scale));color:var(--text-dim)">Type your task below and press Send</span>
</div>
</div>
<div class="sheet-foot">
<button type="button" id="scheduleBtn" class="sheet-btn" onclick="showSchedulePanel()" title="Run this crew every day"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>Schedule daily</button>
<button type="button" class="sheet-btn primary" onclick="closeAgentSheet()">Done</button>
</div>
</div>
</div>
</div>
<div class="modal-overlay" id="screenModal" onclick="closeScreenshot()" role="dialog" aria-modal="true" aria-label="Image" data-dialog="show">
<button class="modal-close" onclick="event.stopPropagation(); closeScreenshot()" aria-label="Close image" data-dialog-close><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"/></svg></button>
<img id="screenImg" src="" alt="" onclick="event.stopPropagation()">
<a class="modal-dl" id="screenDl" href="#" download hidden onclick="event.stopPropagation()"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"/></svg>Download</a>
</div>
<div class="toast" id="toast" role="status" aria-live="polite"></div>
<!-- Markdown replies: vendored marked + DOMPurify + highlight.js, then the shared renderer -->
<script src="/static/vendor/marked.umd.js"></script>
<script src="/static/vendor/purify.min.js"></script>
<script src="/static/vendor/highlight.min.js"></script>
<script src="/static/codec-md.js?v=44d1a451"></script>
<script>
/* Safe storage accessors — use these, never localStorage/sessionStorage directly.
Storage access THROWS when blocked; it does not return null. Safari private
mode, a hardened profile, and an iframe whose third-party storage is blocked
all raise on the FIRST touch. An unguarded read at the top level of a script
therefore kills that entire script: every statement after it, theme init
included, silently never runs, and the page looks fine while being half-dead.
That is exactly what happened to cortex, which the dashboard embeds in an
iframe. Reads degrade to null, writes to no-ops — a page with no persisted
preferences beats a page with no JavaScript. */
function _lsGet(k){try{return localStorage.getItem(k)}catch(e){return null}}
function _lsSet(k,v){try{localStorage.setItem(k,v)}catch(e){}}
function _lsDel(k){try{localStorage.removeItem(k)}catch(e){}}
function _ssGet(k){try{return sessionStorage.getItem(k)}catch(e){return null}}
function _ssSet(k,v){try{sessionStorage.setItem(k,v)}catch(e){}}
function _ssDel(k){try{sessionStorage.removeItem(k)}catch(e){}}
</script>
<script>
// 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;
var _authRedirecting=false;
window.fetch=function(u,o){
o=o||{};
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;_ssSet('_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(_ssGet('_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 Monaco editor + live preview. New skills land through the human-review approval flow.\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" +
"### 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. Never use emoji. For emphasis use CAPS or *asterisks*. For code use backticks. For long-form: use headers and structure.";
// ── Reasoning scaffold (Think mode). Tuned for the local 4-bit Qwen: forces a
// dependency check so it stops giving glib surface answers (the "car wash" class
// of trick). Model reasons in <thinking>, then emits "### FINAL ANSWER:"; the UI
// hides the thinking (shown only in the reveal window) and displays the answer.
var REASON_SCAFFOLD="\n\n### RESPONSE FORMAT (MANDATORY)\n" +
"Structure EVERY reply in exactly two parts:\n" +
"<thinking>\n" +
"Do ALL of your reasoning here — every step, every case. First identify what the user is actually trying to ACCOMPLISH, and check for any hidden physical or logical dependencies (things that must be true or present for the goal to work). Never give a glib surface answer that ignores them. For CHALLENGES (the user doubts you / says 'check online'): do ONE quick internal check, do NOT loop. For SIMPLE questions: keep this to 1-2 sentences.\n" +
"</thinking>\n" +
"### FINAL ANSWER:\n" +
"(your clean, concise answer for the user)\n" +
"RULES: ALWAYS open with <thinking> as the very first characters of your reply. Put 100% of your deliberation inside the tags — never reason outside them. After </thinking>, write exactly \"### FINAL ANSWER:\" then the answer.";
var CONCISE_MODE="\n\n### RESPONSE STYLE\nAnswer directly and concisely. Do not use <thinking> tags or show reasoning — get straight to the point.";
// System prompt: identity + concise directive when Think is off. The reasoning
// scaffold is appended server-side (reason_scaffold flag) so it lands as the
// LAST instruction and isn't buried under the backend's base prompt.
function buildSystem(){return SYS+(thinkingEnabled?'':CONCISE_MODE);}
// Working folder allocated to this chat (like a working directory). Sent with
// every message so file operations can be scoped to it. Persists per-browser.
var _workdir=_lsGet('codec_workdir')||'';
function _renderWorkdir(){
var chip=document.getElementById('workdirChip');
if(_workdir){document.getElementById('workdirPath').textContent=_workdir;chip.style.display='flex'}
else{chip.style.display='none'}
}
function pickWorkingFolder(){
fetch('/api/pick-folder',{method:'POST'}).then(function(r){return r.json()}).then(function(j){
if(j&&j.ok&&j.path){_workdir=j.path;_lsSet('codec_workdir',_workdir);_renderWorkdir();
showToast('Working folder: '+_workdir)}
else if(j&&j.cancelled){/* user dismissed — no-op */}
else{showToast((j&&j.error)||'Could not open folder picker')}
}).catch(function(){showToast('Folder picker unavailable')});
}
function clearWorkingFolder(){_workdir='';_lsDel('codec_workdir');_renderWorkdir();}
_renderWorkdir();
var chatHist=[],isProcessing=false;
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)}
// execCommand fallback for when navigator.clipboard is unavailable — it is
// undefined on any non-secure origin, so plain-http LAN access (http://<ip>:8090)
// lands here even though the Cloudflare HTTPS host does not.
// iOS Safari needs all three of: contentEditable, a Range selection (plain
// .select() is ignored), and NO pointer-events:none — that last one silently
// blocks the selection, which is why the old fallback never worked on the phone.
// 16px font-size stops iOS from zooming the viewport while the node is focused.
// ── Reply stats ───────────────────────────────────────────────────────────
// The backend emits one {stats:{…}} SSE frame after the stream finishes.
// elapsed_s is wall time as the user experienced it (a cold model load is
// included on purpose — that IS the wait). tok/s comes from the server's own
// completion_tokens, so it is measured, not estimated.
var _lastStats = null;
function _fmtModel(id){ return String(id||'').split('/').pop().replace('-4bit',''); }
function renderStats(msgEl, st){
try{
var meta = msgEl.querySelector('.msg-meta'); if(!meta) return;
var bits = [];
bits.push((st.elapsed_s != null ? st.elapsed_s : '?') + 's');
if(st.completion_tokens != null) bits.push(st.completion_tokens + ' tok');
if(st.tok_per_s != null) bits.push(st.tok_per_s + ' tok/s');
if(st.prompt_s != null && st.gen_s != null) bits.push(st.prompt_s + 's prompt');
if(st.model) bits.push(_fmtModel(st.model));
var span = document.createElement('span');
span.className = 'msg-stats';
span.textContent = bits.join(' · ');
if(st.prompt_tokens != null && st.total_tokens != null){
span.title = st.prompt_tokens + ' prompt + ' + (st.completion_tokens||0) +
' completion = ' + st.total_tokens + ' tokens' +
(st.gen_s != null ? '\n' + st.gen_s + 's generating, ' +
(st.prompt_s||0) + 's processing your prompt' : '');
}
meta.appendChild(span);
}catch(e){}
}
// ── "Memory used" (P2.4): what the reply was given from memory ────────────
// /api/chat sends the sources and counts (never the text) as a `memory` event;
// the button under the reply lists them and links to Settings > Memory.
var _lastMemory = null;
var _MEM_LABEL = { // [one, more than one]
'chat:recent': ['recent chat message', 'recent chat messages'], 'chat:relevant': ['past chat message about this', 'past chat messages about this'],
'voice:recent': ['recent voice line', 'recent voice lines'], 'voice:relevant': ['past voice line about this', 'past voice lines about this'],
'vibe:relevant': ['past Vibe message about this', 'past Vibe messages about this'], 'rules:standing': ['standing rule', 'standing rules'],
'threads:open': ['open thread', 'open threads']
};
function renderMemoryUsed(msgEl, items){
try{
var meta = msgEl.querySelector('.msg-meta'); if(!meta || !items || !items.length) return;
var btn = document.createElement('button');
btn.type = 'button'; btn.className = 'msg-memory'; btn.textContent = 'Memory used';
btn.setAttribute('aria-expanded', 'false');
var panel = document.createElement('div');
panel.className = 'msg-memory-panel'; panel.hidden = true;
var ul = document.createElement('ul');
items.forEach(function(it){
var li = document.createElement('li');
var lb = _MEM_LABEL[it.source + ':' + it.kind] || [it.source + ' ' + it.kind, it.source + ' ' + it.kind];
li.textContent = it.count + ' ' + lb[it.count === 1 ? 0 : 1];
ul.appendChild(li);
});
var a = document.createElement('a');
a.href = '/#memory'; a.textContent = 'See and edit what CODEC remembers';
panel.appendChild(ul); panel.appendChild(a);
btn.addEventListener('click', function(){ panel.hidden = !panel.hidden; btn.setAttribute('aria-expanded', String(!panel.hidden)); });
meta.appendChild(btn);
meta.parentNode.insertBefore(panel, meta.nextSibling);
}catch(e){}
}
// ── Model picker ──────────────────────────────────────────────────────────
// All local models are served by ONE mlx_vlm.server holding a single model at a
// time, so switching unloads the current model and loads the new one. That is a
// real pause (~6-25s here), hence the explicit "loading" state — and why the
// select is disabled while it runs. If the target fails to load the backend
// restores the previous model before replying, so CODEC is never left mute.
var _modelBusy = false;
function loadModels(){
fetch('/api/models').then(function(r){return r.json()}).then(function(d){
var sel=document.getElementById('modelSelect'); if(!sel)return;
sel.innerHTML='';
(d.models||[]).forEach(function(m){
var o=document.createElement('option');
o.value=m.id;
o.textContent=m.label+(m.role?' — '+m.role:'');
if(m.active)o.selected=true;
sel.appendChild(o);
});
sel.dataset.current=d.active||'';
_markPicker(sel,d);
}).catch(function(){});
}
// The picker shows accent when CODEC is running something other than the
// everyday model — a glance tells you which brain answered, without opening it.
function _markPicker(sel,d){
try{
var act=(d.models||[]).filter(function(m){return m.active})[0];
var everyday=!act||/everyday/i.test(act.role||'');
sel.classList.toggle('alt',!everyday);
}catch(e){}
}
function switchModel(){
var sel=document.getElementById('modelSelect');
if(!sel||_modelBusy)return;
var target=sel.value, prev=sel.dataset.current||'';
if(!target||target===prev)return;
_modelBusy=true; sel.disabled=true;
var label=sel.options[sel.selectedIndex].textContent;
showToast('Loading '+label+'…');
var hdrs={'Content-Type':'application/json'};
var cm=document.cookie.match(/codec_csrf=([^;]+)/); if(cm)hdrs['x-csrf-token']=cm[1];
fetch('/api/model',{method:'POST',headers:hdrs,body:JSON.stringify({model:target})})
.then(function(r){return r.json()})
.then(function(d){
if(d.ok){ sel.dataset.current=d.active; showToast('Now using '+label+' ('+(d.detail||'')+')'); loadModels(); }
else { sel.value=d.active||prev; sel.dataset.current=d.active||prev; _retryAfterSwitch=null;
showToast(d.error||'Switch failed — kept the previous model', true); }
})
.catch(function(){ sel.value=prev; _retryAfterSwitch=null; showToast('Switch failed',true); })
.finally(function(){ _modelBusy=false; sel.disabled=false;
// P2.7 "Retry with another model": regenerate the reply once the new model is loaded.
var rd=_retryAfterSwitch; _retryAfterSwitch=null;
if(rd&&rd.isConnected)regenerateResponse(rd); });
}
// ── Create image (docs/CHAT-CREATE-IMAGE-DESIGN.md) ─────────────────────────
// Qwen-Image 2.1 runs on this Mac, one job at a time: ~1 min to load the model,
// then ~46 s per 512 px image. The bubble polls the job and shows its stage.
var _imgMaxRefs=3;
function loadImageStatus(){
fetch('/api/image/status').then(function(r){return r.json()}).then(function(d){
var b=document.getElementById('modeImageBtn');if(!b)return;
if(!d||!d.available){b.style.display='none';return}
b.style.display='';
_imgMaxRefs=d.max_refs||3;
var sel=document.getElementById('imageSize');
if(sel&&Array.isArray(d.sizes)&&d.sizes.length){
sel.innerHTML='';
d.sizes.forEach(function(px,i){var o=document.createElement('option');o.value=px;o.textContent=px+' px'+(i===0?' (~2 min)':'');sel.appendChild(o)});
}
}).catch(function(){});
}
async function sendImage(text){
if(!text){showToast('Describe the image you want',true);return}
var refs=pendingFiles.filter(function(f){return f.type==='imgref'});
var names=refs.map(function(f){return f.name});
addMessage('user',names.length?(names.join('\n')+'\n\n'+text):text);
clearChips();
var div=document.createElement('div');div.className='msg assistant';
var bubble=document.createElement('div');bubble.className='msg-bubble';
var status=document.createElement('div');status.className='img-status';status.textContent='Starting…';
var cancel=document.createElement('button');cancel.className='img-cancel';cancel.textContent='Cancel';
bubble.appendChild(status);bubble.appendChild(cancel);div.appendChild(bubble);
document.getElementById('messages').appendChild(div);scrollBottom();
var body={prompt:text,refs:refs.map(function(f){return f.content}),count:1,
size:parseInt(document.getElementById('imageSize').value,10)||512,
transparent:!!document.getElementById('imageTransparent').checked};
var d;
try{var r=await fetch('/api/image/jobs',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});d=await r.json()}
catch(e){status.textContent='Could not start the image.';cancel.remove();return}
if(!d||!d.ok){status.textContent=(d&&d.error)||'Could not start the image.';cancel.remove();return}
var id=d.job.id;
cancel.onclick=function(){cancel.disabled=true;fetch('/api/image/jobs/'+id+'/cancel',{method:'POST'}).catch(function(){})};
_pollImage(id,status,cancel,bubble);
}
function _pollImage(id,status,cancel,bubble){
(async function tick(){
var j;
try{var r=await fetch('/api/image/jobs/'+id);var d=await r.json();j=d&&d.job}catch(e){setTimeout(tick,3000);return}
if(!j){status.textContent='This image job was not found.';cancel.remove();return}
if(j.state==='queued'){status.textContent='Waiting for the image before it to finish ('+(j.position||1)+' in line)…'}
else if(j.state==='running'){
status.textContent=j.stage==='loading'?'Loading the image model on this Mac (about 1 min)…':
'Creating the image… step '+(j.step||0)+' of '+(j.steps||'?')+(j.count>1?' (image '+j.image+' of '+j.count+')':'');
}else if(j.state==='done'){
cancel.remove();status.textContent='Created on this Mac in '+Math.round(j.seconds||0)+' s.';
(j.results||[]).forEach(function(u){
if(!/^\/api\/image\/file\/[0-9a-f]{12}\/\d{2}\.png$/.test(u))return;
var a=document.createElement('a');a.href=u;a.title='Open';
a.addEventListener('click',function(ev){ev.preventDefault();openLightbox(u,'codec-image-'+id+'.png',a)}); // P2.12 lightbox
var im=document.createElement('img');im.src=u;im.alt=j.prompt||'Created image';im.className='gen-img';im.onload=scrollBottom;
a.appendChild(im);bubble.appendChild(a);
var dl=document.createElement('a');dl.href=u;dl.download='codec-image-'+id+'.png';dl.textContent='Download';dl.className='gen-dl';
bubble.appendChild(dl);
});
scrollBottom();return;
}else{
cancel.remove();status.textContent=j.state==='cancelled'?'Cancelled.':(j.error||'The image could not be created.');return;
}
setTimeout(tick,2000);
})();
}
function _copyFallback(text){
try{
var ta=document.createElement('textarea');
ta.value=text;
ta.contentEditable='true';
ta.readOnly=false;
ta.style.position='fixed';
ta.style.top='0';ta.style.left='0';
ta.style.width='1px';ta.style.height='1px';
ta.style.padding='0';ta.style.border='none';ta.style.outline='none';
ta.style.boxShadow='none';ta.style.background='transparent';
ta.style.fontSize='16px';
ta.style.opacity='0';
document.body.appendChild(ta);
var sel=window.getSelection();
var range=document.createRange();
range.selectNodeContents(ta);
sel.removeAllRanges();sel.addRange(range);
ta.setSelectionRange(0,ta.value.length);
ta.focus();
var ok=document.execCommand('copy');
sel.removeAllRanges();
document.body.removeChild(ta);
return ok;
}catch(e){return false}
}
// ── Step 10 Q11: Project-promotion suggestion chip (2026-07) ──
// Backend emits {escalate_project:{estimated_checkpoints,reason}} after a
// task-shaped chat reply. "Start as Project" pre-fills the input in Project
// mode (user still hits send — no surprise dispatch); "No thanks" silences
// the suggestion for this session.
var _lastEscalateText='';
function renderEscalateChip(sugg,userText){
_lastEscalateText=userText||'';
var n=sugg&&sugg.estimated_checkpoints?sugg.estimated_checkpoints:'several';
var div=document.createElement('div');div.className='msg assistant';
div.innerHTML='<div class="msg-bubble" style="border:1px dashed var(--accent);background:var(--accent-dim)">'+
'<div style="font-weight:600;margin-bottom:6px">This looks like a multi-step project (~'+escHtml(String(n))+' checkpoints)</div>'+
'<div style="font-size:calc(12px * var(--fs-scale));color:var(--text-dim);margin-bottom:8px">CODEC can draft a plan, ask for your approval once, then run it autonomously in the background.</div>'+
'<div style="display:flex;gap:8px">'+
'<button onclick="escalateStartProject(this)" style="padding:6px 14px;background:var(--accent);color:var(--on-accent);border:none;border-radius:6px;cursor:pointer;font-size:calc(12px * var(--fs-scale));font-weight:600">Start as Project</button>'+
'<button onclick="escalateDismiss(this)" style="padding:6px 14px;background:transparent;color:var(--text);border:1px solid var(--border,#2a2a30);border-radius:6px;cursor:pointer;font-size:calc(12px * var(--fs-scale))">No thanks</button>'+
'</div></div>';
document.getElementById('messages').appendChild(div);scrollBottom();
}
function escalateStartProject(btn){
setMode('project');
var input=document.getElementById('chatInput');
input.value=_lastEscalateText;input.focus();
var card=btn.closest('.msg');if(card)card.remove();
showToast('Project mode — hit send to draft the plan');
}
function escalateDismiss(btn){
try{fetch('/api/chat/escalate_silence',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({session_id:(typeof sessionId!=='undefined'&&sessionId)||''})})}catch(e){}
var card=btn.closest('.msg');if(card)card.remove();
}
// ── Conversational create_skill (beat 21) ──
// Backend emits {skill_confirm:{description}} after briefing the user. "Build it"
// runs the real create_skill review-gate flow via /api/chat/build_skill; the
// outcome is dropped back into the chat. Nothing is built until the user clicks.
var _lastSkillDesc='';
function renderSkillConfirmChip(info,userText){
_lastSkillDesc=(info&&info.description)||'';
var div=document.createElement('div');div.className='msg assistant';
div.innerHTML='<div class="msg-bubble" style="border:1px dashed var(--accent);background:var(--accent-dim)">'+
'<div style="font-weight:600;margin-bottom:6px">Build this skill?</div>'+
'<div style="font-size:calc(12px * var(--fs-scale));color:var(--text-dim);margin-bottom:8px">'+escHtml(_lastSkillDesc)+' — I\'ll generate it and stage it in your Skills tab for review. Nothing runs until you approve it there.</div>'+
'<div style="display:flex;gap:8px">'+
'<button onclick="skillConfirmBuild(this)" style="padding:6px 14px;background:var(--accent);color:var(--on-accent);border:none;border-radius:6px;cursor:pointer;font-size:calc(12px * var(--fs-scale));font-weight:600">Build it</button>'+
'<button onclick="skillConfirmCancel(this)" style="padding:6px 14px;background:transparent;color:var(--text);border:1px solid var(--border,#2a2a30);border-radius:6px;cursor:pointer;font-size:calc(12px * var(--fs-scale))">Cancel</button>'+
'</div></div>';
document.getElementById('messages').appendChild(div);scrollBottom();
}
function skillConfirmBuild(btn){
var desc=_lastSkillDesc;var card=btn.closest('.msg');
if(card){var b=card.querySelector('.msg-bubble');if(b)b.innerHTML='<span style="color:var(--text-dim)">Building the skill…</span>';}
fetch('/api/chat/build_skill',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({description:desc})})
.then(function(r){return r.json()})
.then(function(d){if(card)card.remove();var div=document.createElement('div');div.className='msg assistant';
var bub=document.createElement('div');bub.className='msg-bubble';div.appendChild(bub);mdRender(bub,d.response||'Done.');
document.getElementById('messages').appendChild(div);scrollBottom();})
.catch(function(e){if(card)card.remove();showToast('Build failed: '+e,true);});
}
function skillConfirmCancel(btn){var card=btn.closest('.msg');if(card)card.remove();}
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 iBtn=document.getElementById('modeImageBtn');
if(iBtn)iBtn.classList.toggle('active',mode==='image');
var iOpts=document.getElementById('imageOpts');
if(iOpts)iOpts.style.display=mode==='image'?'flex':'none';
// Reference images belong to Image mode only; drop them when leaving it.
if(mode!=='image')pendingFiles.filter(function(f){return f.type==='imgref'}).forEach(function(f){removeChip(f.id)});
var cs=document.getElementById('crewSelect');
var crew=mode==='research'?cs.value:'deep_research';
// Deep Research restricts the model to 35B/27B: show the research picker and
// hide the normal chat model picker so no other (voice/4B) model is selectable.
var _rms=document.getElementById('researchModelSelect');
var _showRms=(mode==='research'&&crew==='deep_research');
var _rmr=document.getElementById('researchModelRow');
if(_rmr)_rmr.style.display=_showRms?'flex':'none';
var _msel=document.getElementById('modelSelect');
if(_msel){var _mnode=(_msel.__csMenu&&_msel.__csMenu.wrap)||_msel;_mnode.style.display=(_showRms||mode==='image')?'none':(_msel.__csMenu?'inline-flex':'inline-block')}
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});