File size: 84,075 Bytes
81dba88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e03db2
 
 
 
 
 
 
 
 
 
 
 
81dba88
5e03db2
81dba88
 
 
5e03db2
 
 
 
 
 
 
 
 
81dba88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b68496
 
 
f9f6ffb
 
7b68496
f9f6ffb
7b68496
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81dba88
8b948e5
 
 
 
 
 
 
 
 
 
 
 
 
 
8687cb9
 
 
 
 
 
 
 
 
 
0242e85
 
81dba88
 
 
 
 
 
 
 
 
 
5e03db2
 
81dba88
 
 
 
 
 
 
 
 
5e03db2
81dba88
5e03db2
 
81dba88
 
 
 
 
 
 
 
5e03db2
81dba88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b68496
 
 
 
 
 
 
8687cb9
 
 
8b948e5
 
 
 
81dba88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e03db2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81dba88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe909f5
8aa062f
81dba88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8aa062f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe909f5
0336867
 
 
fe909f5
 
0336867
fe909f5
 
 
 
81dba88
 
fe909f5
81dba88
8551d9d
 
 
 
 
 
 
 
 
81dba88
a593567
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81dba88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe909f5
 
 
 
8551d9d
8aa062f
8551d9d
8aa062f
8551d9d
 
fe909f5
8551d9d
 
 
 
 
7b68496
fe909f5
8551d9d
7b68496
fe909f5
 
 
8551d9d
fe909f5
 
 
 
 
 
 
 
 
 
 
81dba88
 
 
 
 
 
 
 
7b68496
81dba88
fe909f5
81dba88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9f6ffb
81dba88
 
 
 
 
8551d9d
 
 
 
81dba88
8551d9d
 
 
 
7b68496
81dba88
8551d9d
7b68496
81dba88
 
8551d9d
 
81dba88
 
 
f94d26f
 
 
 
 
81dba88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f94d26f
8687cb9
 
4845e8d
 
 
 
 
 
 
 
 
8aa062f
81dba88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b948e5
 
 
 
 
 
 
e40897c
8b948e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0242e85
8b948e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f94d26f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b948e5
 
 
 
 
 
 
 
 
 
8687cb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0242e85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b948e5
f94d26f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b948e5
81dba88
 
 
 
 
 
 
 
 
 
 
 
f94d26f
81dba88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0242e85
81dba88
 
 
 
 
 
8aa062f
81dba88
 
 
 
 
a593567
81dba88
 
 
 
0242e85
81dba88
 
 
 
 
a593567
 
 
 
 
81dba88
 
 
 
 
 
 
 
 
 
 
 
 
8b948e5
 
 
 
 
0242e85
81dba88
 
 
 
 
 
 
 
 
 
8b948e5
 
 
0242e85
8b948e5
81dba88
 
 
a593567
 
 
 
 
 
81dba88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9f6ffb
81dba88
 
 
 
f94d26f
f9f6ffb
 
 
7b68496
 
 
 
 
 
f9f6ffb
7b68496
f9f6ffb
 
7b68496
f9f6ffb
7b68496
 
 
 
 
 
 
 
f9f6ffb
 
 
81dba88
0336867
 
 
 
 
 
 
 
 
 
8aa062f
 
 
 
 
 
 
 
f94d26f
 
 
 
 
 
8687cb9
f94d26f
8687cb9
f94d26f
 
 
8687cb9
4845e8d
8687cb9
f94d26f
8687cb9
 
f94d26f
 
 
 
 
 
 
 
8687cb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4845e8d
8687cb9
 
 
 
 
 
 
 
 
 
 
 
 
0336867
8551d9d
 
 
 
 
 
0336867
 
8aa062f
0336867
97d52c5
 
 
 
 
 
 
 
 
 
 
f94d26f
97d52c5
 
 
f94d26f
81dba88
 
8aa062f
1a8aaf0
 
 
 
81dba88
 
8aa062f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81dba88
 
 
 
