Spaces:
Running on Zero

File size: 43,900 Bytes
b7f34d4
 
 
 
 
 
 
 
 
a41ee62
 
 
 
 
 
 
 
b7f34d4
a41ee62
 
 
 
b7f34d4
a41ee62
b7f34d4
 
 
 
 
 
a41ee62
 
 
 
 
 
 
 
b7f34d4
 
 
 
a41ee62
b7f34d4
 
 
a41ee62
 
b7f34d4
a41ee62
 
b7f34d4
a41ee62
 
b7f34d4
 
a41ee62
 
 
 
 
 
 
 
 
 
 
 
 
b7f34d4
a41ee62
b7f34d4
 
 
 
a41ee62
 
 
 
 
b7f34d4
a41ee62
b7f34d4
 
a41ee62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7f34d4
 
a41ee62
 
b7f34d4
 
a41ee62
 
 
 
 
 
 
 
b7f34d4
a41ee62
 
b7f34d4
 
a41ee62
 
 
 
 
 
b7f34d4
 
 
a41ee62
 
 
b7f34d4
a41ee62
b7f34d4
 
a41ee62
 
b7f34d4
 
a41ee62
 
 
 
 
 
 
 
 
 
 
b7f34d4
 
a41ee62
 
b7f34d4
 
a41ee62
 
b7f34d4
a41ee62
 
b7f34d4
a41ee62
 
 
 
b7f34d4
a41ee62
 
b7f34d4
 
 
a41ee62
 
b7f34d4
 
 
a41ee62
b7f34d4
a41ee62
 
 
b7f34d4
 
a41ee62
 
b7f34d4
a41ee62
 
b7f34d4
 
a41ee62
 
 
b7f34d4
 
a41ee62
 
b7f34d4
a41ee62
b7f34d4
a41ee62
b7f34d4
a41ee62
 
 
 
b7f34d4
 
a41ee62
b7f34d4
a41ee62
 
b7f34d4
 
 
a41ee62
b7f34d4
 
a41ee62
b7f34d4
 
 
 
a41ee62
b7f34d4
 
 
 
 
 
a41ee62
 
b7f34d4
 
a41ee62
 
 
 
b7f34d4
 
 
a41ee62
 
b7f34d4
a41ee62
 
b7f34d4
 
 
a41ee62
 
 
 
 
b7f34d4
 
a41ee62
 
b7f34d4
 
a41ee62
 
b7f34d4
 
 
a41ee62
b7f34d4
a41ee62
b7f34d4
 
a41ee62
 
b7f34d4
a41ee62
b7f34d4
 
a41ee62
 
 
b7f34d4
a41ee62
b7f34d4
 
 
a41ee62
 
b7f34d4
a41ee62
b7f34d4
a41ee62
 
 
 
b7f34d4
 
a41ee62
b7f34d4
a41ee62
b7f34d4
a41ee62
 
 
 
b7f34d4
a41ee62
 
b7f34d4
 
a41ee62
 
b7f34d4
 
 
a41ee62
b7f34d4
 
 
 
 
a41ee62
 
 
 
b7f34d4
a41ee62
 
b7f34d4
 
 
 
 
 
a41ee62
b7f34d4
 
a41ee62
 
 
 
b7f34d4
 
 
a41ee62
 
 
 
 
b7f34d4
a41ee62
 
 
 
 
b7f34d4
a41ee62
 
 
b7f34d4
 
 
 
 
a41ee62
 
 
 
 
 
 
 
 
 
b7f34d4
a41ee62
 
 
b7f34d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a41ee62
 
 
 
 
 
 
 
 
 
 
 
b7f34d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a41ee62
b7f34d4
 
 
 
 
 
a41ee62
b7f34d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a41ee62
 
b7f34d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a41ee62
b7f34d4
 
 
 
 
a41ee62
 
b7f34d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a41ee62
b7f34d4
 
 
 
 
 
 
 
a41ee62
 