f9f6ffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
<!doctype html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Bonsai</title>
<style>

  /* Claude-desktop look: warm charcoal stage, 11% hairlines, 12-14px radii, serif display.

     NEUTRAL accent (was Claude coral): a premium bone fill on the charcoal — mono, sharp, calm.

     Type floor is 15px everywhere. Everything fits ONE viewport at 1280×800 AND 375×812 (dvh + clamp). */

  :root { --bg:#262624; --ink:#eceae4; --muted:#b8b5ad; --faint:rgba(232,230,224,.45);

          --hair:rgba(255,255,255,.11);

          --accent:#ece9e3; --accent-ink:#20201e; --accent-hi:#f7f5ef; --focus:rgba(255,255,255,.4);

          --coral:var(--accent); --coral-hi:var(--muted); --lav:rgba(255,255,255,.5); --r:13px;

          --serif:"Tiempos Text","Charter","Iowan Old Style",Georgia,serif; }

  * { box-sizing:border-box; margin:0; padding:0; }

  html,body { height:100%; }

  body { background:var(--bg); color:var(--ink); font:15px/1.55 system-ui,-apple-system,"Segoe UI",Inter,sans-serif;

         -webkit-font-smoothing:antialiased; overflow:hidden; }

  .num { font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; font-size:15px; }

  .stage { position:fixed; inset:0; height:100dvh; display:flex; flex-direction:column; align-items:center;

           justify-content:center; padding:24px; opacity:0; pointer-events:none; transition:opacity .6s ease; }

  .stage.on { opacity:1; pointer-events:auto; }



  /* ── arrival: golden split — copy holds the φ-major column, the ring floats in the φ-minor.

     Everything (columns, type scale, vertical rhythm) is proportioned by φ = 1.618, and it stays

     balanced and legible from a 320px phone to an ultrawide. ── */

  #arrive { display:grid; grid-template-columns:1.618fr 1fr; align-items:center; padding:0; gap:clamp(8px,2vw,40px); }

  #holo { position:absolute; inset:0; width:100%; height:100%; display:block; z-index:0; }   /* full-bleed; the ring is drawn into the φ-minor column by JS */

  #arrive .copy { position:relative; z-index:1; grid-column:1; justify-self:center; width:100%;

                  max-width:min(90%,34rem); padding-inline:clamp(20px,3vw,44px);

                  display:flex; flex-direction:column; align-items:flex-start; }

  #arrive h1 { font-family:var(--serif); font-weight:500; font-size:clamp(42px,6.2vw,80px); line-height:1.04;

               letter-spacing:-.018em; }

  #arrive h1 span { display:block; white-space:nowrap; }   /* exactly two lines: "An AI" / "that's yours." — never a third wrap */

  #arrive .sub { margin-top:21px; font-size:clamp(17px,1.5vw,20px); line-height:1.5; color:var(--muted); max-width:34ch; }

  #arrive button { margin-top:34px; background:var(--accent); border:none; color:var(--accent-ink); border-radius:999px;

                   padding:15px 34px; font:600 16px/1 system-ui,sans-serif; letter-spacing:-.01em; cursor:pointer;

                   transition:transform .2s ease, background .2s ease; }

  #arrive button:hover { background:var(--accent-hi); transform:translateY(-1px); }

  #arrive button:disabled { filter:saturate(.3) brightness(.8); cursor:default; transform:none; }

  #arrive .fine { margin-top:21px; font-size:15px; color:var(--faint); }

  /* portrait / narrow: stack — the ring floats in the upper zone (golden 38% line), copy rests below,

     the whole thing centered in one viewport with safe-area breathing room */

  @media (max-width:820px), (orientation:portrait) {

    #arrive { grid-template-columns:1fr; grid-template-rows:1fr auto; align-items:end; justify-items:center;

              padding-bottom:max(7vh, env(safe-area-inset-bottom, 0px) + 28px); }

    #arrive .copy { grid-column:1; grid-row:2; align-items:flex-start; max-width:min(92%,30rem);

                    padding-inline:clamp(22px,7vw,40px); }

    #arrive h1 { font-size:clamp(40px,12vw,68px); }

  }



  /* ── chat: the Claude-desktop room — serif greeting, ONE centered input card, quiet metrics ── */

  #chat { justify-content:center; padding:0; }

  #chat .col { display:flex; flex-direction:column; width:min(100%,760px); height:100%; padding:0 22px; justify-content:center; }

  #chat .col.started { justify-content:flex-start; }

  #hello { text-align:center; margin-bottom:26px; }

  #hello .mark { display:inline-block; width:30px; height:30px; vertical-align:-4px; margin-right:12px; color:var(--coral); }

  #hello h2 { display:inline; font-family:var(--serif); font-weight:500; font-size:clamp(30px,4.4vw,44px); letter-spacing:-.01em; }

  .col.started #hello { display:none; }

  #log { display:none; }

  .col.started #log { display:block; flex:1; overflow-y:auto; padding:30px 4px 16px;

                      scrollbar-width:none; -ms-overflow-style:none; }   /* the content scrolls; no chrome */

  #log::-webkit-scrollbar { width:0; height:0; }

  .msg { margin:0 0 22px; }

  .msg .who { font-size:15px; color:var(--faint); margin-bottom:4px; }

  .msg.user { display:flex; justify-content:flex-end; }                        /* Grok/Claude: user turn is a right bubble */

  .msg.user .who { display:none; }

  .msg.user .body { background:rgba(255,255,255,.05); border:1px solid var(--hair); border-radius:16px 16px 4px 16px;

                    padding:11px 16px; max-width:78%; }

  .msg .body { white-space:pre-wrap; font-size:16px; line-height:1.65; }

  /* "Thought for Ns" — a quiet collapsible reasoning header (Grok's signature, in Claude's palette) */

  details.think { margin:0 0 10px; }

  details.think summary { list-style:none; cursor:pointer; font-size:15px; color:var(--faint);

                          display:inline-flex; align-items:center; gap:7px; user-select:none; }

  details.think summary::-webkit-details-marker { display:none; }

  details.think summary .chev { transition:transform .2s ease; font-size:11px; }

  details.think[open] summary .chev { transform:rotate(90deg); }

  details.think .t { color:var(--faint); font-size:15px; line-height:1.6; white-space:pre-wrap; margin-top:8px;

                     border-left:2px solid var(--hair); padding-left:12px; }

  /* assistant action row: copy · regenerate (appears when the answer settles) */

  .acts { display:flex; gap:4px; margin-top:8px; opacity:0; transition:opacity .25s ease; }

  .msg:hover .acts, .acts.shown { opacity:1; }

  .acts button { background:none; border:none; color:var(--faint); cursor:pointer; border-radius:8px;

                 width:30px; height:30px; display:grid; place-items:center; transition:background .15s, color .15s; }

  .acts button:hover { background:rgba(255,255,255,.06); color:var(--ink); }

  .acts button svg { width:16px; height:16px; stroke:currentColor; fill:none; stroke-width:1.7; }

  .acts .ok { color:var(--coral-hi); }

  /* follow-up suggestions: Grok's placement — borderless rows stacked in the conversation flow */

  .fu { display:flex; flex-direction:column; margin:14px 0 4px; }

  .fu button { display:flex; align-items:center; gap:12px; background:none; border:none; border-top:1px solid transparent;

               color:var(--muted); font-size:16px; text-align:left; padding:11px 6px; cursor:pointer;

               border-radius:10px; transition:background .15s, color .15s; }

  .fu button:hover { background:rgba(255,255,255,.045); color:var(--ink); }

  .fu .arr { color:var(--faint); font-size:15px; flex:none; }

  .note { text-align:center; font-size:15px; color:var(--faint); margin:6px 0 12px; }

  #card { background:rgba(255,255,255,.03); border:1px solid var(--hair); border-radius:18px; padding:6px 8px 8px; }

  #card:focus-within { border-color:var(--focus); }

  #inp { width:100%; background:none; border:none; color:var(--ink); padding:14px 12px 10px;

         font:16px/1.45 system-ui,sans-serif; outline:none; }

  #cardrow { display:flex; align-items:center; gap:12px; padding:0 8px 4px 12px; }

  /* the model name IS a dropdown: click to pick the mind. Quiet trigger + a small popover menu. */

  #modelsel { position:relative; }

  #modelswitch { display:inline-flex; align-items:center; gap:5px; background:none; border:none; cursor:pointer;

                 padding:5px 9px; margin-left:-9px; border-radius:8px; color:var(--muted);

                 transition:background .16s ease, color .16s ease; }

  #modelswitch:hover, #modelswitch[aria-expanded="true"] { background:rgba(255,255,255,.06); color:var(--ink); }

  #modelname { font-size:15px; letter-spacing:-.005em; }

  #modelswitch .caret { width:13px; height:13px; opacity:.55; transition:opacity .16s ease, transform .18s ease; }

  #modelswitch:hover .caret { opacity:.9; }

  #modelswitch[aria-expanded="true"] .caret { transform:rotate(180deg); opacity:.9; }

  /* popover: opens UPWARD from the trigger (the card sits mid-screen), premium charcoal, hairline, soft shadow */

  #modelmenu { position:absolute; left:-4px; bottom:calc(100% + 8px); z-index:20; min-width:236px;

               background:#2f2f2c; border:1px solid var(--hair); border-radius:14px; padding:6px;

               box-shadow:0 16px 40px rgba(0,0,0,.5), 0 2px 8px rgba(0,0,0,.3);

               display:flex; flex-direction:column; gap:2px; }

  #modelmenu[hidden] { display:none; }

  #modelmenu [role="option"] { display:flex; align-items:center; gap:10px; width:100%; text-align:left;

               background:none; border:none; cursor:pointer; color:var(--ink); border-radius:10px; padding:10px 12px;

               transition:background .14s ease; }

  #modelmenu [role="option"]:hover { background:rgba(255,255,255,.06); }

  #modelmenu .tick { width:15px; flex:none; color:var(--ink); opacity:0; font-size:15px; line-height:1; }

  #modelmenu [role="option"][aria-selected="true"] .tick { opacity:1; }

  #modelmenu .opt { display:flex; flex-direction:column; gap:2px; }

  #modelmenu .opt b { font-weight:600; font-size:15px; letter-spacing:-.005em; }

  #modelmenu .opt em { font-style:normal; font-size:13px; color:var(--faint); }

  #cardrow .grow { flex:1; }

  /* the voice toggle: one quiet speaker button (V3 law: no panel, no picker). While Q speaks, the

     icon breathes with the live audio level (--lv, set from the analyser) — reduced-motion safe:

     it is a transition on opacity/color, no keyframes. */

  #voice { background:none; border:none; cursor:pointer; color:var(--faint); width:34px; height:34px;

           border-radius:9px; display:grid; place-items:center; position:relative;

           transition:background .16s ease, color .16s ease; }

  #voice:hover { background:rgba(255,255,255,.06); color:var(--ink); }

  #voice[aria-pressed="true"] { color:var(--ink); }

  #voice svg { width:18px; height:18px; stroke:currentColor; fill:none; stroke-width:1.8;

               stroke-linecap:round; stroke-linejoin:round; transition:opacity .12s linear; }

  #voice .off { position:absolute; width:18px; height:18px; stroke:currentColor; fill:none; stroke-width:1.8; }

  #voice[aria-pressed="true"] .off { display:none; }

  #voice.speaking svg { opacity:calc(.55 + .45 * var(--lv, 0)); }

  #voice.speaking { color:var(--accent); }

  /* the ear: one mic button arms the whole conversation (ear on, voice on). While listening the

     icon holds the accent; while YOU speak it breathes with the live mic level. No motion keyframes. */

  #mic { background:none; border:none; cursor:pointer; color:var(--faint); width:34px; height:34px;

         border-radius:9px; display:grid; place-items:center; transition:background .16s ease, color .16s ease; }

  #mic:hover { background:rgba(255,255,255,.06); color:var(--ink); }

  #mic[aria-pressed="true"] { color:var(--ink); }

  #mic svg { width:18px; height:18px; stroke:currentColor; fill:none; stroke-width:1.8;

             stroke-linecap:round; stroke-linejoin:round; transition:opacity .12s linear; }

  #mic.listening { color:var(--accent); }

  #mic.hearing svg { opacity:calc(.5 + .5 * var(--lv, 0)); }

  /* S4 karaoke: the clause currently SOUNDING carries a quiet wash — no motion, reduced-motion safe */

  .msg .body mark.kq { background:rgba(255,255,255,.08); color:inherit; border-radius:4px; padding:0 2px; }

  #send { background:var(--accent); border:none; color:var(--accent-ink); border-radius:999px; width:38px; height:38px;

          font:500 17px/1 system-ui,sans-serif; cursor:pointer; transition:background .2s ease; }

  #send:hover { background:var(--accent-hi); }

  #send:disabled { background:rgba(255,255,255,.06); color:var(--faint); cursor:default; }

  #metrics { text-align:center; font-size:15px; color:var(--faint); padding:12px 0 16px; min-height:22px; }

  #metrics b { color:var(--muted); font-weight:500; }

  #err { color:#f87171; font-size:15px; padding:0 0 18px; text-align:center; white-space:pre-wrap; }

  .spn { display:inline-block; width:1.1ch; font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;

         color:var(--coral-hi); margin-right:7px; }

  /* CSS hologram (fallback when WebGL is unavailable/blocked): layered orb + scanlines + drift */

  #holofb { position:absolute; width:min(30vw,430px); aspect-ratio:1; left:80.9%; top:50%;

            transform:translate(-50%,-50%); border-radius:50%; pointer-events:none;

            background:radial-gradient(circle at 38% 34%, rgba(255,255,255,.5), rgba(206,204,198,.22) 42%, rgba(255,255,255,.1) 72%, transparent 76%);

            box-shadow:0 0 90px rgba(255,255,255,.14), inset 0 0 60px rgba(255,255,255,.12);

            animation:holofloat 7s ease-in-out infinite; }

  #holofb::before { content:""; position:absolute; inset:0; border-radius:50%;

            background:repeating-linear-gradient(to bottom, rgba(255,255,255,.09) 0 2px, transparent 2px 7px);

            mix-blend-mode:screen; animation:holoscan 2.6s linear infinite;

            -webkit-mask:radial-gradient(circle, #000 70%, transparent 74%); mask:radial-gradient(circle, #000 70%, transparent 74%); }

  #holofb::after { content:""; position:absolute; inset:-2%; border-radius:50%;

            border:1px solid rgba(255,255,255,.25); filter:blur(.4px); }

  @keyframes holofloat { 50% { transform:translate(-50%,calc(-50% - 14px)); } }

  @keyframes holoscan { to { background-position:0 7px; } }

  @media (max-width:820px), (orientation:portrait){ #holofb { left:50%; top:38.2%; transform:translate(-50%,-50%); width:min(58vw,300px); }

                            @keyframes holofloat { 50% { transform:translate(-50%,calc(-50% - 10px)); } } }

  @media (prefers-reduced-motion: reduce){ #holofb, #holofb::before { animation:none; } }

</style>
<body>

<div class="stage on" id="arrive">
  <canvas id="holo"></canvas>
  <div id="holofb" hidden></div>
  <div class="copy">
    <h1><span>An AI</span><span>that&rsquo;s yours.</span></h1>
    <p class="sub">It runs entirely on your device. Private, and works offline.</p>
    <button id="go">Start chatting</button>
    <div class="fine" id="fine">Free. No account, nothing to install.</div>
  </div>
</div>

<div class="stage" id="chat">
  <div class="col" id="col">
    <div id="hello">
      <svg class="mark" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" aria-hidden="true"><path d="M12 3v18M3 12h18M5.6 5.6l12.8 12.8M18.4 5.6L5.6 18.4"/></svg><h2>Ready when you are.</h2>
    </div>
    <div id="log"></div>
    <div id="card">
      <input id="inp" placeholder="Ask anything" autocomplete="off">
      <div id="cardrow">
        <div id="modelsel">
          <button type="button" id="modelswitch" aria-haspopup="listbox" aria-expanded="false" aria-label="Choose model"><span id="modelname">Bonsai</span><svg class="caret" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 9l6 6 6-6"/></svg></button>
          <div id="modelmenu" role="listbox" hidden>
            <button type="button" role="option" data-m="27b"><span class="tick">&check;</span><span class="opt"><b>Bonsai 27B</b><em>The full mind, deeper answers</em></span></button>
            <button type="button" role="option" data-m="8b"><span class="tick">&check;</span><span class="opt"><b>Bonsai 8B</b><em>Lighter and faster</em></span></button>
          </div>
        </div>
        <button type="button" id="mic" aria-pressed="false" aria-label="Talk" title="Talk to Bonsai">
          <svg viewBox="0 0 24 24" aria-hidden="true"><rect x="9" y="3" width="6" height="11" rx="3"/><path d="M5 11a7 7 0 0 0 14 0M12 18v3M8.5 21h7"/></svg>
        </button>
        <button type="button" id="voice" aria-pressed="false" aria-label="Voice" title="Voice">
          <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M11 5 6.5 9H3v6h3.5L11 19zM15.5 8.5a5 5 0 0 1 0 7M18.4 5.6a9 9 0 0 1 0 12.8"/></svg>
          <svg class="off" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 4l16 16"/></svg>
        </button>
        <span class="grow"></span>
        <button id="send" aria-label="Send">&uarr;</button>
      </div>
    </div>
    <div id="metrics">on your device</div>
    <div id="err" hidden></div>
  </div>
</div>

<script type="module">

// ── the OS boot animation, verbatim look ─────────────────────────────────────────────────────

// This is the SAME animation the OS greeter shows on its login screen (holo-plymouth.mjs): the

// abstract_ring Plymouth theme — a dense torus of dark spheres cycling progress-0..40.png at

// 25 fps — streamed progressively from the same public pack the OS streams from

// (adi1090x/plymouth-themes, GPL-3.0 artwork), cached in the Cache API so every return visit

// paints instantly and offline. Each frame's baked-black background is CHROMA-KEYED to

// transparent on decode (the greeter's keyBlack, verbatim), so the emblem floats over the stage

// with no black box — identical to the login screen.

const cv = document.getElementById("holo");

const reduced = matchMedia("(prefers-reduced-motion: reduce)").matches;

window.__holoOff = null;

try {

  const N = 41, FPS = 25;

  const url = (i) => "https://raw.githubusercontent.com/adi1090x/plymouth-themes/master/pack_1/abstract_ring/progress-" + i + ".png";

  const ctx = cv.getContext("2d");

  const frames = new Array(N).fill(null);

  let have = 0, dead = false, raf = 0;

  // Plymouth sprites bake their black screen into the PNG; over the stage that black must be AIR.

  // keyBlack (holo-plymouth.mjs, verbatim ramp) fades near-black pixels to transparent → the ring

  // floats on the charcoal exactly like the greeter's emblem floats on the login wall.

  const keyBlack = (bmp) => {

    try {

      const w = bmp.width, h = bmp.height; if (!w || !h) return bmp;

      const c = document.createElement("canvas"); c.width = w; c.height = h;

      const x = c.getContext("2d", { willReadFrequently: true });

      x.drawImage(bmp, 0, 0);

      const d = x.getImageData(0, 0, w, h), p = d.data;

      for (let i = 0; i < p.length; i += 4) {

        const v = Math.max(p[i], p[i + 1], p[i + 2]);

        if (v < 48) p[i + 3] = Math.min(p[i + 3], Math.max(0, ((v - 12) / 36) * 255) | 0);

      }

      x.putImageData(d, 0, 0);

      return c;

    } catch { return bmp; }

  };

  const cachePromise = caches.open("holo-plymouth-v1").catch(() => null);

  const loadFrame = async (i) => {

    try {

      const cache = await cachePromise;

      let resp = cache && await cache.match(url(i));

      if (!resp) { resp = await fetch(url(i)); if (cache && resp.ok) { try { await cache.put(url(i), resp.clone()); } catch {} } }

      if (!resp || !resp.ok) return;

      frames[i] = keyBlack(await createImageBitmap(await resp.blob()));

      have++;

    } catch {}

  };

  // frame 0 first (first paint), then the rest with small concurrency — plays as it arrives

  await loadFrame(0);

  (async () => { let i = 1; const w = async () => { while (i < N && !dead) { const k = i++; await loadFrame(k); } };

                 await Promise.all([w(), w(), w(), w()]); })();

  const size = () => { cv.width = innerWidth * Math.min(devicePixelRatio || 1, 2); cv.height = innerHeight * Math.min(devicePixelRatio || 1, 2); };

  size(); addEventListener("resize", size);

  let f = 0, last = 0;

  const draw = (t) => {

    if (dead) return;

    raf = requestAnimationFrame(draw);

    if (t - last < 1000 / FPS) return; last = t;

    if (!reduced) { f = (f + 1) % N; }

    let img = frames[f]; if (!img) { for (let k = 0; k < N; k++) if (frames[k]) { img = frames[k]; break; } }

    if (!img) return;

    ctx.clearRect(0, 0, cv.width, cv.height);

    // golden layout: side-by-side when the CSS grid is (innerWidth ≥ 820 AND landscape) — the ring

    // centers in the φ-minor right column (x ≈ 0.809W); otherwise it floats in the upper-golden band.

    const side = innerWidth >= 820 && cv.width / cv.height > 1;

    let s, x, y;

    if (side) {

      const colW = cv.width * 0.382;                                   // the φ-minor column that holds the ring

      s = Math.min(colW, cv.height) * 0.88 / Math.max(img.width, img.height);

      const w = img.width * s, h = img.height * s;

      x = Math.min(cv.width * 0.809, cv.width - w * 0.5 - cv.width * 0.02) - w / 2;   // centre the φ-minor column, always a hair inside the edge

      y = cv.height / 2 - h / 2;

      ctx.drawImage(img, x, y, w, h);

    } else {

      s = Math.min(cv.width, cv.height) * 0.72 / Math.max(img.width, img.height);

      const w = img.width * s, h = img.height * s;

      x = cv.width / 2 - w / 2;

      y = cv.height * 0.382 - h / 2;                                   // the golden 38.2% line — copy rests below

      ctx.drawImage(img, x, y, w, h);

    }

  };

  raf = requestAnimationFrame(draw);

  document.addEventListener("visibilitychange", () => { if (dead) return; if (document.hidden) cancelAnimationFrame(raf); else raf = requestAnimationFrame(draw); });

  window.__holoFrame = () => cv.toDataURL("image/png");

  window.__holoOff = () => { dead = true; cancelAnimationFrame(raf); window.__holoFrame = null; cv.remove(); };

  setTimeout(() => { if (!dead && have === 0) { const fb = document.getElementById("holofb"); if (fb) fb.hidden = false; } }, 4000);   // no frames at all → CSS stand-in

} catch (e) {

  const fb = document.getElementById("holofb"); if (fb) fb.hidden = false;

}

</script>

<script type="module">

import init, { qvac_load_gpu, qvac_gpu_free } from "./q/pkg/holospaces_web.js";

import { loadKappaObject } from "./q/holo-load2bit.mjs";

import { createQvacGPU } from "./q/qvac-gpu.js?v=68";

import { createEngine } from "./q/core/engine.js";

import { loadBridge } from "./bonsai27-bridge.mjs";   // 27B hybrid engine, wrapped in the 8B engine shape

import { swarmWarm, defaultMirrors } from "./kappa-swarm.mjs";   // I1 κ-SWARM: multi-origin verified block warm



const $ = (id) => document.getElementById(id);

// braille pulse: one 80ms ticker animates every [data-spin] slot (loading, waking, thinking) —

// a single interval, zero layout work, stops mattering the instant the last spinner is removed.

const SPIN = ["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];

let _sf = 0;

setInterval(() => { const els = document.querySelectorAll("[data-spin]"); if (!els.length) return; const f = SPIN[_sf = (_sf + 1) % SPIN.length]; for (const el of els) el.textContent = f; }, 80);

const spn = () => `<span class="spn" data-spin>${SPIN[0]}</span>`;

const show = (id) => { for (const s of document.querySelectorAll(".stage")) s.classList.toggle("on", s.id === id); };

const short = (k) => String(k).replace(/^(did:holo:)?sha256:/, "").slice(0, 12) + "…";



// model source: ?src=<κ-object dir> for dev, HF mirror by default; ?m=27b flips to the 27B

// κ-object (engine support for its hybrid layers lands separately — the guard below is honest).

// Everything shown to the user (name, size) is READ FROM THE MANIFEST — swapping the κ URL is a

// zero-code model change. The manifest pin is the Law-L5 anchor.

const QS = new URLSearchParams(location.search);

const SRC = QS.get("src");

// ── I0 BENCH (?bench=load): honest cold-load stage report — per-stage wall-time, wire bytes,

// effective MB/s, origin/connection counts, and a Paris probe (the bit-identical gate). Everything

// is gated on BENCH; a normal visit takes zero extra work. &swarm=0 = loader-only baseline ·

// &cold=0 = keep the cache · &conc=N = swarm workers (default 24).

const BENCH = QS.get("bench") === "load";

const BM = { t0: 0, purged: -1, manMs: 0, fetch0: 0, fetchN: 0, wire: 0, raw: 0, blocks: 0,

             swarm: null, swarmLive: null, ready: 0, ttft: 0, genDone: 0, answer: null,

             doSwarm: QS.get("swarm") !== "0", conc: Math.max(1, Number(QS.get("conc")) || 24), nOrigins: 1 };

const fmtMB = (b) => (b / 1048576).toFixed(1) + " MB";

const fmtS = (ms) => (ms / 1000).toFixed(1) + "s";

function benchRender() {

  const p = document.getElementById("benchpanel"); if (!p) return;

  const L = [`BENCH cold-load · ${M27 ? "Bonsai 27B" : "Bonsai 8B"} · swarm ${BM.doSwarm ? `ON (conc ${BM.conc} · ${BM.nOrigins} origin${BM.nOrigins > 1 ? "s" : ""})` : "OFF (loader-only baseline, conc 12 · 1 origin)"}`];

  if (BM.purged >= 0) L.push(`cache   purged ${BM.purged} entries (cold start)`);

  if (BM.swarmLive && !BM.swarm) L.push(`swarm   ${BM.swarmLive.done}/${BM.swarmLive.total} blocks · ${fmtMB(BM.swarmLive.bytes)} · ${BM.swarmLive.mbps.toFixed(2)} MB/s`);

  if (BM.swarm) L.push(`swarm   ${BM.swarm.fetched} fetched + ${BM.swarm.skipped} cached · ${fmtMB(BM.swarm.bytes)} in ${fmtS(BM.swarm.ms)} → ${BM.swarm.mbps.toFixed(2)} MB/s wire · ` +

                       BM.swarm.mirrors.map((m) => `${m.label}:${m.blocks}${m.fails ? "(" + m.fails + " fail)" : ""}`).join(" "));

  if (BM.manMs) L.push(`live    manifest ${fmtS(BM.manMs)}`);

  if (BM.fetch0) { const w = Math.max(1, (BM.fetchN - BM.fetch0));

    L.push(`fetch+verify ${BM.blocks} blocks · ${fmtMB(BM.wire)} wire (${fmtMB(BM.raw)} raw) in ${fmtS(w)} → ${((BM.wire / 1048576) / (w / 1000)).toFixed(2)} MB/s${BM.swarm ? " (warm cache read)" : ""}`); }

  if (BM.ready && BM.fetchN) L.push(`after   last block → ready ${fmtS(BM.ready - BM.fetchN)} (GPU upload tail + pipeline compile)`);

  if (BM.ready && BM.t0) L.push(`ready   at ${fmtS(BM.ready - BM.t0)} total from load start`);

  if (BM.ttft) L.push(`first   ${fmtS(BM.ttft * 1000)} to first answer token (prefill + forward)`);

  if (BM.answer !== null) L.push(`probe   "capital of France" → ${/paris/i.test(BM.answer) ? "PASS" : "FAIL"} (${BM.answer.slice(0, 60).replace(/\s+/g, " ")}…)`);

  // honest floor: model bytes / link. Chrome CAPS navigator.connection.downlink at 10 Mbit — when it

  // reads 10 the real link is unknown, so use the best MEASURED wire MB/s as the link's lower bound.

  try { const dl = navigator.connection && navigator.connection.downlink;

    const meas = Math.max(BM.swarm ? BM.swarm.mbps : 0, BM.fetch0 && !BM.swarm ? (BM.wire / 1048576) / (Math.max(1, BM.fetchN - BM.fetch0) / 1000) : 0);

    const link = (dl && dl < 10) ? dl / 8 : meas;                              // dl==10 = the cap, not the link

    if (link) L.push(`floor   link ${dl && dl < 10 ? "~" : "≥"}${link.toFixed(1)} MB/s (${dl && dl < 10 ? "browser estimate" : "measured lower bound"}) → ${M27 ? "3.4 GB" : "1.16 GB"} floor ≤ ${Math.round((M27 ? 3474 : 1188) / link)}s`); } catch (e) {}

  p.textContent = L.join("\n");

}

function benchBlock(rec, delta) {   // one verified block landed in the live loader (27B bridge or 8B fetchT)

  const n = performance.now(); if (!BM.fetch0) BM.fetch0 = n; BM.fetchN = n;

  BM.wire += (rec && rec.stored) || 0; BM.raw += delta || 0; BM.blocks++;

  benchRender();

}

function benchAsk() {   // the gate probe: a REAL forward (memo bypassed in bench) must answer Paris

  const len0 = story.length;

  $("inp").value = "What is the capital of France?"; send();

  const t = setInterval(() => {

    if (busy || story.length <= len0) return;

    clearInterval(t);

    BM.answer = story[story.length - 1].a || ""; BM.ttft = lastTTFT || 0; BM.genDone = performance.now();

    benchRender();

  }, 250);

}

const DEFAULT_27B = true;                                  // the full 27B hybrid mind is the default (parity-verified via bonsai27-bridge.mjs)

const MODEL_KEY = "bonsai.model.v1";                       // remembered only for the dropdown's reload chain

// choose the model: an explicit ?m= wins (the dropdown reload path), else ALWAYS the 27B default.

// Every fresh visit opens on 27B — the mind we want strangers to meet — no matter what was picked before.

function pickModel() {

  const q = QS.get("m");

  if (q === "27b" || q === "8b") return q;

  return DEFAULT_27B ? "27b" : "8b";

}

const MODEL = pickModel();

const M27 = MODEL === "27b";

const BASE = SRC || (M27 ? "https://huggingface.co/HOLOGRAMTECH/q-bonsai-27b/resolve/main" : "https://huggingface.co/HOLOGRAMTECH/q-bonsai-8b/resolve/main");

const PIN = M27 ? "did:holo:sha256:00beea03509a79f6567879f019c04bb15dda8721f6320f8295d9ea1dd9ba54af" : "did:holo:sha256:a0dc81f26ec5ce98b28ee9c1fab620e91c20720f777e1de6bc416317f54d27e2";

const CTX = M27 ? 1024 : 2048;   // the 27B ring-decode head caps context at 1024 (KV VRAM); the 8B keeps 2048



// ── INSTANT START: everything the load needs, begun at PAINT, not at click ──────────────────────

// PROG is the ONE progress truth (gz wire bytes resident vs total): the welcome swarm feeds it, the

// live load reads it — so the visible % starts where the welcome head-start left off, never at a

// dead 0% while a 170 MB first block streams. MAN_P fetches the manifest ONCE at paint (was a serial

// step after enter). The GPU adapter warms at paint too (first requestAdapter costs real ms).

const PROG = { have: 0, total: 0 };

const MAN_P = SRC ? null : fetch(BASE + "/manifest.json").then((r) => r.json()).catch(() => null);

try { if (navigator.gpu) navigator.gpu.requestAdapter().catch(() => {}); } catch {}



let engine = null, gpu = null, rootK = "", warm = false, mind = [], thinkOpen = -1, thinkClose = -1;

// ── E1 IN-SESSION KV ELISION ─────────────────────────────────────────────────────────────────────

// Measured: multi-turn TTFT climbs (0.4→2.0s over a thread) because the follow-up-suggestion

// generation after each answer RESETS the conversation's K/V, forcing a full re-prefill next turn.

// Fix: snapshot the conversation K/V (engine.kvSnapshot → gpu.dumpState) BEFORE the follow-up gen

// evicts it, and restore it before the next turn so only the new turn prefills. One in-memory blob,

// byte-identical by determinism (restoreState re-derives the last token). Gated to long threads on

// capable desktops (below ~256 tokens re-prefill is <0.5s and not worth the blob I/O; the 27B ring

// engine is excluded — different KV path).

function _kvMobile() { try { return !!(navigator.userAgentData && navigator.userAgentData.mobile); } catch (e) { return false; } }

let KV_ELIDE = QS.get("elide") !== "0" && !M27 && !_kvMobile() && (navigator.deviceMemory || 8) >= 8;   // ?elide=0; runtime-toggleable for A/B

const KV_ELIDE_MIN = 256;

let kvSnap = null;                                          // { ids, snap } — resident conversation K/V captured before eviction

const kvStat = { restores: 0, snaps: 0 };

const _sameIds = (a, b) => a && b && a.length === b.length && a.every((v, i) => v === b[i]);

window.__kvElide = () => ({ on: KV_ELIDE, avail: !!(engine && engine.kvElideAvailable), have: !!kvSnap, blobMB: kvSnap ? +(kvSnap.snap.bytes.byteLength / 1048576).toFixed(1) : 0, ...kvStat });

window.__setElide = (v) => { KV_ELIDE = !!v; return KV_ELIDE; };   // A/B without reload (avoids per-navigation GPU-device leaks)

window.__eng = () => engine;                                       // prefill micro-probe: measure elision without sustained decode

window.__resetChat = () => {                                       // clear the thread + GPU K/V in place for a clean same-page A/B

  mind = []; story = []; memoryNote = ""; kvSnap = null; kvStat.restores = 0; kvStat.snaps = 0;

  try { gpu && gpu.reset && gpu.reset(); } catch (e) {}

  try { $("log").innerHTML = ""; $("col").classList.remove("started"); } catch (e) {}

};

let modelName = "Bonsai";                                  // set from the manifest once loaded

let story = [], memoryNote = "";                           // the WHOLE conversation + the folded memory of its older part

const STORE = "bonsai.story.v1";

// ── O(1) κ-ANSWER MEMO (the hologram-runtime thesis, applied honestly) ────────────────────────

// Greedy decode is deterministic: the answer is a PURE FUNCTION of (model root κ, exact input token

// ids). So the answer is itself content-addressable. Key = sha256(rootκ · ids) → cached reply. A hit

// streams instantly and is BYTE-IDENTICAL to recomputing — repeated questions, and the model-authored

// follow-ups other visitors also click, become 0-latency. Persisted; survives reloads and works offline.

const MEMO = "bonsai.memo.v1";

let memoMap = null;

function memoLoad() { if (memoMap) return memoMap; try { memoMap = JSON.parse(localStorage.getItem(MEMO) || "{}"); } catch { memoMap = {}; } return memoMap; }

async function memoKey(ids) {

  const b = new TextEncoder().encode(rootK + ":" + ids.join(","));

  const h = await crypto.subtle.digest("SHA-256", b);

  return [...new Uint8Array(h)].slice(0, 16).map((x) => x.toString(16).padStart(2, "0")).join("");

}

function memoSave(key, val) {

  const m = memoLoad(); m[key] = val;

  const ks = Object.keys(m); if (ks.length > 400) delete m[ks[0]];       // bounded FIFO

  try { localStorage.setItem(MEMO, JSON.stringify(m)); } catch {}

}

function persistStory() {

  try { localStorage.setItem(STORE, JSON.stringify({ story: story.slice(-200), memoryNote })); } catch {}

}

// fold everything so far into a compact memory the model writes for itself (bounded, abortable-free:

// runs inside send() before the next turn, with the braille pulse narrating it)

async function foldMemory() {

  const recent = story.slice(-8).map((t) => `Q: ${t.q}

A: ${t.a.slice(0, 300)}`).join("\n");

  const prior = memoryNote ? "Earlier memory: " + memoryNote + "\n\n" : "";

  const ask = prior + "Recent conversation:\n" + recent + "\n\nFold ALL of the above into one memory note under 130 words. Keep every name, number, decision and open question. Write only the note.";

  const ids = engine.tokenize(engine.frameTurn(ask, false));

  const res = await engine.generate(ids, { maxNew: 300 });

  const seg = splitThink(res.outIds || []);

  const text = (seg.ans.length ? engine.detokenize(seg.ans) : res.text || "").trim();

  return text.slice(0, 1200);

}



let entered = false, streamStarted = false;

// ── 27B path: the hybrid engine behind the SAME engine shape send() consumes (bonsai27-bridge.mjs). ──

// The bridge does its own κ-verified load (loadKappaObject) and hands back { engine, modelName, rootK };

// its engine.{tokenize,detokenize,frameTurn,generate} match the 8B contract, so send() is unchanged.

async function stream27(t0, phase) {

  let wire = 0, done = 0, total = 0, label = "", man = null;

  const tm0 = performance.now();

  try { man = MAN_P ? await MAN_P : null; if (!man) man = await (await fetch(BASE + "/manifest.json")).json(); total = Object.keys(man.tensors || {}).length; } catch {}

  if (BENCH) { BM.manMs = performance.now() - tm0; benchRender(); }

  const totalBytes = man ? Object.values(man.tensors || {}).reduce((a, r) => a + (r.stored || 0), 0) : 0;

  if (totalBytes) PROG.total = totalBytes;

  const tick = () => {

    // BYTE-true %, monotonic: the max of what the welcome swarm made resident and what the engine has

    // read — never a dead 0% while the first (largest) block streams, and the head start shows instantly.

    const denom = PROG.total || totalBytes;

    const pct = denom ? Math.min(99, Math.floor(Math.max(PROG.have, wire) / denom * 100))

                      : (total ? Math.min(99, Math.round(done / total * 100)) : 0);

    phase(`${spn()}Loading Bonsai 27B &middot; ${pct}%`);

  };

  tick();                                                    // first paint immediately, not after 300ms

  const iv = setInterval(tick, 300);

  try {

    const b = await loadBridge({

      base: BASE, pin: SRC ? null : PIN,                    // ?src = loose dev object → unpinned; HF = κ-pinned

      onProgress: (name, delta) => { const rec = man && man.tensors && man.tensors[name]; wire += (rec && rec.stored) || delta || 0; done++; if (BENCH) benchBlock(rec, delta); },

      onStatus: (s) => { label = s; },

    });

    engine = b.engine;

    modelName = String(b.modelName || "Bonsai 27B");

    rootK = b.rootK || PIN;

    $("modelname").textContent = modelName;

    thinkOpen = engine.thinkOpen ?? -1; thinkClose = engine.thinkClose ?? -1;   // atomic <think>/</think> (248068/248069)

  } finally { clearInterval(iv); }

  phase(spn() + "Almost ready");

  enterChat();

}

async function stream() {

  if (entered) { show("chat"); $("inp").focus(); }         // welcome (and its living hologram) stays until the visitor enters

  const t0 = performance.now();

  const phase = (s) => { $("metrics").innerHTML = s; };

  try {

    if (!navigator.gpu) throw new Error("This browser has no WebGPU. Chrome or Edge 113+ required.");

    // warm-load detect (honest offline copy): the κ-cache already holds the manifest → this visit is disk-speed.

    try { const c = await caches.open("holo-kappa-v1"); warm = !!(await c.match(BASE + "/manifest.json")); } catch {}

    phase(spn() + "Loading " + (M27 ? "Bonsai 27B" : "Bonsai 8B") + " &middot; 0%");

    await init();

    if (M27) { await stream27(t0, phase); return; }   // the 27B hybrid mind loads through the bridge (its own engine + ring decode)

    // PARALLEL κ-BLOCKS FIRST (the measured Netflix path on CDN origins): 399 content-addressed

    // blocks race over 12 connections (HF cdn-lfs caps a single stream ~2 MB/s; the parallel parts

    // path measured 6.8 MB/s on the same line). The ONE-file .holo stays as the fallback for

    // origins that only host the wafer (and its OPFS warm store makes revisits 0-network either way).

    let r, pinned = true, holo = false;

    try {

      r = await loadKappaObject(BASE, { expectKappa: PIN, blake3: false });

    } catch (e1) {

      try {

        const hs = await import("./q/core/holo-stream-load.mjs");

        r = await hs.openHoloKappa(BASE + "/q-bonsai-8b.v1.holo", {});

        holo = true; warm = !!r.warm;

      } catch (e) { if (!SRC) throw e; pinned = false; r = await loadKappaObject(BASE, { allowUnpinned: true, blake3: false }); }  // dev fallback only under ?src

    }

    rootK = (r.info && r.info.root) || PIN;

    modelName = SRC ? String((r.info && r.info.model) || "Bonsai").replace(/-/g, " ") : "Bonsai 8B";   // the toggle needs an unambiguous name; dev ?src keeps the manifest's

    $("modelname").textContent = modelName;

    // HONESTY GATE: the hybrid (27B) engine ships separately — never pretend to run what we can't.

    if (r.manifest.hybrid) throw new Error(modelName + " uses a hybrid engine this build does not include yet. It is arriving; the 8B runs today.");

    // progress = ONE quiet line under the input (per-tensor counters; no grid, no takeover)

    const total = (r.manifest.tensors || []).length;

    const recs = (r.info && r.info.tensors) || {};

    const totalBytes = Object.values(recs).reduce((a, t) => a + (t.stored || 0), 0);

    if (totalBytes) PROG.total = totalBytes;

    let done = 0, wire = 0;

    const tick = () => {

      // BYTE-true, monotonic vs the welcome swarm's head start (same rule as the 27B path)

      const denom = PROG.total || totalBytes;

      const pct = denom ? Math.min(99, Math.floor(Math.max(PROG.have, wire) / denom * 100))

                        : Math.min(99, Math.round(done / Math.max(total, 1) * 100));

      phase(`${spn()}Loading ${modelName} &middot; ${pct}%`);

    };

    tick();

    const iv = setInterval(tick, 300);

    const fetchT = async (name) => {                       // wrap fetchTensor: the progress driver

      const b = await r.fetchTensor(name);

      wire += (recs[name] && recs[name].stored) || b.byteLength; done++;

      if (BENCH) benchBlock(recs[name], b.byteLength);

      return b;

    };

    // tokenizer header (arch + vocab) — embedded in the .holo (0 extra fetches), else same κ-object dir.

    let hdr = r.tokenizerBytes;

    if (!hdr) {                                            // the fused carve caches this too — cache-first, network once

      try { const c = await caches.open("holo-kappa-v1"); const h = await c.match(BASE + "/tokenizer.gguf"); if (h) hdr = new Uint8Array(await h.arrayBuffer()); } catch {}

      if (!hdr) hdr = new Uint8Array(await (await fetch(BASE + "/tokenizer.gguf")).arrayBuffer());

    }

    const lr = JSON.parse(qvac_load_gpu(hdr));

    if (lr.error) throw new Error("tokenizer: " + lr.error);

    try { qvac_gpu_free(); } catch {}

    r.manifest.kv4 = false;                                // exact f32 KV (the proven first-light config)

    gpu = await createQvacGPU(r.manifest, fetchT, CTX, lr.eos ?? 2, false);

    clearInterval(iv);

    phase(spn() + "Almost ready");

    const m = { fam: "Bonsai", name: modelName, size: "1.16 GB", fmt: "q1 1-bit κ", cap: 200, ctx: CTX, qwen: true, chat: true, rep: 1.05, gpu: true, gpuOnly: true };

    engine = await createEngine(m, { gpu, info: lr, imageKappa: r.info.root });

    // Qwen3 thinking markers are atomic tokens and clean() strips them from text — split by token id instead.

    const o = engine.tokenize("<think>"), c2 = engine.tokenize("</think>");

    thinkOpen = o.length === 1 ? o[0] : -1; thinkClose = c2.length === 1 ? c2[0] : -1;

    enterChat();

  } catch (e) {

    $("metrics").textContent = ""; $("err").hidden = false;

    $("err").textContent = String(e && e.message || e);

    console.error(e);

  }

}



// the ONLY chat metrics, one quiet line: model · time to first word · tok/s (operator spec)

let lastTTFT = null, lastTokps = null;

function metrics(state) {

  const bits = [`<b>${modelName}</b>`];

  if (lastTTFT != null) bits.push(`${lastTTFT.toFixed(1)}s to first word`);

  if (lastTokps != null) bits.push(`<b>${lastTokps.toFixed(0)}</b> tokens a second`);

  if (!lastTTFT && !lastTokps) bits.push(state || (warm ? "on your device · works offline" : "on your device"));

  $("metrics").innerHTML = bits.join(" &nbsp;&middot;&nbsp; ");

}

let pendingQ = null, restored = false;

function restoreStory() {

  if (restored) return; restored = true;

  try {

    const saved = JSON.parse(localStorage.getItem(STORE) || "null");

    if (!saved || !saved.story || !saved.story.length) return;

    story = saved.story; memoryNote = saved.memoryNote || "";

    $("col").classList.add("started");

    for (const t of story.slice(-12)) {                    // the room re-fills; the model remembers ALL of it via the fold

      msg("You", "user").body.textContent = t.q;

      msg(modelName, "bot").body.textContent = t.a;

    }

    if (!memoryNote && story.length) memoryNote = story.slice(-6).map((t) => `${t.q} → ${t.a.slice(0, 120)}`).join("; ").slice(0, 1200);

    note("picked up where you left off");

    log.scrollTop = log.scrollHeight;

  } catch {}

}

function enterChat() {

  ready = true; narrStop(); $("send").disabled = false; restoreStory(); metrics();

  // the conversation's other organs (voice + ear) top up AFTER the mind is ready and the wire is

  // idle — a returning visitor's instant boot skips the welcome carve, this catches the remainder.

  // top up any stragglers of the voice+ear+mind object — but only once the mind is IDLE (a

// returning visitor who fires a question immediately must get every CPU cycle for the decode;

  // the carve waits for the pause to clear, then finishes quietly).

  if (!SRC && !BENCH) {

    let topped = false;

    const topUp = () => { if (topped || busy) return; topped = true;

      if (!fusedStats || !fusedStats.ok || fusedStats.carved + fusedStats.skipped < fusedStats.members) warmFused(4, true); };

    setTimeout(function tick() { if (topped) return; if (!busy) topUp(); else setTimeout(tick, 1500); }, 1200);

  }

  if (BENCH && !BM.ready) { BM.ready = performance.now(); benchRender(); benchAsk(); }

  if (pendingQ) { $("inp").value = pendingQ; pendingQ = null; send(); }

  else if (entered) $("inp").focus();

}



const log = $("log");

function msg(who, cls) {

  const d = document.createElement("div"); d.className = "msg " + cls;

  d.innerHTML = `<div class="who">${who}</div>`;

  const think = document.createElement("details"); think.className = "think"; think.hidden = true;

  think.innerHTML = `<summary><span class="chev">▸</span><span class="sum">thinking…</span></summary><div class="t"></div>`;

  const body = document.createElement("div"); body.className = "body";

  d.appendChild(think); d.appendChild(body);

  let acts = null;

  if (cls === "bot") { acts = document.createElement("div"); acts.className = "acts"; d.appendChild(acts); }

  log.appendChild(d);

  log.scrollTop = log.scrollHeight;

  return { d, body, think, acts, t: think.querySelector(".t") };

}

const ICON = {

  copy: '<svg viewBox="0 0 24 24"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>',

  ok:   '<svg viewBox="0 0 24 24"><path d="M5 13l4 4L19 7"/></svg>',

  regen:'<svg viewBox="0 0 24 24"><path d="M21 12a9 9 0 1 1-3-6.7"/><path d="M21 3v5h-5"/></svg>',

};

function iconBtn(html, title, fn) { const b = document.createElement("button"); b.type = "button"; b.title = title; b.innerHTML = html; b.onclick = fn; return b; }

// action row: copy the answer + regenerate the last turn (Grok's row, Claude's restraint)

function fitActions(ui, text, regen) {

  if (!ui.acts) return; ui.acts.innerHTML = "";

  const copy = iconBtn(ICON.copy, "Copy", async () => {

    try { await navigator.clipboard.writeText(text); copy.classList.add("ok"); copy.innerHTML = ICON.ok;

      setTimeout(() => { copy.classList.remove("ok"); copy.innerHTML = ICON.copy; }, 1200); } catch {}

  });

  ui.acts.appendChild(copy);

  if (regen) ui.acts.appendChild(iconBtn(ICON.regen, "Regenerate", regen));

  ui.acts.classList.add("shown");

}

// follow-ups AUTHORED BY THE MODEL about the actual exchange (Grok's behavior, done locally):

// one bounded extra generation right after the answer; killed instantly if the user starts typing.

let sugCtl = null;

async function offerFollowups(lastQ, lastA, host) {

  try { if (sugCtl) sugCtl.abort(); } catch {}

  sugCtl = new AbortController();

  const ask = `Here is a conversation:

Question: ${lastQ}

Answer: ${lastA.slice(0, 600)}



Write exactly two short, sharp follow-up questions a curious person would ask next. One per line. No numbering, no preamble.`;

  try {

    const ids = engine.tokenize(engine.frameTurn(ask, false));

    const res = await engine.generate(ids, { maxNew: 180, signal: sugCtl.signal });

    const seg = splitThink(res.outIds || []);

    const text = seg.ans.length ? engine.detokenize(seg.ans) : (res.text || "");

    const qs = text.split(/\n+/).map((l) => l.replace(/^[-*\d.\s]+/, "").trim()).filter((l) => l.length > 8 && l.length < 140).slice(0, 2);

    if (!qs.length || busy) return;

    const box = document.createElement("div"); box.className = "fu";

    for (const label of qs) {

      const b = document.createElement("button"); b.type = "button";

      b.innerHTML = `<span class="arr">↳</span>${label.replace(/[<>&]/g, "")}`;

      b.onclick = () => { box.remove(); $("inp").value = label; send(); };

      box.appendChild(b);

    }

    host.appendChild(box);

    log.scrollTop = log.scrollHeight;

  } catch {}                                              // aborted / out of room → no suggestions, no noise

}

function note(s) { const d = document.createElement("div"); d.className = "note"; d.textContent = s; log.appendChild(d); }



// split streamed outIds into thinking + answer segments by the <think> token ids (robust: no

// tags at position 0 → everything is answer; unclosed → everything so far is thinking).

function splitThink(outIds) {

  if (thinkOpen < 0 || outIds[0] !== thinkOpen) return { think: [], ans: outIds };

  const c = outIds.indexOf(thinkClose);

  if (c < 0) return { think: outIds.slice(1), ans: [] };

  return { think: outIds.slice(1, c), ans: outIds.slice(c + 1) };

}



// ── VOICE (pocket-tts as a κ-object): the answer is SPOKEN as it is written. ─────────────────────

// kyutai pocket-tts (100M, int8 ONNX) streams from HOLOGRAMTECH/q-pocket-tts as verified κ-blocks —

// the same content-addressed discipline the mind loads under — and runs 100% on-device in a WASM

// worker (CPU; the GPU stays Bonsai's). Clauses are cut from the streaming answer the moment they

// complete and queued gaplessly, so first sound lands mid-answer. The think block is NEVER spoken.

// Voice OFF = this code never runs; the text experience is byte-identical.

const VOICE_KEY = "bonsai.voice.v1";

let voiceOn = true; try { const v = localStorage.getItem(VOICE_KEY); if (v === "0") voiceOn = false; } catch {}   // ON by default for every new visitor; a stored "0" = they chose to mute (the speaker button persists it)

let voiceMod = null, voice = null, voiceCtx = null, voiceQ = null, voiceFeed = null, voiceWarming = false;

let voiceDegrade = 0;   // never stutter: 0 clause-streamed → 1 sentence-at-a-time → 2 synthesize-after-answer

const vBtn = $("voice");

function voiceUI() { vBtn.setAttribute("aria-pressed", String(voiceOn)); vBtn.title = voiceOn ? "Voice on" : "Voice"; }

async function voiceWarmup() {

  if (voice && voice.isReady()) return true;

  if (voiceWarming) return false;

  voiceWarming = true;

  try {

    if (!voiceMod) voiceMod = await import("./pocket-voice.mjs");

    if (!voice) voice = voiceMod.createPocketVoice({});

    const ok = await voice.warm((p) => {   // the ONLY thing voice ever adds to the metrics line (V3 law)

      if (busy || !voiceOn || !p.total) return;

      $("metrics").innerHTML = spn() + "warming the voice &middot; " + Math.min(99, Math.floor(p.have / p.total * 100)) + "%";

    });

    if (voiceOn && !busy && ready) metrics();

    return ok;

  } catch { return false; } finally { voiceWarming = false; }

}

function voiceStop() {

  if (voice) voice.stop();                                   // kills the queue → scheduled audio halts NOW (barge-in)

  voiceQ = null; voiceFeed = null;

  if (voiceKar && voiceKar.ui && voiceKar.lastHtml) { try { voiceKar.ui.body.textContent = voiceKar.text; } catch (e) {} voiceKar.lastHtml = null; }   // no karaoke residue on the old bubble

  vBtn.classList.remove("speaking"); vBtn.style.removeProperty("--lv");

}

function toggleVoice() {

  voiceOn = !voiceOn;

  try { localStorage.setItem(VOICE_KEY, voiceOn ? "1" : "0"); } catch {}

  voiceUI();

  if (voiceOn) {

    if (!voiceCtx) { try { voiceCtx = new (window.AudioContext || window.webkitAudioContext)(); } catch {} }

    if (voiceCtx && voiceCtx.state === "suspended") voiceCtx.resume().catch(() => {});   // this click IS the autoplay gesture

    voiceWarmup();

  } else { voiceStop(); if (!busy && ready) metrics(); }

}

vBtn.addEventListener("click", toggleVoice);

voiceUI();

if (voiceOn) setTimeout(voiceWarmup, 2500);                  // returning voice-on visitor: the engine warms quietly (downloads need no gesture)

function speakStart() {                                      // open a fresh gapless queue + clause feed for one answer

  if (!voiceOn || !voice || !voice.isReady() || voiceQ) return;

  if (!voiceCtx) { try { voiceCtx = new (window.AudioContext || window.webkitAudioContext)(); } catch { return; } }

  if (voiceCtx.state === "suspended") voiceCtx.resume().catch(() => {});

  const q = voice.openQueue({ ctx: voiceCtx, onLevel: (l) => {

    vBtn.style.setProperty("--lv", l.toFixed(3));

    vBtn.classList.toggle("speaking", l > 0.02);

  } });

  voiceQ = q; window.__vq = q;                               // live handle for the witness probes

  // S2 PROSODY BATCHING: the first clause goes solo (latency), but once playback runs ahead of

  // synthesis by >1.5s, whole sentences merge into ONE generate so the flow-LM carries its melody

  // across them instead of resetting per clause. The lead is measured off the queue's own clock.

  const pend = [];

  const emitNow = (t) => { if (voiceQ === q && !q.closed) q.enqueue(t); };

  const emit = (c) => {

    if (!q.startedOnce && !pend.length) { emitNow(c); return; }   // opening clause goes solo: first sound fast

    // after that, sentences merge into one generate — chunks stream DURING generation, so merging

    // costs no latency while the flow-LM carries prosody across the merged span

    pend.push(c);

    const joined = pend.join(" ");

    const sentenceEnd = /[.!?]['")\]]?$/.test(c);

    if ((sentenceEnd && (pend.length >= 2 || joined.length > 90)) || joined.length > 180) { emitNow(joined); pend.length = 0; }

  };

  const cf = voiceMod.makeClauseFeed(emit, { sentenceOnly: voiceDegrade === 1 });

  voiceFeed = { feed: cf.feed, flush: () => { cf.flush(); if (pend.length) { emitNow(pend.join(" ")); pend.length = 0; } } };

  q.drained().then(() => {                                   // the answer finished PLAYING: honesty check on gaps

    if (q.closed) return;

    if (q.gapSec > 1.5 && voiceDegrade < 2) voiceDegrade++;  // synthesis fell behind on this device → calmer mode next turn

    if (voiceQ === q) { vBtn.classList.remove("speaking"); vBtn.style.removeProperty("--lv"); }

  });

}

function speakText(text) {                                   // memo hits + degraded mode: one whole text, clause-queued

  speakStart();

  if (voiceFeed) { voiceFeed.feed(text); voiceFeed.flush(); }

}

// ── THE EAR + THE CALL LOOP: moonshine STT (bonsai-ear.mjs, Q's proven holo-ear twin) turns the

// demo into a conversation — speak, it listens (Silero VAD segments your sentence), transcribes

// on-device in ~300ms, sends; the answer streams back SPOKEN clause by clause; when Q's voice

// drains, the mic gate reopens and it is your turn again. One tap arms the whole loop (ear AND

// voice — a conversation has both). Half-duplex by design: the mic waits out Q's own voice (echo

// cancellation stays on regardless). 100% on-device: audio never leaves the browser; the ear's

// weights and pinned runtime arrive inside the SAME fused κ-object as the mind and the mouth.

let earMod = null, hfEar = null, micOn = false, micState = "idle";

const micBtn = $("mic");

function voiceSpeaking() { return !!(voiceQ && !voiceQ.closed && voiceCtx && voiceQ.cursor > voiceCtx.currentTime + 0.05); }

function micUI(state) {

  if (state) micState = state;

  micBtn.setAttribute("aria-pressed", String(micOn));

  micBtn.classList.toggle("listening", micOn && (micState === "listening" || micState === "speech"));

  micBtn.classList.toggle("hearing", micOn && micState === "speech");

  micBtn.title = micOn ? "Listening. Tap to stop" : "Talk to Bonsai";

}

async function toggleMic() {

  if (micOn) { micOn = false; try { if (hfEar) hfEar.stop(); } catch (e) {} micUI("idle"); return; }

  if (!voiceOn) toggleVoice();                               // the call has a mouth too (this tap is the gesture for both)

  micOn = true; micUI("loading");

  try {

    if (!earMod) earMod = await import("./bonsai-ear.mjs");

    if (!hfEar) hfEar = earMod.createHandsFree({

      silenceMs: 550,                                        // conversational tail (the OS default 700 feels formal)

      gate: () => ready && !busy && !voiceSpeaking(),        // your turn only when Q is idle and silent

      onState: (s) => micUI(s),

      onLevel: (l) => { try { micBtn.style.setProperty("--lv", l.toFixed(3)); } catch (e) {} },

      onFinal: (text) => { if (!micOn || !text) return; $("inp").value = text; send(); },

    });

    if (!hfEar.available()) throw new Error("no microphone API");

    await hfEar.start();

    micUI("listening");

  } catch (e) {

    micOn = false; micUI("idle");

    note("I couldn't reach the microphone. Check the browser's mic permission and tap the mic again.");

  }

}

micBtn.addEventListener("click", toggleMic);

micUI("idle");

window.__earDebug = () => ({ micOn, micState, engine: earMod && earMod.engine ? earMod.engine() : "unloaded" });



// ── S4 KARAOKE: the clause currently SOUNDING highlights in the transcript. The binding is the

// queue's own segment timeline ({text,start,end} in AudioContext seconds, recorded at schedule

// time), so text and voice can never drift apart — both read the same clock. One 200ms ticker;

// voice off, queue closed, or playback past the end → plain text, zero residue.

let voiceKar = null;                                         // { ui, text, lastHtml }

const escH = (s) => s.replace(/[&<>]/g, (c) => c === "&" ? "&amp;" : c === "<" ? "&lt;" : "&gt;");

function karSpan(hay, needle, seg) {                         // whitespace-insensitive locate; cache HITS only

  if (seg._span) return seg._span;                           // a miss retries — the clause may not be fully in the body yet

  try {

    const rx = new RegExp(needle.trim().split(/\s+/).map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("\\s+"));

    const m = rx.exec(hay);

    if (m) seg._span = { a: m.index, b: m.index + m[0].length };

  } catch (e) {}

  return seg._span || null;

}

function karRender(force) {

  const k = voiceKar; if (!k || !k.ui) return;

  let html = null, q = voiceQ;

  if (voiceOn && q && !q.closed && voiceCtx && q.segments.length) {

    const t = voiceCtx.currentTime;

    const seg = q.segments.find((s) => s.start != null && t >= s.start && t < (s.end == null ? Infinity : s.end));

    const span = seg && k.text ? karSpan(k.text, seg.text, seg) : null;

    if (span) html = escH(k.text.slice(0, span.a)) + '<mark class="kq">' + escH(k.text.slice(span.a, span.b)) + "</mark>" + escH(k.text.slice(span.b));

  }

  if (!force && html === k.lastHtml) return;

  k.lastHtml = html;

  if (html) k.ui.body.innerHTML = html;

  else if (force || k.ui.body.querySelector("mark")) k.ui.body.textContent = k.text;   // never fight the plain path

}

setInterval(() => { try { karRender(false); } catch (e) {} }, 200);

window.__voiceDebug = () => ({ on: voiceOn, ready: !!(voice && voice.isReady()), degrade: voiceDegrade,

  narrated: narrLines, pv: voice && voice.debug ? voice.debug() : null,

  q: voiceQ ? { enq: voiceQ.enqueued, memoHits: voiceQ.memoHits || 0, gaps: voiceQ.gaps, gapSec: +voiceQ.gapSec.toFixed(2), firstAudioAt: voiceQ.firstAudioAt, cursor: voiceQ.cursor, closed: voiceQ.closed } : null });



// ── S1 THE ARRIVAL NARRATION: the voice is packed FIRST in the fused object, so it is resident

// while the mind still streams — and it says so, in its own voice, from real numbers. Voice-on

// visitors only; at most three quiet lines; any user act (typing, sending, ready) ends it. The

// "Start chatting" click is the autoplay gesture that makes this legal.

let narrLines = 0, narrDone = false, narrTimer = 0;

function narrStop() { narrDone = true; if (narrTimer) { clearTimeout(narrTimer); narrTimer = 0; } }

async function armNarration() {

  if (!voiceOn || narrDone || ready) return;

  const ok = await voiceWarmup();                            // voice blocks are the payload's head — this is quick

  if (!ok || narrDone || ready || !voiceOn || busy) return;

  speakStart();

  if (!voiceQ) return;

  const say = (t) => { if (!narrDone && voiceQ && !voiceQ.closed) { voiceQ.enqueue(t); narrLines++; } };

  say("My voice is already here. The rest of my mind is still arriving.");

  const again = () => {

    narrTimer = setTimeout(() => {

      if (narrDone || ready || !voiceOn) return;

      const pct = PROG.total ? Math.round(PROG.have / PROG.total * 100) : 0;

      if (pct >= 45 && narrLines < 3) say(pct >= 80 ? "Almost with you." : "More than halfway now.");

      if (narrLines < 3) again();

    }, 18000);

  };

  again();

}

$("inp").addEventListener("input", narrStop);



let busy = false, ready = false;

async function send() {

  const q = $("inp").value.trim();

  if (!q || busy) return;

  if (!ready || !engine) {                                 // the mind is still arriving: hold ONE question, it sends itself

    pendingQ = q; $("inp").value = "";

    $("col").classList.add("started");

    msg("You", "user").body.textContent = q;

    note("This sends as soon as Bonsai is ready.");

    return;

  }

  busy = true; $("inp").value = ""; $("send").disabled = true;

  narrStop(); voiceStop();                                 // barge-in: a new question silences narration and the old answer instantly

  $("col").classList.add("started");                       // the greeting yields to the conversation (Claude-room transition)

  msg("You", "user").body.textContent = q;

  let turn = engine.tokenize(engine.frameTurn(q, mind.length > 0));

  if (mind.length + turn.length + 384 > CTX) {                                 // the window fills: the mind FOLDS its history, never drops it

    $("metrics").innerHTML = spn() + "folding memory · nothing is forgotten";

    try { memoryNote = await foldMemory(); persistStory(); } catch {}

    mind = [];

  }

  let qEff = q;

  if (!mind.length && memoryNote) qEff = `(What you remember of our conversation so far: ${memoryNote})



${q}`;

  if (!mind.length) turn = engine.tokenize(engine.frameTurn(qEff, false));

  const ids = mind.concat(turn);

  try { if (sugCtl) sugCtl.abort(); } catch {}

  document.querySelectorAll(".fu").forEach((n) => n.remove());

  const mindBefore = mind.slice();

  const ui = msg(modelName, "bot"); ui.body.innerHTML = spn();

  voiceKar = { ui, text: "", lastHtml: null };               // karaoke binds to THIS answer bubble

  ui.think.querySelector("summary").innerHTML = spn() + `<span class="sum">thinking</span>`;

  const tSend = performance.now(); let ttftSet = false, thoughtMs = 0;

  lastTTFT = null; lastTokps = null;

  // κ-MEMO HIT: identical (model, input) seen before → replay the exact answer, instantly. Honest:

  // greedy is deterministic, so this is the same bytes recompute would produce, at O(1).

  const mkey = await memoKey(ids);

  const hit = BENCH ? null : memoLoad()[mkey];   // bench: never replay — the Paris probe must be a real forward

  if (hit) {

    if (hit.think) { ui.think.hidden = false; ui.t.textContent = hit.think; }

    ui.think.querySelector("summary").innerHTML = `<span class="chev">▸</span><span class="sum">Thought for ${hit.secs || 1}s</span>`;

    ui.body.textContent = hit.ans;

    mind = ids.concat(hit.ansIds || engine.tokenize(hit.ans));

    kvSnap = null;                                          // a memo replay ran no forward pass → the GPU K/V is stale for this mind

    story.push({ q, a: hit.ans }); persistStory();

    lastTTFT = (performance.now() - tSend) / 1000; lastTokps = null;

    $("metrics").innerHTML = `<b>${modelName}</b> &nbsp;&middot;&nbsp; from memory &nbsp;&middot;&nbsp; content-addressed &nbsp;&middot;&nbsp; instant`;

    fitActions(ui, hit.ans, () => { if (!busy) { mind = mindBefore; $("inp").value = q; send(); } });

    if (voiceOn) { voiceKar = { ui, text: hit.ans, lastHtml: null }; speakText(hit.ans); }   // a remembered answer is spoken (and karaoke-lit) too

    offerFollowups(q, hit.ans, ui.d);

    busy = false; $("send").disabled = false; $("inp").focus();

    log.scrollTop = log.scrollHeight;

    return;

  }

  // E1: if a prior turn's conversation K/V is still snapshotted, restore it so this turn prefills

  // only its new tokens (the intervening follow-up gen reset the live K/V). Byte-identical.

  if (KV_ELIDE && kvSnap && mind.length >= KV_ELIDE_MIN && _sameIds(kvSnap.ids, mind) && engine.kvRestore) {

    try { if (await engine.kvRestore(mind, kvSnap.snap)) kvStat.restores++; } catch (e) {}

  }

  $("metrics").innerHTML = spn() + `<b>${modelName}</b> is thinking`;

  try {

    const res = await engine.generate(ids, {

      maxNew: CTX - ids.length - 8,                        // the whole remaining KV window (eos stops early)

      onToken: (t) => {

        if (!ttftSet) { ttftSet = true; lastTTFT = (performance.now() - tSend) / 1000; }   // TTFT = send → first visible token

        if (t.stats && t.stats.tokps) lastTokps = t.stats.tokps;

        metrics();

        const s = splitThink(t.outIds);

        if (s.think.length) { ui.think.hidden = false; ui.t.textContent = engine.detokenize(s.think); }

        if (s.ans.length && !thoughtMs) { thoughtMs = performance.now() - tSend;                                   // answer flowing: freeze "Thought for Ns"

          const secs = Math.max(1, Math.round(thoughtMs / 1000));

          ui.think.querySelector("summary").innerHTML = `<span class="chev">▸</span><span class="sum">Thought for ${secs}s</span>`; }

        const ansText = s.ans.length ? engine.detokenize(s.ans) : "";

        ui.body.textContent = ansText || (s.think.length ? "" : t.text);

        // speak-as-it-writes: the ANSWER stream (never the think block) feeds the clause queue the

        // moment each clause completes — speech starts while the model is still mid-sentence.

        if (ansText && voiceOn && voiceDegrade < 2) { if (!voiceQ) speakStart(); if (voiceFeed) voiceFeed.feed(ansText); }

        if (voiceOn && voiceKar) { voiceKar.text = ansText; if (voiceQ) karRender(true); }   // keep the karaoke wash on top of the fresh text

        log.scrollTop = log.scrollHeight;

      },

    });

    const s = splitThink(res.outIds || []);

    const secs = Math.max(1, Math.round((thoughtMs || (performance.now() - tSend)) / 1000));

    ui.think.querySelector("summary").innerHTML = `<span class="chev">▸</span><span class="sum">Thought for ${secs}s</span>`;

    if (s.think.length) { ui.think.hidden = false; ui.t.textContent = engine.detokenize(s.think); }

    if (s.ans.length) {

      const answer = engine.detokenize(s.ans);

      ui.body.textContent = answer;

      if (voiceOn) {                                       // the answer settled: speak the trailing partial clause…

        if (voiceQ && voiceFeed && voiceDegrade < 2) { voiceFeed.feed(answer); voiceFeed.flush(); }

        else if (voiceDegrade >= 2) speakText(answer);     // …or, on a device where synthesis fell behind, the whole answer now

        if (voiceKar) voiceKar.text = answer;              // karaoke follows the settled text to the end of playback

      }

      mind = ids.concat(s.ans);                            // history carries the ANSWER only (Qwen3 convention: prior-turn thinking dropped)

      story.push({ q, a: answer }); persistStory();

      memoSave(mkey, { ans: answer, ansIds: s.ans, think: s.think.length ? engine.detokenize(s.think) : "", secs });   // κ-memo: this exact (model,input)→answer is now O(1)

      // E1: capture the conversation K/V NOW, while it is resident — before offerFollowups' divergent

      // generation resets it. Next turn restores this instead of re-prefilling the whole thread.

      kvSnap = null;

      if (KV_ELIDE && mind.length >= KV_ELIDE_MIN && engine.kvSnapshot) {

        try { const snap = await engine.kvSnapshot(mind); if (snap) { kvSnap = { ids: mind.slice(), snap }; kvStat.snaps++; } } catch (e) {}

      }

      fitActions(ui, answer, () => { if (!busy) { mind = mindBefore; $("inp").value = q; send(); } });   // regenerate: rewind history, re-ask

      offerFollowups(q, answer, ui.d);                     // the model writes its own follow-ups, in place

    } else if (s.think.length) {

      ui.body.textContent = "I ran out of room while thinking. Ask again, a bit shorter.";   // unclosed <think> at the window edge; turn not kept

    } else {

      ui.body.textContent = res.text;

      mind = ids.concat(res.outIds || []);

    }

    if (res.stats && res.stats.tokps) lastTokps = res.stats.tokps;

    metrics();

  } catch (e) { ui.body.textContent = "Something broke: " + (e && e.message || e); }

  busy = false; $("send").disabled = false; $("inp").focus();

  log.scrollTop = log.scrollHeight;

}



function enterRoom() {   // the visitor crosses from the welcome wall into the chat room (distinct from enterChat = engine ready)

  entered = true;

  try { if (window.__holoOff) { window.__holoOff(); window.__holoOff = null; } } catch {}   // hand the hologram off — ONLY now, as the visitor enters (a warm engine load must never kill the welcome ring)

  show("chat"); $("inp").focus();

  if (!streamStarted) { streamStarted = true; stream(); }

  if (voiceOn && !ready) armNarration();                   // the voice greets the wait (its blocks lead the fused payload)

}

$("go").addEventListener("click", enterRoom);



// model dropdown: the model name in the chat card opens a menu to pick the mind. Choosing the OTHER

// model reloads into it and lands straight back in chat (the welcome wall never replays); choosing the

// current one just closes. A session flag carries the visitor across the reload into the conversation.

function switchModel(m) {

  if (m === MODEL) return;

  try { localStorage.setItem(MODEL_KEY, m); } catch {}

  try { sessionStorage.setItem("bonsai.enter.v1", "1"); } catch {}          // land in chat, not the welcome wall

  const u = new URL(location.href); u.searchParams.set("m", m); location.href = u.toString();

}

{

  const sel = $("modelsel"), btn = $("modelswitch"), menu = $("modelmenu");

  if (!SRC) $("modelname").textContent = M27 ? "Bonsai 27B" : "Bonsai 8B";   // unambiguous from the first paint; the manifest confirms it

  if (sel && btn && menu) {

    for (const o of menu.querySelectorAll("[role=option]")) o.setAttribute("aria-selected", String(o.dataset.m === MODEL));

    const open = (v) => { menu.hidden = !v; btn.setAttribute("aria-expanded", String(v)); };

    btn.addEventListener("click", (e) => { e.stopPropagation(); open(menu.hidden); });

    for (const o of menu.querySelectorAll("[role=option]")) o.addEventListener("click", () => { const m = o.dataset.m; open(false); switchModel(m); });

    document.addEventListener("click", (e) => { if (!sel.contains(e.target)) open(false); });

    document.addEventListener("keydown", (e) => { if (e.key === "Escape") open(false); });

  }

}

let enterOnSwitch = false; try { enterOnSwitch = sessionStorage.getItem("bonsai.enter.v1") === "1"; if (enterOnSwitch) sessionStorage.removeItem("bonsai.enter.v1"); } catch {}

if (enterOnSwitch) enterRoom();

$("send").disabled = true;                                  // until the mind is resident (early questions queue)

// ── INSTANT FIRST LOAD (κ-substrate) ─────────────────────────────────────────────────────────────

// The mind streams as content-addressed, verify-on-read blocks. We warm them into the SAME persistent

// cache + URL keys the real loader (loadKappaObject → holo-kappa-v1, "<base>/b/<κ>.gz") reads — starting

// the MOMENT the welcome paints. The seconds a visitor spends reading the welcome become download time,

// so clicking "Start chatting" enters a mind that is already largely resident; every revisit is 0-network

// and works offline. We warm the ACTIVE mind (27B by default) first, then the other, so the dropdown

// switch is fast too. On enter, the live loader owns the wire — these workers step aside and it simply

// reads the blocks we already cached. Aggressive parallelism here is safe: nothing decodes yet on the GPU.

const HF = { "27b": "https://huggingface.co/HOLOGRAMTECH/q-bonsai-27b/resolve/main",

             "8b":  "https://huggingface.co/HOLOGRAMTECH/q-bonsai-8b/resolve/main" };

// I1: the welcome-warm now rides the κ-SWARM (kappa-swarm.mjs) — SAME cache, SAME canonical keys

// ("<HF-base>/b/sha256_<hex>.gz"), so loadKappaObject hits warm no matter which mirror served the

// bytes; and unlike the old warmKappa, every block is sha256-verified BEFORE it is cached. Extra

// origins are a pure list add in defaultMirrors(); ?mirror=<base>[,<base>] adds test origins

// (sha-named layout) — safe by construction: a wrong/hostile mirror fails verification and only

// loses the race. On enter the live loader owns the wire (shouldStop), exactly as before.

const XMIRR = (QS.get("mirror") || "").split(",").map((s) => s.trim()).filter(Boolean);

const swarmMirrors = (base) => defaultMirrors(base).concat(XMIRR.map((b, i) => ({ label: "x" + i, base: b, kind: "sha" })));

// ── S0 THE SPEAKING MIND (one κ): the 8B and its voice are ALSO published fused — one bao payload,

// ONE BLAKE3 root. The carve loader streams that single file in verified range windows and slices

// members into the SAME canonical cache keys the per-block loaders read; on any failure the

// per-block swarm simply finishes the remainder. Voice-first packing → the voice is resident at

// ~6% of the wire. The root below is the Law-L5 pin: one hash holds the mind and its voice.

const FUSED_BASE = QS.get("fused") || "https://huggingface.co/HOLOGRAMTECH/q-bonsai-8b-speaking/resolve/main";

const FUSED_ROOT = "4eed444d6f04bcfc059f66bab17b7a54d2eca96b7a8713f8f5eeab0b3d14be99";   // v2: mind + voice + EAR (incl. its whole runtime), one hash

let fusedStats = null;                                       // witness (window.__fused)

async function warmFused(conc, force) {

  try {

    const { carveWarm } = await import("./bao-carve.mjs");

    fusedStats = await carveWarm({ base: FUSED_BASE, root: FUSED_ROOT, conc,

      shouldStop: () => (force ? false : streamStarted),     // force = post-ready top-up (the wire is idle then)

      pause: () => busy,                                     // NEVER carve while the mind decodes — one readback/token is main-thread and scheduler-sensitive

      onProgress: (pr) => {                                  // feed the visible % with MIND bytes only (voice + ear ride ahead of it)

        if (M27 || !pr.index) return;

        const nonMind = pr.nonMindBytes != null ? pr.nonMindBytes

                      : (pr.index.voiceBytes || 0) + ((pr.index.members.find((m) => m.raw) || {}).len || 0);

        if (pr.totalBytes) PROG.total = pr.totalBytes - nonMind;

        const mindHave = Math.max(0, pr.haveBytes - nonMind);

        if (mindHave > PROG.have) PROG.have = mindHave;

      } });

    window.__fused = fusedStats;

    return !!(fusedStats && fusedStats.ok);

  } catch (e) { return false; }

}

// ── W0.5: the 27B ALSO streams as ONE bao object — payload.bin (3.63 GB, boot-ordered gz blocks)

// under ONE BLAKE3 root, outboard 0.098%. Same carve loader as the fused 8B; its index names

// tensors instead of carrying cache keys, so members are mapped through the model manifest

// (name → sha256 κ) into the exact keys loadKappaObject reads. Any index/manifest mismatch throws

// inside the carve → fail-soft false → the per-block swarm path takes over, byte-identical.

const BAO27_BASE = HF["27b"] + "/bao/full";

const BAO27_ROOT = "cd7271ec4f780ea052669e7c8fec6e1c2d74dbfdeebf2573d49ede169bf36a6f";

let bao27Stats = null;                                       // witness (window.__bao27)

async function warmBao27(conc) {

  try {

    let man = null;

    try { man = (M27 && MAN_P) ? await MAN_P : null; } catch (e) {}

    if (!man) man = await (await fetch(HF["27b"] + "/manifest.json")).json();

    if (!man || !man.tensors) return false;

    const { carveWarm } = await import("./bao-carve.mjs");

    bao27Stats = await carveWarm({ base: BAO27_BASE, root: BAO27_ROOT, conc,

      shouldStop: () => streamStarted,

      pause: () => busy,                                     // yield the decode thread while the mind speaks

      mapMembers: (index) => index.tensors.map((t) => {

        const rec = man.tensors[t.name];

        if (!rec || rec.stored !== t.len) throw new Error("bao index != manifest: " + t.name);

        return { off: t.off, len: t.len, cacheKey: HF["27b"] + "/b/sha256_" + String(rec.kappa).replace(/^sha256:/, "") + ".gz" };

      }),

      onProgress: M27 ? (pr) => {                            // the ACTIVE mind feeds the visible %

        if (pr.totalBytes) PROG.total = pr.totalBytes;

        if (pr.haveBytes > PROG.have) PROG.have = pr.haveBytes;

      } : undefined });

    window.__bao27 = bao27Stats;

    return !!(bao27Stats && bao27Stats.ok);

  } catch (e) { return false; }

}

async function warmKappa(base, conc) {

  try { await swarmWarm({ base, mirrors: swarmMirrors(base), conc, shouldStop: () => streamStarted,

    manifest: (base === BASE && MAN_P) ? (await MAN_P) || undefined : undefined,          // paint-time manifest, fetched once

    onProgress: base === BASE ? (pr) => {                                                  // only the ACTIVE mind feeds the visible %

      if (pr.totalBytes) PROG.total = pr.totalBytes;

      if (pr.haveBytes > PROG.have) PROG.have = pr.haveBytes;

    } : undefined }); } catch (e) {}

}

(async () => {

  if (SRC || BENCH) return;                                                   // dev override / bench: no background pulls

  if (navigator.connection && navigator.connection.saveData) return;          // respect data saver

  // PAINT FIRST, pull second: the warm starts only after the welcome has painted and settled — a

  // fetch storm racing first paint can kill weaker frames outright (observed: the Spaces EMBED

  // iframe died before ever painting). Inside an embed the renderer shares its world with the

  // host page, so every warm runs at half strength there.

  await new Promise((r) => setTimeout(r, 900));

  const EMB = (() => { try { return window.top !== window.self; } catch (e) { return true; } })();

  if (streamStarted) return;                                                  // returning visitor already booting — the live loader owns the wire

  if (!M27) {                                                                 // 8B active: the ONE-κ fused object first (mind + voice + ear in one verified stream)

    const ok = await warmFused(EMB ? 4 : 6);

    if (!ok && !streamStarted) await warmKappa(BASE, EMB ? 6 : 12);           // fused origin unreachable → per-block swarm finishes the remainder

    if (!streamStarted) { const ok27 = await warmBao27(EMB ? 4 : 6); if (!ok27 && !streamStarted) await warmKappa(HF["27b"], EMB ? 4 : 8); }

  } else {

    const ok27 = await warmBao27(EMB ? 5 : 8);                                // the ACTIVE mind (27B by default) as ONE verified bao stream, while the visitor reads

    if (!ok27 && !streamStarted) await warmKappa(BASE, EMB ? 6 : 12);         // bao path unavailable → per-block swarm, byte-identical outcome

    if (!streamStarted) { const ok = await warmFused(EMB ? 3 : 4); if (!ok && !streamStarted) await warmKappa(HF["8b"], EMB ? 4 : 8); }   // then the OTHER mind — fused brings its voice along

  }

})();

(async () => {                                              // returning visitor: the mind wakes BEHIND the welcome screen

  if (BENCH) return;                                        // bench orchestrates its own (cold) load

  // …but NOT inside an embed iframe: silently loading a multi-GB mind into the GPU while sharing

  // a renderer with the host page kills the frame (observed on the Spaces embed). There, the

  // visitor's click starts the boot — warm cache still makes it fast.

  try { if (window.top !== window.self) return; } catch (e) { return; }

  try { const c = await caches.open("holo-kappa-v1"); if (await c.match(BASE + "/manifest.json")) { streamStarted = true; stream(); } } catch {}

})();

// ── I0 BENCH flow: purge (cold) → optional swarm warm to completion → live load → Paris probe. ──

if (BENCH) (async () => {

  const pane = document.createElement("pre");

  pane.id = "benchpanel";

  pane.style.cssText = "position:fixed;left:12px;bottom:12px;z-index:99;max-width:min(92vw,620px);max-height:46vh;overflow:auto;background:rgba(0,0,0,.74);border:1px solid var(--hair);border-radius:10px;padding:10px 12px;font:12px/1.55 ui-monospace,Consolas,monospace;color:#cfcdc6;white-space:pre-wrap;";

  document.body.appendChild(pane);

  window.__bench = BM;                                      // machine-readable for a harness

  if (QS.get("cold") !== "0") {                             // honest cold: drop THIS model's cached entries (bench is opt-in)

    try { const c = await caches.open("holo-kappa-v1"); let n = 0;

      for (const req of await c.keys()) if (req.url.startsWith(BASE + "/")) { await c.delete(req); n++; }

      BM.purged = n; } catch (e) { BM.purged = 0; }

  }

  benchRender();

  if (BM.doSwarm) {

    const mirrors = swarmMirrors(BASE);

    BM.nOrigins = mirrors.length;

    BM.swarm = await swarmWarm({ base: BASE, mirrors, conc: BM.conc, shouldStop: () => false,

                                 onProgress: (pr) => { BM.swarmLive = pr; benchRender(); } });

    benchRender();

  }

  BM.t0 = performance.now();

  enterRoom();                                              // live load: fetch/verify (warm when swarm ran) → GPU → ready → probe

})();

$("send").addEventListener("click", send);

$("inp").addEventListener("keydown", (e) => { if (e.key === "Enter") send(); });

if (!navigator.gpu) { $("go").disabled = true; $("fine").textContent = "This browser has no WebGPU. Chrome or Edge 113 or newer required."; }

</script>
</body>
<script>
/* κ-runtime — content-addressed holospace boot. Classic SW → works on every browser; a no-op where absent. */
(function () {
  if (!("serviceWorker" in navigator)) return;
  try { navigator.serviceWorker.register("portal-sw.js"); } catch (e) {}
  function ready() {
    if (document.getElementById("kappa-ok") || !document.body) return;
    var d = document.createElement("div"); d.id = "kappa-ok"; d.textContent = "offline-ready";
    d.title = "Every file is fetched by content hash and re-derived to it before it runs. After this visit it works with no network.";
    d.style.cssText = "position:fixed;top:15px;right:17px;z-index:60;font:500 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.02em;color:rgba(232,230,224,.42);opacity:0;transition:opacity .7s ease;user-select:none";
    var dot = document.createElement("span");
    dot.style.cssText = "display:inline-block;width:6px;height:6px;border-radius:50%;background:currentColor;opacity:.7;margin-right:7px;vertical-align:1px";
    d.prepend(dot); document.body.appendChild(d);
    setTimeout(function () { d.style.opacity = "1"; }, 60);   // timeout, not rAF — rAF is throttled in background tabs
  }
  navigator.serviceWorker.ready
    .then(function () { navigator.serviceWorker.controller ? ready() : navigator.serviceWorker.addEventListener("controllerchange", ready); })
    .catch(function () {});
})();
</script>