b7f34d4
 
 
 
 
 
 
 
 
a41ee62
b7f34d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a41ee62
b7f34d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>SenseNova-Loop-9B Studio</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fontsource-variable/inter@5/index.css" />
<style>
  :root {
    --bg: #fbfbfe;
    --panel: #ffffff;
    --inset: #f6f6fb;
    --border: #ececf4;
    --border-lit: #dcdce8;
    --text: #17171f;
    --muted: #6b7280;
    --dim: #9aa0ae;
    --accent: #7c5cf0;
    --accent-blue: #3b82f6;
    --accent-teal: #2dd4bf;
    --accent-soft-bg: #f3efff;
    --good: #1f9d63;
    --mono: "SFMono-Regular", ui-monospace, "Cascadia Mono", Menlo, Consolas, monospace;
    --serif: Georgia, "Times New Roman", "Songti SC", "SimSun", serif;
  }
  * { margin: 0; padding: 0; box-sizing: border-box; }
  [hidden] { display: none !important; }
  html { height: 100%; }
  body {
    font-family: "Inter Variable", "Inter", ui-sans-serif, system-ui, sans-serif;
    background:
      radial-gradient(720px 340px at 50% -120px, rgba(139, 92, 246, 0.20), transparent 70%),
      radial-gradient(560px 300px at 72% -100px, rgba(59, 130, 246, 0.14), transparent 70%),
      radial-gradient(520px 300px at 28% -100px, rgba(45, 212, 191, 0.10), transparent 70%),
      var(--bg);
    background-attachment: fixed;
    color: var(--text);
    min-height: 100vh; padding-bottom: 40px;
    -webkit-font-smoothing: antialiased;
  }
  button:focus-visible, a:focus-visible, textarea:focus-visible,
  select:focus-visible, input:focus-visible, summary:focus-visible {
    outline: 2px solid #c9b8ff; outline-offset: 1px;
  }
  ::-webkit-scrollbar { width: 8px; height: 8px; }
  ::-webkit-scrollbar-track { background: transparent; }
  ::-webkit-scrollbar-thumb { background: #d5d5e2; border-radius: 4px; }
  ::-webkit-scrollbar-thumb:hover { background: #c2c2d4; }

  /* ---------- top nav ---------- */
  .snav {
    position: sticky; top: 0; z-index: 30;
    display: flex; align-items: center; gap: 18px; height: 54px; padding: 0 18px;
    background: rgba(255, 255, 255, 0.82); backdrop-filter: blur(10px);
    border-bottom: 1px solid var(--border);
  }
  .sbrand { display: flex; align-items: center; gap: 9px; text-decoration: none; color: var(--text); white-space: nowrap; }
  .sbrand .mark { width: 24px; height: 24px; flex-shrink: 0; border-radius: 5px; }
  .sbrand .name { font-family: var(--serif); font-size: 1.02rem; letter-spacing: 0.01em; }
  .sbrand .name b { font-weight: 700; }
  .sbrand .thin { color: var(--muted); }
  .slinks { display: flex; gap: 4px; margin-left: 10px; }
  .slinks button {
    border: none; background: transparent; padding: 6px 12px; cursor: pointer;
    font: 550 0.82rem/1 inherit; font-family: inherit; color: var(--muted);
    border-bottom: 2px solid transparent; transition: color 0.12s;
  }
  .slinks button:hover { color: var(--text); }
  .slinks button.active { color: var(--text); border-bottom-color: var(--accent); }
  .spacer { flex: 1; }
  .toplink { color: var(--muted); text-decoration: none; font-size: 0.78rem; font-weight: 550; white-space: nowrap; }
  .toplink:hover { color: var(--text); }
  .hdr-badge { display: inline-flex; align-items: center; height: 22px; flex-shrink: 0; }
  .hdr-badge img { height: 22px; display: block; }
  .hdr-cta {
    display: inline-flex; align-items: center; gap: 6px; height: 28px; padding: 0 14px;
    background: #111; color: #fff; border-radius: 999px;
    font: 600 0.68rem/1 inherit; font-family: inherit;
    letter-spacing: 0.03em; text-decoration: none; white-space: nowrap; flex-shrink: 0;
    transition: background 0.12s, transform 0.08s;
  }
  .hdr-cta:hover { background: #2c2c34; }
  .hdr-cta:active { transform: translateY(1px); }

  /* ---------- hero ---------- */
  .hero {
    position: relative; text-align: center; padding: 26px 20px 18px;
    max-width: 880px; margin: 0 auto; overflow: visible;
  }
  .hero h1 { font-family: var(--serif); font-weight: 500; font-size: 2rem; letter-spacing: 0.005em; }
  .hero p { margin: 8px auto 0; max-width: 640px; color: var(--muted); font-size: 0.84rem; line-height: 1.55; }
  .chips { display: flex; justify-content: center; flex-wrap: wrap; gap: 6px; margin-top: 12px; }
  .chips span {
    border: 1px solid var(--border-lit); background: rgba(255, 255, 255, 0.75);
    color: #4b4b5c; border-radius: 999px; padding: 4px 11px;
    font: 550 0.66rem/1 inherit; letter-spacing: 0.04em;
  }

  /* mosaic pixel clusters (SenseNova signature) */
  .pixels { position: absolute; width: 7px; height: 7px; pointer-events: none; }
  .hero-pixels {
    right: 6%; top: 8px;
    box-shadow:
      14px 0 #8b5cf6, 21px 0 #8b5cf655, 28px 7px #3b82f6, 7px 7px #a78bfa88,
      21px 14px #2dd4bf99, 35px 14px #3b82f666, 14px 21px #8b5cf633, 42px 7px #a78bfa44,
      28px 21px #2dd4bf55, 49px 21px #8b5cf622, 7px 28px #3b82f633, 35px 28px #a78bfa33,
      21px 35px #2dd4bf33, 49px 0 #3b82f622, 42px 35px #8b5cf618, 56px 14px #2dd4bf30;
  }
  .hero-pixels-l {
    left: 6%; bottom: 0;
    box-shadow:
      0 7px #3b82f655, 7px 0 #8b5cf633, 14px 7px #2dd4bf55, 21px 14px #a78bfa55,
      28px 7px #8b5cf622, 7px 21px #3b82f633, 35px 21px #2dd4bf33, 28px 28px #8b5cf622;
  }
  .card-pixels {
    right: 14px; bottom: 12px; opacity: 0.8;
    box-shadow:
      0 0 #8b5cf644, 7px 7px #3b82f633, 14px 0 #2dd4bf44, 21px 7px #a78bfa33,
      7px 14px #8b5cf622, 28px 14px #3b82f622, 14px 21px #2dd4bf22;
  }

  /* ---------- layout ---------- */
  .studio-grid {
    display: grid; grid-template-columns: 320px minmax(0, 1fr); gap: 12px;
    width: calc(100vw - 28px); max-width: 1500px; margin: 4px auto 0; align-items: start;
    transition: grid-template-columns 0.15s ease;
  }
  #studio-view.no-rail .studio-grid { grid-template-columns: minmax(0, 1fr); }
  #studio-view.no-rail #session-panel { display: none; }
  .panel {
    position: relative; background: var(--panel); border: 1px solid var(--border);
    border-radius: 14px; overflow: hidden;
    box-shadow: 0 1px 3px rgba(30, 30, 60, 0.05);
  }
  .chat-panel { display: flex; flex-direction: column; height: calc(100vh - 224px); min-height: 460px; position: sticky; top: 66px; }
  .panel-head {
    display: flex; align-items: center; gap: 8px; padding: 9px 14px;
    background: var(--panel); border-bottom: 1px solid var(--border);
    flex-wrap: wrap; row-gap: 6px;
  }
  .p-title { font: 650 0.8rem/1 inherit; letter-spacing: 0.01em; color: var(--text); }
  .p-sub { font: 500 0.66rem/1 var(--mono); color: var(--dim); letter-spacing: 0.04em; }
  .p-dot {
    width: 7px; height: 7px; flex-shrink: 0; border-radius: 2px;
    background: linear-gradient(135deg, var(--accent) 0%, var(--accent-blue) 60%, var(--accent-teal) 100%);
  }
  .mono { font-family: var(--mono); font-variant-numeric: tabular-nums; }
  .icon-btn {
    display: inline-flex; align-items: center; justify-content: center;
    width: 24px; height: 24px; border: 1px solid var(--border-lit); border-radius: 999px;
    background: #fff; color: var(--muted); cursor: pointer; font-size: 0.7rem;
    transition: all 0.12s; flex-shrink: 0;
  }
  .icon-btn:hover { border-color: var(--accent); color: var(--accent); }

  /* ---------- session rail ---------- */
  .input-body { padding: 14px; display: flex; flex-direction: column; gap: 12px; }
  .field-label { font: 600 0.62rem/1 inherit; letter-spacing: 0.1em; text-transform: uppercase; color: var(--dim); }
  select, input[type="number"] {
    font-family: inherit; color: var(--text);
    background: var(--inset); border: 1px solid var(--border); border-radius: 9px; outline: none;
    transition: border-color 0.12s, box-shadow 0.12s;
  }
  select:focus, input[type="number"]:focus { border-color: #c9b8ff; box-shadow: 0 0 0 3px #7c5cf01f; background: #fff; }
  .ctl-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
  .ctl { display: flex; flex-direction: column; gap: 5px; }
  select { appearance: none; -webkit-appearance: none; width: 100%; padding: 8px 26px 8px 10px; font-size: 0.78rem; cursor: pointer;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 24 24' fill='none' stroke='%236b7280' stroke-width='3' stroke-linecap='round'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E");
    background-repeat: no-repeat; background-position: right 9px center; }
  input[type="number"] { width: 100%; padding: 8px 10px; font-size: 0.78rem; font-family: var(--mono); }
  .switch { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; font-size: 0.76rem; color: var(--muted); user-select: none; }
  .switch input { display: none; }
  .switch .sw {
    width: 30px; height: 17px; border-radius: 999px; background: #e4e4ee;
    border: 1px solid var(--border-lit); position: relative; transition: background 0.12s; flex-shrink: 0;
  }
  .switch .sw::after {
    content: ""; position: absolute; top: 2px; left: 2px; width: 11px; height: 11px; border-radius: 999px;
    background: #fff; box-shadow: 0 1px 2px rgba(0,0,0,0.18); transition: transform 0.12s;
  }
  .switch input:checked + .sw { background: var(--accent); border-color: var(--accent); }
  .switch input:checked + .sw::after { transform: translateX(13px); }
  #new-chat {
    width: 100%; border: 1px solid var(--border-lit); border-radius: 999px; padding: 9px;
    background: #fff; color: var(--text);
    font: 600 0.76rem/1 inherit; font-family: inherit; letter-spacing: 0.02em;
    cursor: pointer; transition: all 0.12s;
  }
  #new-chat:hover { border-color: #111; }
  .cold-hint { font: 500 0.64rem/1.6 inherit; color: var(--dim); text-align: center; }

  .presets { border-top: 1px solid var(--border); }
  .presets summary {
    display: flex; align-items: center; gap: 8px; padding: 10px 14px;
    font: 600 0.62rem/1 inherit; letter-spacing: 0.1em; text-transform: uppercase;
    color: var(--dim); cursor: pointer; user-select: none; list-style: none;
  }
  .presets summary::-webkit-details-marker { display: none; }
  .presets summary::before { content: "▸"; font-size: 0.7rem; color: var(--accent); transition: transform 0.12s; display: inline-block; }
  .presets[open] summary::before { transform: rotate(90deg); }
  .presets summary:hover { color: var(--text); }
  .preset-grid { display: flex; flex-direction: column; gap: 3px; margin-top: 2px; max-height: 300px; overflow-y: auto; padding: 0 12px 12px; }
  .preset-group { font: 650 0.6rem/1 inherit; letter-spacing: 0.12em; text-transform: uppercase; color: var(--accent); padding: 8px 8px 3px; }
  .preset {
    text-align: left; border: 1px solid transparent; background: transparent; color: var(--muted);
    border-radius: 8px; padding: 6px 9px; font: 500 0.76rem/1.35 inherit; font-family: inherit; cursor: pointer;
    transition: all 0.1s; display: flex; gap: 8px; align-items: baseline;
  }
  .preset:hover { background: var(--accent-soft-bg); border-color: #e4dbff; color: var(--text); }
  .preset .idx { font: 600 0.6rem/1 var(--mono); color: #b9a8f5; flex-shrink: 0; }

  /* ---------- thread ---------- */
  .thread-wrap { flex: 1; overflow-y: auto; padding: 18px 16px 10px; }
  .thread { max-width: 820px; margin: 0 auto; display: flex; flex-direction: column; gap: 18px; }
  .msg { display: flex; flex-direction: column; gap: 7px; }
  .msg.user { align-items: flex-end; }
  .msg.user .bubble {
    max-width: 82%; background: #f2f2f9; border: 1px solid #e6e6f1; border-radius: 14px 14px 4px 14px;
    padding: 9px 13px; font-size: 0.85rem; line-height: 1.55; white-space: pre-wrap; word-break: break-word;
  }
  .msg.user .thumbs-in { display: flex; gap: 6px; flex-wrap: wrap; justify-content: flex-end; }
  .msg.user .thumbs-in img {
    width: 88px; height: 88px; object-fit: cover; border: 1px solid var(--border-lit); border-radius: 10px; cursor: pointer;
  }
  .msg.bot { border-left: 2px solid #d9ccff; padding-left: 14px; }
  .meta-line { font: 500 0.62rem/1 var(--mono); color: var(--dim); letter-spacing: 0.03em; }
  .answer { font-size: 0.86rem; line-height: 1.65; word-break: break-word; color: #23232e; }
  .answer.cursor::after { content: "▊"; color: var(--accent); animation: blink 0.9s steps(1) infinite; }
  @keyframes blink { 50% { opacity: 0; } }

  details.think { border: 1px solid var(--border); background: #fafaff; border-radius: 10px; }
  details.think summary {
    padding: 8px 12px; font: 600 0.66rem/1 inherit; letter-spacing: 0.09em; text-transform: uppercase;
    color: var(--accent); cursor: pointer; user-select: none; list-style: none;
    display: flex; align-items: center; gap: 8px;
  }
  details.think summary::-webkit-details-marker { display: none; }
  details.think summary::before { content: "▸"; color: #b9a8f5; transition: transform 0.12s; }
  details.think[open] summary::before { transform: rotate(90deg); }
  .spin {
    width: 9px; height: 9px; border: 1.5px solid var(--accent); border-top-color: transparent;
    border-radius: 50%; animation: spin 0.8s linear infinite; flex-shrink: 0;
  }
  @keyframes spin { to { transform: rotate(360deg); } }
  pre.think-body {
    padding: 2px 14px 12px; font: 450 0.74rem/1.6 var(--mono); color: #8a8aa5; font-style: italic;
    white-space: pre-wrap; word-break: break-word; max-height: 320px; overflow-y: auto;
  }

  /* markdown in answers */
  .md p { margin: 0 0 8px; }
  .md p:last-child { margin-bottom: 0; }
  .md h3, .md h4, .md h5, .md h6 { margin: 13px 0 6px; font-size: 0.98rem; font-family: var(--serif); }
  .md h4, .md h5, .md h6 { font-size: 0.9rem; }
  .md ul, .md ol { margin: 4px 0 8px 20px; }
  .md li { margin: 3px 0; }
  .md code { font: 0.82em var(--mono); background: #f2f2f8; border: 1px solid var(--border); border-radius: 5px; padding: 1px 5px; }
  .md pre.md-code { background: #17191f; border: none; border-radius: 10px; padding: 12px 14px; overflow-x: auto; margin: 7px 0 10px; }
  .md pre.md-code code { background: none; border: none; padding: 0; font-size: 0.74rem; line-height: 1.55; color: #b8c2d4; display: block; white-space: pre; }
  .md a { color: var(--accent); }

  .thread-placeholder {
    display: flex; flex-direction: column; align-items: center; justify-content: center;
    gap: 8px; color: var(--dim); font: 500 0.78rem/1.7 inherit; letter-spacing: 0.02em;
    text-align: center; padding: 64px 20px;
  }
  .thread-placeholder .big { font-size: 1.6rem; opacity: 0.6; }
  .thread-placeholder .ttl { font-family: var(--serif); font-size: 1.1rem; color: var(--muted); }

  /* ---------- transport ---------- */
  .transport {
    background: var(--inset); border-top: 1px solid var(--border);
    padding: 7px 12px 8px;
  }
  .t-row { display: flex; align-items: center; gap: 6px; }
  .t-track { display: flex; align-items: center; gap: 4px; flex: 1; min-width: 0; }
  .t-stage {
    position: relative; flex: 1; text-align: center;
    font: 600 0.58rem/1 inherit; letter-spacing: 0.12em; color: var(--dim);
    padding: 6px 0 5px; border-radius: 999px; background: #fff; border: 1px solid var(--border);
    transition: all 0.15s; overflow: hidden; white-space: nowrap;
  }
  .t-stage.lit { background: var(--accent-soft-bg); color: var(--accent); border-color: #d9ccff; }
  .t-stage.ok { background: #e9f8f1; color: var(--good); border-color: #c8ecd9; }
  .t-readout { font: 600 0.64rem/1 var(--mono); color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; }

  /* ---------- composer ---------- */
  .composer { padding: 10px 14px 12px; display: flex; flex-direction: column; gap: 8px; background: var(--panel); border-top: 1px solid var(--border); }
  .thumbs { display: flex; gap: 6px; flex-wrap: wrap; }
  .thumb { position: relative; width: 54px; height: 54px; border: 1px solid var(--border-lit); border-radius: 9px; overflow: hidden; }
  .thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
  .thumb button {
    position: absolute; top: 2px; right: 2px; width: 15px; height: 15px;
    background: #0009; color: #fff; border: none; border-radius: 999px; font-size: 9px; cursor: pointer; line-height: 1;
  }
  .composer-row { display: flex; gap: 8px; align-items: flex-end; }
  textarea {
    font-family: inherit; color: var(--text); flex: 1;
    background: var(--inset); border: 1px solid var(--border); border-radius: 12px; outline: none;
    padding: 10px 12px; font-size: 0.85rem; line-height: 1.45; resize: none;
    min-height: 42px; max-height: 160px; transition: border-color 0.12s, box-shadow 0.12s, background 0.12s;
  }
  textarea:focus { border-color: #c9b8ff; box-shadow: 0 0 0 3px #7c5cf01f; background: #fff; }
  textarea::placeholder { color: var(--dim); }
  #attach-btn {
    display: inline-flex; align-items: center; justify-content: center;
    width: 40px; height: 40px; border: 1px solid var(--border-lit); border-radius: 999px;
    background: #fff; color: var(--muted); cursor: pointer; font-size: 1rem; transition: all 0.12s; flex-shrink: 0;
  }
  #attach-btn:hover { border-color: var(--accent); color: var(--accent); }
  #send-btn {
    border: none; border-radius: 999px; padding: 0 22px; height: 40px;
    background: #111; color: #fff;
    font: 650 0.78rem/1 inherit; font-family: inherit; letter-spacing: 0.04em;
    cursor: pointer; transition: background 0.12s, transform 0.08s; flex-shrink: 0;
    -webkit-tap-highlight-color: transparent;
  }
  #send-btn:hover:not(:disabled) { background: #2c2c34; }
  #send-btn:active:not(:disabled) { transform: translateY(1px); }
  #send-btn:disabled { opacity: 0.4; cursor: wait; }
  #stop-btn {
    border: 1px solid #efc5c5; border-radius: 999px; padding: 0 16px; height: 40px;
    background: #fff5f5; color: #c44;
    font: 650 0.74rem/1 inherit; font-family: inherit; letter-spacing: 0.04em;
    cursor: pointer; transition: all 0.12s; flex-shrink: 0;
  }
  #stop-btn:hover { background: #ffeaea; }
  .kb-hint { font: 450 0.62rem/1 var(--mono); color: var(--dim); text-align: right; }
  .kb-hint kbd {
    font: 600 0.58rem/1 var(--mono); color: var(--muted);
    border: 1px solid var(--border-lit); border-bottom-width: 2px; border-radius: 4px;
    padding: 1px 5px; background: #fff;
  }

  /* workflow view */
  #workflow-view { position: fixed; inset: 55px 0 39px 0; z-index: 5; background: var(--bg); }
  #workflow-view iframe { width: 100%; height: 100%; border: none; }

  /* status bar */
  .statusbar {
    position: fixed; left: 0; right: 0; bottom: 0; z-index: 30;
    display: flex; align-items: center; gap: 9px; padding: 0 16px; height: 28px;
    background: rgba(255, 255, 255, 0.88); backdrop-filter: blur(10px);
    border-top: 1px solid var(--border);
    font: 500 0.66rem/1 var(--mono); color: var(--muted);
  }
  .pulse { width: 7px; height: 7px; border-radius: 999px; background: var(--good); flex-shrink: 0; }
  .statusbar.busy .pulse { background: var(--accent); animation: pulse 1s ease-in-out infinite; }
  @keyframes pulse { 50% { opacity: 0.3; } }
  #seed-out { font-variant-numeric: tabular-nums; color: var(--dim); }

  /* ---------- tablet ---------- */
  @media (max-width: 1000px) {
    .studio-grid { grid-template-columns: 1fr; }
    .chat-panel { position: static; height: 76vh; }
    .toplink:not(.no-hide), .hdr-badge, .hdr-cta { display: none; }
    #rail-hide { display: none; }
    .hero p { display: none; }
    .hero { padding: 18px 16px 12px; }
    .hero h1 { font-size: 1.5rem; }
    .chat-panel { height: calc(100vh - 190px); }
  }
  /* ---------- phone ---------- */
  @media (max-width: 640px) {
    body { padding-bottom: 38px; }
    .snav { height: 50px; padding: 0 12px; gap: 10px; }
    .sbrand .name { font-size: 0.9rem; }
    .slinks { margin-left: 2px; }
    .slinks button { padding: 6px 8px; font-size: 0.76rem; }
    .toplink { display: none; }
    .hero { padding: 14px 12px 8px; }
    .hero h1 { font-size: 1.25rem; }
    .chips span { font-size: 0.6rem; padding: 3px 9px; }
    .studio-grid { width: calc(100vw - 12px); gap: 8px; }
    .chat-panel { height: calc(100vh - 180px); min-height: 380px; }
    .msg.user .bubble { max-width: 92%; }
    .statusbar { height: 26px; padding: 0 10px; font-size: 0.6rem; }
    #seed-out, .kb-hint { display: none; }
    #workflow-view { inset: 51px 0 36px 0; }
  }
</style>
</head>
<body>

<header class="snav">
  <a class="sbrand" href="/">
    <svg class="mark" viewBox="0 0 28 28" aria-hidden="true">
      <rect x="1" y="1" width="8" height="8" rx="1.5" fill="#3b82f6"/>
      <rect x="11" y="1" width="8" height="8" rx="1.5" fill="#8b5cf6"/>
      <rect x="1" y="11" width="8" height="8" rx="1.5" fill="#6366f1"/>
      <rect x="11" y="11" width="8" height="8" rx="1.5" fill="#a78bfa"/>
      <rect x="1" y="21" width="8" height="6" rx="1.5" fill="#2dd4bf"/>
      <rect x="11" y="21" width="8" height="6" rx="1.5" fill="#8b5cf6" opacity="0.5"/>
      <rect x="21" y="11" width="6" height="8" rx="1.5" fill="#2dd4bf" opacity="0.7"/>
    </svg>
    <span class="name"><b>SenseNova</b> <span class="thin">Loop Studio</span></span>
  </a>
  <nav class="slinks">
    <button id="mode-studio" class="active">Chat</button>
    <button id="mode-workflow">Workflow</button>
  </nav>
  <div class="spacer"></div>
  <a class="hdr-badge" href="https://hf.co/chat?mode=ml-intern" target="_blank" rel="noopener" title="Built with ML Intern">
    <img src="https://hf.co/datasets/huggingface/badges/resolve/main/built-with-ml-intern-sm.svg" alt="Built with ML Intern" />
  </a>
  <a class="hdr-cta" href="https://hf.co/chat?mode=ml-intern&prompt=Build%20me%20my%20own%20model%20studio%20like%20akhaliq%2Fsensenova-loop-9b" target="_blank" rel="noopener">
    Build your own app here
    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"><path d="M13.5 6H5a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2v-8.5m-10.5 6L21 3m0 0h-5m5 0v5"/></svg>
  </a>
  <a class="toplink no-hide" href="https://huggingface.co/sensenova/SenseNova-Loop-9B" target="_blank" rel="noopener">Model ↗</a>
  <a class="toplink" href="https://github.com/OpenSenseNova/SenseNova-Loop" target="_blank" rel="noopener">GitHub ↗</a>
</header>

<div id="studio-view">
  <section class="hero">
    <div class="pixels hero-pixels"></div>
    <div class="pixels hero-pixels-l"></div>
    <h1>SenseNova-Loop-9B</h1>
    <p>A chat studio for the looped-architecture multimodal model — 32 stored layers executed as 56 with two-stream mHC routing, vision input, thinking mode, and a 512K context.</p>
    <div class="chips">
      <span>Looped ×2</span><span>Two-stream mHC</span><span>Vision</span><span>Thinking</span><span>512K context</span><span>Apache-2.0</span>
    </div>
  </section>

  <main class="studio-grid">

  <!-- ------------- session rail ------------- -->
  <section class="panel" id="session-panel">
    <div class="panel-head">
      <span class="p-dot"></span>
      <span class="p-title">Session</span>
      <div class="spacer"></div>
      <span class="p-sub">zerogpu · bf16</span>
      <button class="icon-btn" id="rail-hide" title="Hide the Session panel">⟨</button>
    </div>
    <div class="input-body">
      <button id="new-chat">+&nbsp; New chat</button>
      <div class="ctl-grid">
        <div class="ctl">
          <span class="field-label">Max new tokens</span>
          <select id="max-tokens">
            <option value="512">512</option>
            <option value="1024" selected>1024</option>
            <option value="2048">2048</option>
            <option value="4096">4096</option>
            <option value="8192">8192</option>
          </select>
        </div>
        <div class="ctl">
          <span class="field-label">Temperature</span>
          <select id="temperature">
            <option value="0">0 · greedy</option>
            <option value="0.3">0.3</option>
            <option value="0.6">0.6</option>
            <option value="1.0" selected>1.0 · default</option>
            <option value="1.5">1.5</option>
          </select>
        </div>
        <div class="ctl">
          <span class="field-label">Top-p</span>
          <select id="top-p">
            <option value="0.8">0.8</option>
            <option value="0.9">0.9</option>
            <option value="0.95" selected>0.95 · default</option>
            <option value="1.0">1.0</option>
          </select>
        </div>
        <div class="ctl">
          <span class="field-label">Seed</span>
          <input type="number" id="seed" value="0" min="0" max="2147483647" />
        </div>
        <div class="ctl" style="justify-content:end">
          <label class="switch"><input type="checkbox" id="thinking" checked /><span class="sw"></span><span>Thinking mode</span></label>
        </div>
        <div class="ctl" style="justify-content:end">
          <label class="switch"><input type="checkbox" id="randomize" checked /><span class="sw"></span><span>Randomize seed</span></label>
        </div>
      </div>
      <p class="cold-hint">Runs locally on ZeroGPU in bf16 — the first message after idle may wait a few seconds for a GPU.</p>
    </div>

    <details class="presets" id="preset-details" open>
      <summary>Preset prompts</summary>
      <div class="preset-grid" id="examples"></div>
    </details>
    <div class="pixels card-pixels"></div>
  </section>

  <!-- ------------- conversation ------------- -->
  <section class="panel chat-panel">
    <div class="panel-head">
      <button class="icon-btn" id="rail-show" title="Show the Session panel" hidden>◧</button>
      <span class="p-dot"></span>
      <span class="p-title">Conversation</span>
      <div class="spacer"></div>
      <span id="ctx-meta" class="mono" style="font-size:0.66rem;color:var(--dim)">0 turns</span>
    </div>

    <div class="thread-wrap" id="thread-scroll">
      <div class="thread" id="thread">
        <div class="thread-placeholder" id="placeholder">
          <div class="big">🔁</div>
          <div class="ttl">How can SenseNova-Loop help today?</div>
          <div style="font-size:0.7rem">pick a preset or write below · attach up to 4 images with 📎</div>
        </div>
      </div>
    </div>

    <div class="transport">
      <div class="t-row">
        <div class="t-track">
          <div class="t-stage" id="st-queue">QUEUED</div>
          <div class="t-stage" id="st-think">THINK</div>
          <div class="t-stage" id="st-write">WRITE</div>
          <div class="t-stage" id="st-done">DONE</div>
        </div>
        <span class="t-readout" id="t-clock">00:00</span>
        <span class="t-readout" id="t-kb">0.0 KB</span>
      </div>
    </div>

    <div class="composer">
      <div class="thumbs" id="thumbs" hidden></div>
      <div class="composer-row">
        <button id="attach-btn" title="Attach images (max 4)">📎</button>
        <input type="file" id="file-input" accept="image/*" multiple hidden />
        <textarea id="prompt" rows="1" placeholder="Message SenseNova-Loop-9B…"></textarea>
        <button id="stop-btn" hidden>■ Stop</button>
        <button id="send-btn">Send →</button>
      </div>
      <div class="kb-hint"><kbd>↵</kbd> to send · <kbd>Shift</kbd>+<kbd>↵</kbd> for a new line</div>
    </div>
  </section>

  </main>
</div>

<section id="workflow-view" hidden>
  <iframe id="workflow-frame" title="SenseNova-Loop-9B workflow canvas"></iframe>
</section>

<footer class="statusbar" id="statusbar">
  <div class="pulse"></div>
  <span id="status">Ready</span>
  <div class="spacer"></div>
  <span id="seed-out"></span>
</footer>

<script type="module">
  import { client } from "https://cdn.jsdelivr.net/npm/@gradio/client@2.7.1/dist/index.min.js";

  const $ = (id) => document.getElementById(id);
  const state = { app: null, live: null, stopped: false };
  const convo = []; // {role: "user"|"assistant", text, images: [server paths]}
  let busy = false;

  // ---------- presets ----------
  const GROUPS = [
    ["Showcase", [
      ["🔁 The loop, explained simply",
       "Explain SenseNova-Loop-9B's looped block (32 stored layers executed as 56) and its two-stream mHC residual routing in simple terms, as if to an ML engineer meeting the architecture for the first time."],
      ["🧮 The widget puzzle",
       "If 5 machines take 5 minutes to make 5 widgets, how long would 100 machines take to make 100 widgets? Reason carefully, then explain why the intuitive answer tempts people."],
      ["💻 One-pass merge",
       "Write a Python function that merges two sorted lists in one pass, with type hints, a docstring, and pytest unit tests."],
    ]],
    ["Multilingual & vision", [
      ["🀄 循环架构讲解",
       "用简单的语言解释 SenseNova-Loop-9B 的循环块(looped block)和双流 mHC,并举一个生活中的类比。"],
      ["🖼️ Describe an image (attach one first)",
       "Describe this image in detail — setting, objects, colors, composition — then list three things that stand out."],
      ["📊 Chart to table (attach one first)",
       "Read the chart in this image and turn it into a markdown table, then summarize the main trend in two sentences."],
    ]],
  ];
  let presetIdx = 0;
  GROUPS.forEach(([group, items]) => {
    const header = document.createElement("div");
    header.className = "preset-group";
    header.textContent = group;
    $("examples").appendChild(header);
    items.forEach(([title, prompt]) => {
      presetIdx += 1;
      const chip = document.createElement("button");
      chip.className = "preset";
      const idx = document.createElement("span");
      idx.className = "idx";
      idx.textContent = String(presetIdx).padStart(2, "0");
      chip.appendChild(idx);
      chip.appendChild(document.createTextNode(title));
      chip.title = prompt.slice(0, 220);
      chip.onclick = () => {
        $("prompt").value = prompt;
        $("prompt").focus();
        autoGrow();
        setStatus(`Preset ${String(presetIdx).padStart(2, "0")} loaded — ${title}`);
      };
      $("examples").appendChild(chip);
    });
  });
  if (window.matchMedia("(max-width: 1000px)").matches) $("preset-details").open = false;

  // ---------- workspace chrome ----------
  $("rail-hide").onclick = () => { $("studio-view").classList.add("no-rail"); $("rail-show").hidden = false; };
  $("rail-show").onclick = () => { $("studio-view").classList.remove("no-rail"); $("rail-show").hidden = true; };

  let frameLoaded = false;
  function setMode(mode) {
    $("mode-studio").classList.toggle("active", mode === "studio");
    $("mode-workflow").classList.toggle("active", mode === "workflow");
    $("studio-view").style.display = mode === "workflow" ? "none" : "";
    $("workflow-view").hidden = mode !== "workflow";
    if (mode === "workflow" && !frameLoaded) {
      $("workflow-frame").src = "/workflow/?ui=canvas";
      frameLoaded = true;
    }
  }
  $("mode-studio").onclick = () => setMode("studio");
  $("mode-workflow").onclick = () => setMode("workflow");

  // ---------- gradio client ----------
  async function getApp() {
    if (!state.app) state.app = await client(location.origin, { events: ["data", "status"] });
    return state.app;
  }

  function setStatus(text, isBusy = false) {
    $("status").textContent = text;
    $("statusbar").classList.toggle("busy", isBusy);
    busy = isBusy;
    $("send-btn").disabled = isBusy;
    $("stop-btn").hidden = !isBusy;
    if (isBusy) startClock(); else stopClock();
  }

  // ---------- transport ----------
  const STAGES = ["st-queue", "st-think", "st-write", "st-done"];
  function setStage(active) {
    STAGES.forEach((id, i) => {
      const el = $(id);
      el.classList.toggle("ok", i < active);
      el.classList.toggle("lit", i === active);
    });
    if (active >= STAGES.length) STAGES.forEach((id) => { $(id).classList.add("ok"); $(id).classList.remove("lit"); });
  }
  function resetStages() { STAGES.forEach((id) => $(id).classList.remove("ok", "lit")); }

  let clockTimer = null, clockStart = 0;
  function startClock() {
    clockStart = performance.now();
    if (clockTimer) return;
    clockTimer = setInterval(() => {
      const s = Math.floor((performance.now() - clockStart) / 1000);
      $("t-clock").textContent = String(Math.floor(s / 60)).padStart(2, "0") + ":" + String(s % 60).padStart(2, "0");
    }, 500);
  }
  function stopClock() { clearInterval(clockTimer); clockTimer = null; }

  // ---------- minimal markdown ----------
  function md(src) {
    const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    const codeBlocks = [];
    src = src.replace(/```(\w*)\n?([\s\S]*?)(?:```|$)/g, (_, lang, code) => {
      codeBlocks.push(code);
      return "\u0001" + (codeBlocks.length - 1) + "\u0002";
    });
    const inline = (s) => esc(s)
      .replace(/`([^`\n]+)`/g, "<code>$1</code>")
      .replace(/\*\*([^*]+)\*\*/g, "<b>$1</b>")
      .replace(/(^|[\s(])\*([^*\n]+)\*/g, "$1<i>$2</i>")
      .replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>');
    const html = src.split(/\n{2,}/).map((p) => {
      const trimmed = p.trim();
      const blockMatch = trimmed.match(/^\u0001(\d+)\u0002$/);
      if (blockMatch) return "\u0001" + blockMatch[1] + "\u0002";
      const lines = p.split("\n");
      if (lines.every((l) => /^\s*[-•] /.test(l)))
        return "<ul>" + lines.map((l) => `<li>${inline(l.replace(/^\s*[-•] /, ""))}</li>`).join("") + "</ul>";
      if (lines.every((l) => /^\s*\d+[.)] /.test(l)))
        return "<ol>" + lines.map((l) => `<li>${inline(l.replace(/^\s*\d+[.)] /, ""))}</li>`).join("") + "</ol>";
      const h = trimmed.match(/^(#{1,4}) (.*)$/);
      if (h) { const n = Math.min(h[1].length + 2, 6); return `<h${n}>${inline(h[2])}</h${n}>`; }
      return `<p>${inline(p).replace(/\n/g, "<br>")}</p>`;
    }).join("");
    return html.replace(/\u0001(\d+)\u0002/g, (_, i) => `<pre class="md-code"><code>${esc(codeBlocks[+i]).replace(/\n$/, "")}</code></pre>`);
  }

  // ---------- files ----------
  const pendingFiles = [];
  function renderThumbs() {
    const box = $("thumbs");
    box.innerHTML = "";
    box.hidden = pendingFiles.length === 0;
    pendingFiles.forEach((f, i) => {
      const chip = document.createElement("div");
      chip.className = "thumb";
      const img = document.createElement("img");
      img.src = URL.createObjectURL(f);
      img.alt = f.name;
      const rm = document.createElement("button");
      rm.textContent = "✕";
      rm.title = "Remove";
      rm.onclick = () => { pendingFiles.splice(i, 1); renderThumbs(); };
      chip.appendChild(img);
      chip.appendChild(rm);
      box.appendChild(chip);
    });
  }
  $("attach-btn").onclick = () => $("file-input").click();
  $("file-input").addEventListener("change", (e) => {
    for (const f of e.target.files) {
      if (pendingFiles.length >= 4) { setStatus("At most 4 images per message."); break; }
      pendingFiles.push(f);
    }
    e.target.value = "";
    renderThumbs();
  });

  async function uploadFiles(files) {
    const fd = new FormData();
    for (const f of files) fd.append("files", f);
    const res = await fetch("/gradio_api/upload", { method: "POST", body: fd });
    if (!res.ok) throw new Error(`Image upload failed (HTTP ${res.status}).`);
    const out = await res.json();
    const paths = Array.isArray(out) ? out : (out.files || []);
    if (paths.length !== files.length) throw new Error("Image upload returned no paths.");
    return paths;
  }
  const fileUrl = (p) => "/gradio_api/file=" + p.split("/").map(encodeURIComponent).join("/");

  // ---------- thread rendering ----------
  function scrollThread() { const w = $("thread-scroll"); w.scrollTop = w.scrollHeight; }

  function addUserBubble(turn) {
    $("placeholder")?.remove();
    const msg = document.createElement("div");
    msg.className = "msg user";
    if (turn.images.length) {
      const strip = document.createElement("div");
      strip.className = "thumbs-in";
      turn.images.forEach((p) => {
        const img = document.createElement("img");
        img.src = fileUrl(p);
        img.alt = "attached image";
        img.onclick = () => window.open(fileUrl(p), "_blank", "noopener");
        strip.appendChild(img);
      });
      msg.appendChild(strip);
    }
    if (turn.text) {
      const bubble = document.createElement("div");
      bubble.className = "bubble";
      bubble.textContent = turn.text;
      msg.appendChild(bubble);
    }
    $("thread").appendChild(msg);
    scrollThread();
  }

  function addBotBlock() {
    $("placeholder")?.remove();
    const msg = document.createElement("div");
    msg.className = "msg bot";
    const think = document.createElement("details");
    think.className = "think";
    think.open = true;
    const summary = document.createElement("summary");
    const spin = document.createElement("span");
    spin.className = "spin";
    const label = document.createElement("span");
    label.textContent = "Thinking…";
    summary.appendChild(spin);
    summary.appendChild(label);
    const body = document.createElement("pre");
    body.className = "think-body";
    think.appendChild(summary);
    think.appendChild(body);
    const answer = document.createElement("div");
    answer.className = "answer md cursor";
    const meta = document.createElement("div");
    meta.className = "meta-line";
    msg.appendChild(think);
    msg.appendChild(answer);
    msg.appendChild(meta);
    $("thread").appendChild(msg);
    scrollThread();
    return { think, spin, label, body, answer, meta };
  }

  // ---------- one assistant turn ----------
  let renderAt = 0;
  function throttledRender(el, text) {
    const now = performance.now();
    if (now - renderAt < 120) return;
    renderAt = now;
    el.innerHTML = md(text);
    scrollThread();
  }

  function stopLive() {
    if (state.live) {
      state.stopped = true;
      try { state.live.cancel(); } catch {}
      state.live = null;
    }
  }

  function unwrap(result) {
    // submit() messages can nest the yield one level deep ({data: {data: [v]}}).
    let data = result?.data;
    if (data && !Array.isArray(data) && Array.isArray(data.data)) data = data.data;
    if (Array.isArray(data)) data = data[0];
    return data ?? {};
  }

  async function runTurn() {
    resetStages();
    setStage(0);
    setStatus("Sending to SenseNova-Loop-9B…", true);
    $("t-kb").textContent = "0.0 KB";
    let block = null, thinkText = "", answerText = "", done = null;
    state.stopped = false;
    renderAt = 0;
    try {
      const app = await getApp();
      const payload = {
        messages: JSON.stringify(convo),
        max_new_tokens: parseInt($("max-tokens").value, 10),
        temperature: parseFloat($("temperature").value),
        top_p: parseFloat($("top-p").value),
        seed: parseInt($("seed").value, 10) || 0,
        randomize: $("randomize").checked,
        thinking: $("thinking").checked,
      };
      const sub = app.submit("/chat_stream", payload);
      state.live = sub;
      for await (const msg of sub) {
        if (state.live !== sub) return; // replaced or stopped
        if (msg.type === "status") {
          if (msg.stage === "error") throw new Error(msg.message || "Generation failed.");
          if (msg.stage === "pending") setStatus("Queued for the GPU…", true);
          continue;
        }
        if (msg.type !== "data" && msg.type !== "generating") continue;
        const ev = unwrap(msg);
        if (ev.type === "thinking") {
          if (!block) block = addBotBlock();
          setStage(1);
          thinkText += ev.text;
          block.body.textContent = thinkText;
          block.body.scrollTop = block.body.scrollHeight;
          setStatus("Thinking…", true);
          scrollThread();
        } else if (ev.type === "answer_start") {
          if (!block) block = addBotBlock();
          setStage(2);
          block.think.open = false;
          block.spin.hidden = true;
          block.label.textContent = "Thought";
          setStatus("Writing the reply…", true);
        } else if (ev.type === "answer") {
          if (!block) { block = addBotBlock(); block.think.hidden = true; setStage(2); }
          answerText += ev.text;
          $("t-kb").textContent = (answerText.length / 1024).toFixed(1) + " KB";
          throttledRender(block.answer, answerText);
        } else if (ev.type === "done") {
          done = ev;
        } else if (ev.type === "error") {
          throw new Error(ev.message);
        }
      }
      if (state.live !== sub) return;
      state.live = null;
      setStage(4);
      if (!block) { // nothing streamed at all
        setStatus("The model returned nothing — try again.");
        convo.pop(); // drop the user turn so a retry resends it
        return;
      }
      block.answer.classList.remove("cursor");
      block.answer.innerHTML = md(answerText || "");
      if (!answerText.trim() && done?.cut_in_think) {
        block.answer.innerHTML = "<p><i>The token budget ran out while the model was still thinking — raise <b>Max new tokens</b> in the Session panel, or retry.</i></p>";
      }
      convo.push({ role: "assistant", text: answerText.trim(), images: [] });
      const seconds = done?.seconds ?? ((performance.now() - clockStart) / 1000).toFixed(1);
      block.meta.textContent =
        `seed ${done?.seed ?? "—"} · ${seconds}s · ${(answerText.length / 1024).toFixed(1)} KB`
        + (state.stopped ? " · stopped" : "");
      $("seed-out").textContent = "seed " + (done?.seed ?? "—");
      $("ctx-meta").textContent = `${convo.length} turns`;
      setStatus(state.stopped ? "Stopped — partial reply kept" : "Done");
      scrollThread();
    } catch (err) {
      stopLive();
      if (block) {
        block.answer.classList.remove("cursor");
        block.answer.innerHTML = md(answerText) + `<p><i>⚠ ${err?.message || err}</i></p>`;
      }
      setStatus(err?.message || String(err));
    }
  }

  async function send() {
    if (busy) return;
    const text = $("prompt").value.trim();
    if (!text && pendingFiles.length === 0) { setStatus("Write a message or attach an image first."); $("prompt").focus(); return; }
    let paths = [];
    if (pendingFiles.length) {
      setStatus(`Uploading ${pendingFiles.length} image${pendingFiles.length > 1 ? "s" : ""}…`, true);
      try {
        paths = await uploadFiles(pendingFiles.splice(0));
        renderThumbs();
      } catch (err) {
        setStatus(err?.message || String(err));
        return;
      }
    }
    const turn = { role: "user", text, images: paths };
    convo.push(turn);
    addUserBubble(turn);
    $("prompt").value = "";
    autoGrow();
    $("ctx-meta").textContent = `${convo.length} turns`;
    await runTurn();
  }

  $("send-btn").onclick = send;
  $("stop-btn").onclick = () => { stopLive(); };
  $("new-chat").onclick = () => {
    stopLive();
    convo.length = 0;
    busy = false;
    $("thread").innerHTML = "";
    const ph = document.createElement("div");
    ph.className = "thread-placeholder";
    ph.id = "placeholder";
    ph.innerHTML = '<div class="big">🔁</div><div class="ttl">How can SenseNova-Loop help today?</div><div style="font-size:0.7rem">pick a preset or write below · attach up to 4 images with 📎</div>';
    $("thread").appendChild(ph);
    $("ctx-meta").textContent = "0 turns";
    resetStages();
    setStatus("Ready");
  };

  // ---------- composer ----------
  function autoGrow() {
    const ta = $("prompt");
    ta.style.height = "auto";
    ta.style.height = Math.min(ta.scrollHeight, 160) + "px";
  }
  $("prompt").addEventListener("input", autoGrow);
  $("prompt").addEventListener("keydown", (e) => {
    if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); }
  });
</script>
</body>
</html>