rapid-structure-rs 1.0.0

Rust document-structure engine for PaddleOCR-family ONNX models: text detection/recognition (PP-OCRv6), table structure (SLANet-plus) and formula recognition (PP-FormulaNet) on Windows x64 via ONNX Runtime.
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
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
<!doctype html>
<html lang="zh-CN" data-theme="light">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>RapidStructure · 本地评估台</title>
    <!--
  ── rapidstruct serve 内联静态页(docs/05 §9 前端规范)──────────────────────────
  · 服务端以 include_str! 读取本文件。占位符契约是**严格的**,实现方必须逐条满足:

    (1) 全文**恰好**只有两种替换点,别无其它:
          __CSP_NONCE__  ×4  →  本次启动随机 nonce。4 处分别是 GET / 响应头
                                Content-Security-Policy 里的 nonce-<值>,以及本文件
                                <style> ×1 与 <script> ×2 的 nonce 属性。
          __SRV_TOKEN__  ×3  →  本次启动随机令牌(客户端经 X-RapidStructure-Token 头携带)。
                                3 处分别是:script 里的 window.__RROCR__ 初始化、
                                JS 顶部的环境判定注释、以及契约说明文字。
        (本段说明文字自身也逐字写有这两个占位符名,属文档而非替换点,不计入上表;
          服务端统计替换点时应按 nonce 属性 / 代码中的赋值点计数,不要用全文出现次数。
          唯一允许的例外就是本注释块:它被替换后仍保留占位符字面量。)
        两处替换值都必须断言**非空**(随机数生成失败 → 启动失败,不得下发空 nonce)。

    (2) 替换完成后,服务端必须把整页**重新扫一遍**:正文里只要仍存在上述两个字面量
        (即本注释块之外的任何一处),就立即报错退出(fail loudly),绝不允许把未注入
        的页面发给浏览器。残留检查必须**精确匹配这两个字面量**,不得写成
        "任意双下划线包裹的大写名"(如 /__[A-Z]+__/)这类模糊模式——本页还有 JS 全局名
        window.__RROCR__,而 RROCR 恰好全大写,模糊模式会对已正确注入的页面误报。

    (3) 响应头里的 nonce 必须与页面内每一个 nonce 属性**逐字节相同**:服务端在读取
        本文件后,先把每个 nonce="…" 属性的值与待下发头部的值做**相等断言**,再开始
        提供 GET /。一处不等价于 CSP 与文档不匹配,浏览器会**静默**拦掉全部脚本
        (页面看起来"能打开但完全不动"),因此该断言不允许省略。

    全文件只允许上述两种占位符写法,不得引入任何其它占位符形式(例如双花括号包裹的
    变体、或同一名字的其它前后缀写法)。本注释内也不书写 script/style 标签字面量,
    以免被"数标签"式的检查或工具误判为脚本块。

    📌 本文件的最终归属是 `src/bin/web/index.html`(由 rapidstruct serve 以 include_str!
    内联);`rapidstruct serve` 落地时把本文件搬过去即可,**当前仍留在 Temp/ 下**。

  · 零外部资源(§9.6):图标为内联 SVG sprite,字体为系统字体栈;
    无内联事件属性、无内联 style 属性(nonce CSP 不放行 style 属性,style 属性同样会被
    拦掉),一切动态样式通过 CSSOM(element.style.*)或 class 切换完成。
    缩放同理:显示尺寸由 JS 写入 element.style.width/height,标记里没有任何 style 属性。
  · 占位符未被替换(直接以文件方式打开)时,自动进入"离线预览"演示模式,
    界面与交互完整可用,数据为内置演示数据,页面顶部有常驻标识。
-->
    <style nonce="__CSP_NONCE__">
      /* ============ 主题变量(黑白灰) ============ */
      * {
        box-sizing: border-box;
        margin: 0;
        padding: 0;
      }
      :root {
        --bg: #f2f2f0;
        --surface: #fafaf8;
        --fg: #141414;
        --fg2: #666668;
        --fg3: #9c9c9e;
        --line: #dfdfdc;
        --shadow: 0 12px 40px rgba(0, 0, 0, 0.1);
      }
      html[data-theme="dark"] {
        --bg: #0e0e0e;
        --surface: #161616;
        --fg: #eaeae8;
        --fg2: #9a9a9c;
        --fg3: #5c5c5e;
        --line: #242424;
        --shadow: 0 12px 40px rgba(0, 0, 0, 0.5);
      }
      html {
        color-scheme: light;
      }
      html[data-theme="dark"] {
        color-scheme: dark;
      }
      *,
      *::before,
      *::after {
        transition:
          background-color 0.35s ease,
          border-color 0.35s ease,
          color 0.35s ease;
      }
      body {
        font-family:
          "Noto Sans SC", "Source Han Sans SC", "PingFang SC",
          "Microsoft YaHei", sans-serif;
        background: var(--bg);
        color: var(--fg);
        height: 100vh;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        -webkit-font-smoothing: antialiased;
      }
      .mono {
        font-family:
          "JetBrains Mono", "Cascadia Mono", Consolas, "Courier New", monospace;
      }
      ::-webkit-scrollbar {
        width: 8px;
        height: 8px;
      }
      ::-webkit-scrollbar-thumb {
        background: var(--line);
      }
      ::-webkit-scrollbar-track {
        background: transparent;
      }
      :focus-visible {
        outline: 2px solid var(--fg);
        outline-offset: 2px;
      }
      button {
        font-family: inherit;
        color: inherit;
      }
      [hidden] {
        display: none !important;
      }

      /* View Transitions:主题切换圆形扩散 */
      ::view-transition-old(root),
      ::view-transition-new(root) {
        animation: none;
        mix-blend-mode: normal;
      }

      /* ============ 动画 ============ */
      @keyframes rise {
        from {
          opacity: 0;
          transform: translateY(12px);
        }
        to {
          opacity: 1;
          transform: none;
        }
      }
      @keyframes spin {
        to {
          transform: rotate(360deg);
        }
      }
      @keyframes scanMove {
        from {
          top: -2px;
        }
        to {
          top: 100%;
        }
      }
      @keyframes toastIn {
        from {
          opacity: 0;
          transform: translateX(16px);
        }
        to {
          opacity: 1;
          transform: none;
        }
      }
      @keyframes toastOut {
        to {
          opacity: 0;
          transform: translateX(12px);
        }
      }
      @keyframes ind {
        from {
          margin-left: 0;
        }
        to {
          margin-left: 70%;
        }
      }
      @keyframes flashB {
        0%,
        100% {
          border-color: var(--line);
        }
        50% {
          border-color: var(--fg);
        }
      }
      @keyframes blink {
        0%,
        100% {
          opacity: 1;
        }
        50% {
          opacity: 0.25;
        }
      }
      .spin {
        animation: spin 0.9s linear infinite;
      }

      /* ============ 图标(内联 SVG sprite) ============ */
      .ic {
        width: 1em;
        height: 1em;
        display: inline-block;
        vertical-align: -0.14em;
        fill: none;
        stroke: currentColor;
        stroke-width: 2;
        stroke-linecap: round;
        stroke-linejoin: round;
      }

      /* ============ 顶栏 ============ */
      header {
        height: 58px;
        flex: none;
        border-bottom: 1px solid var(--line);
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 26px;
        animation: rise 0.6s cubic-bezier(0.22, 1, 0.36, 1) both;
      }
      .brand {
        display: flex;
        align-items: center;
        gap: 13px;
      }
      .brand-mark {
        width: 26px;
        height: 26px;
        background: var(--fg);
        color: var(--bg);
        display: grid;
        place-items: center;
        font-size: 15px;
      }
      .brand-name {
        font-family:
          "Noto Serif SC", "Source Han Serif SC", "Songti SC", SimSun, serif;
        font-weight: 700;
        font-size: 16px;
        letter-spacing: 0.05em;
      }
      .brand-en {
        font-family: "JetBrains Mono", Consolas, monospace;
        font-size: 9.5px;
        letter-spacing: 0.3em;
        color: var(--fg3);
        margin-top: 2px;
      }
      .head-right {
        display: flex;
        align-items: center;
        gap: 16px;
      }
      .engine-pill {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 12px;
        color: var(--fg2);
        border: 1px solid var(--line);
        padding: 7px 13px;
      }
      .engine-pill .ic {
        font-size: 14px;
      }
      .dot {
        width: 7px;
        height: 7px;
        border-radius: 50%;
        background: var(--fg3);
        display: inline-block;
      }
      .dot.ok {
        background: var(--fg);
        animation: blink 2.4s ease infinite;
      }
      .head-sep {
        width: 1px;
        height: 20px;
        background: var(--line);
      }
      .icon-btn {
        width: 36px;
        height: 36px;
        border: 1px solid var(--line);
        background: transparent;
        color: var(--fg2);
        display: grid;
        place-items: center;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }
      .icon-btn:hover {
        border-color: var(--fg2);
        color: var(--fg);
      }
      .icon-btn .ic {
        position: absolute;
        font-size: 17px;
        transition:
          transform 0.5s cubic-bezier(0.4, 0, 0.2, 1),
          opacity 0.25s;
      }
      html[data-theme="light"] .icon-btn .i-moon {
        opacity: 1;
        transform: none;
      }
      html[data-theme="light"] .icon-btn .i-sun {
        opacity: 0;
        transform: rotate(120deg) scale(0.5);
      }
      html[data-theme="dark"] .icon-btn .i-moon {
        opacity: 0;
        transform: rotate(-120deg) scale(0.5);
      }
      html[data-theme="dark"] .icon-btn .i-sun {
        opacity: 1;
        transform: none;
      }

      /* ============ 演示条 / 模型横幅(流式,不遮挡焦点) ============ */
      .demo-strip {
        border-bottom: 1px solid var(--line);
        padding: 7px 26px;
        font-size: 12px;
        color: var(--fg2);
        display: flex;
        align-items: center;
        gap: 8px;
      }
      .demo-strip .ic {
        font-size: 14px;
        flex: none;
      }
      .banner {
        border-bottom: 1px solid var(--line);
        padding: 16px 26px;
      }
      .banner.flash {
        animation: flashB 0.5s ease 2;
      }
      .banner-main {
        display: flex;
        gap: 16px;
        align-items: flex-start;
      }
      .banner-ic {
        font-size: 22px;
        color: var(--fg2);
        flex: none;
        margin-top: 2px;
      }
      .banner-info {
        flex: 1;
        min-width: 0;
      }
      .banner-title {
        display: flex;
        flex-wrap: wrap;
        align-items: baseline;
        gap: 6px 14px;
      }
      .banner-title b {
        font-family: "Noto Serif SC", "Songti SC", SimSun, serif;
        font-size: 16px;
        font-weight: 700;
      }
      .banner-title span {
        font-size: 12px;
        color: var(--fg2);
      }
      .banner-files {
        margin-top: 10px;
        border-top: 1px solid var(--line);
      }
      .bf-row {
        display: grid;
        grid-template-columns: auto 1fr auto auto;
        gap: 4px 14px;
        align-items: baseline;
        padding: 7px 2px;
        border-bottom: 1px solid var(--line);
        font-size: 11.5px;
      }
      .bf-state {
        border: 1px solid var(--fg2);
        padding: 1px 6px;
        font-size: 10px;
        letter-spacing: 0.1em;
      }
      .bf-state.bad {
        border-style: dashed;
      }
      .bf-name {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: var(--fg);
      }
      .bf-role {
        color: var(--fg3);
      }
      .bf-size {
        color: var(--fg2);
      }
      /* 逐文件三态:图标 + 颜色都要能区分(E16.1.2),不只靠文字。 */
      .bf-state {
        display: inline-flex;
        align-items: center;
        gap: 4px;
      }
      .bf-state.present {
        border-style: solid;
        border-color: var(--fg2);
        color: var(--fg2);
      }
      .bf-state.missing {
        border-style: dashed;
        color: var(--fg3);
      }
      .bf-state.corrupt {
        border-style: double;
        border-color: var(--fg);
        color: var(--fg);
        font-weight: 600;
      }
      .bf-state .ic {
        font-size: 11px;
      }
      /* sha256 默认只露前 12 位(够做肉眼比对),展开才给全文(E16.1.2)。 */
      .bf-sha-row {
        border-bottom: 1px solid var(--line);
        padding: 4px 2px 6px;
        font-size: 10.5px;
        color: var(--fg3);
      }
      .bf-sha-row > summary {
        cursor: pointer;
        font-family: "JetBrains Mono", Consolas, monospace;
      }
      .bf-sha-row > code {
        display: block;
        margin-top: 4px;
        word-break: break-all;
        color: var(--fg2);
      }
      /* ============ 模型清单面板(E16.1:常驻,不再只在出错时出现) ============ */
      .msets {
        margin-top: 10px;
        border-top: 1px solid var(--line);
      }
      .mset {
        border-bottom: 1px solid var(--line);
        padding: 8px 2px 10px;
      }
      .mset > summary {
        display: flex;
        flex-wrap: wrap;
        align-items: baseline;
        gap: 6px 12px;
        cursor: pointer;
      }
      .mset > summary::marker {
        color: var(--fg3);
      }
      .ms-state {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        font-size: 10px;
        letter-spacing: 0.1em;
        border: 1px solid var(--fg2);
        padding: 1px 6px;
        color: var(--fg2);
        flex: none;
      }
      .ms-state.ok {
        border-style: solid;
      }
      .ms-state.bad {
        border-style: dashed;
        border-color: var(--fg);
        color: var(--fg);
        font-weight: 600;
      }
      .ms-state .ic {
        font-size: 11px;
      }
      .ms-id {
        font-family: "JetBrains Mono", Consolas, monospace;
        font-size: 13px;
      }
      .ms-meta {
        font-size: 11.5px;
        color: var(--fg3);
      }
      .ms-act {
        margin-top: 10px;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 10px;
      }
      .ms-act .banner-note {
        margin-top: 0;
      }
      /* ============ 模型计划表(E16.1.3:服务端解析的结论,页面只呈现) ============ */
      .plan {
        margin-top: 14px;
        border-top: 1px solid var(--line);
        padding-top: 10px;
      }
      .plan-title {
        font-size: 11.5px;
        letter-spacing: 0.08em;
        color: var(--fg3);
        margin-bottom: 6px;
      }
      .plan-wrap {
        overflow-x: auto;
      }
      .plan-wrap table {
        border-collapse: collapse;
        font-size: 11.5px;
        width: 100%;
      }
      .plan-wrap th,
      .plan-wrap td {
        border-bottom: 1px solid var(--line);
        padding: 5px 8px 5px 0;
        text-align: left;
        vertical-align: top;
      }
      .plan-wrap th {
        font-size: 10.5px;
        letter-spacing: 0.08em;
        color: var(--fg3);
        font-weight: 500;
      }
      .plan-wrap .pn {
        font-family: "JetBrains Mono", Consolas, monospace;
        word-break: break-all;
      }
      .plan-wrap .ps-missing,
      .plan-wrap .ps-corrupt {
        font-weight: 600;
      }
      .banner-note {
        font-size: 11.5px;
        color: var(--fg3);
        margin-top: 8px;
        line-height: 1.7;
      }
      .banner-act {
        flex: none;
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        gap: 8px;
      }
      .banner-dl {
        margin-top: 12px;
      }
      /* 横幅内"按集合下载"按钮:禁用态用类而不是 disabled 属性——
   真实服务端的 /api/models 里 source_url 可能不存在,缺 URL 时不能把按钮渲染成"可点"假象,
   但禁用按钮又不会派发 click 事件,用户得不到解释。因此用 aria-disabled + 类 + 点击后 toast 说明。 */
      .btn-mini {
        height: auto;
        padding: 8px 13px;
        font-size: 11.5px;
        letter-spacing: 0.08em;
        flex: none;
      }
      .banner-act .btn-mini {
        margin: 0;
      }
      .btn-mini[aria-disabled="true"] {
        opacity: 0.4;
        cursor: not-allowed;
        border-style: dashed;
      }
      .dl-line {
        font-size: 12px;
        color: var(--fg2);
        display: flex;
        justify-content: space-between;
        gap: 16px;
        margin-bottom: 8px;
      }
      /* ============ 重新校验(POST /api/models/reverify,A2) ============ */
      .verify-row {
        display: flex;
        align-items: center;
        gap: 10px;
        flex-wrap: wrap;
        margin: 8px 0 2px;
      }
      .verify-hint {
        font-size: 11px;
        color: var(--fg3);
        margin: 0;
        line-height: 1.6;
      }
      .verify-out {
        margin-top: 8px;
        border: 1px solid var(--line);
        padding: 9px 11px;
        font-size: 11.5px;
        color: var(--fg2);
        line-height: 1.75;
      }
      .verify-out b {
        color: var(--fg);
      }
      .verify-out .vo-line {
        display: block;
      }
      .verify-out .vo-files {
        margin-top: 6px;
        border-top: 1px solid var(--line);
        padding-top: 6px;
      }
      .verify-out .vo-row {
        display: flex;
        gap: 10px;
        align-items: baseline;
        padding: 3px 0;
      }
      .verify-out .vo-name {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: var(--fg);
      }
      .verify-out .vo-state {
        flex: none;
        letter-spacing: 0.08em;
      }
      .verify-out .vo-state.ok {
        color: var(--fg2);
      }
      .verify-out .vo-state.bad {
        color: var(--fg);
        border-bottom: 1px dashed var(--fg);
      }
      .dl-line b {
        font-weight: 500;
        color: var(--fg);
      }
      .bar {
        height: 2px;
        background: var(--line);
        position: relative;
        overflow: hidden;
      }
      .bar i {
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        width: 0;
        background: var(--fg);
        transition: width 0.18s linear;
      }
      .bar.ind i {
        width: 30% !important;
        animation: ind 1.1s ease-in-out infinite alternate;
      }

      /* ============ 通用按钮 ============ */
      .btn-primary {
        height: 48px;
        border: none;
        background: var(--fg);
        color: var(--bg);
        cursor: pointer;
        font-size: 14px;
        font-weight: 500;
        letter-spacing: 0.14em;
        padding: 0 22px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 9px;
        transition:
          transform 0.18s cubic-bezier(0.22, 1, 0.36, 1),
          opacity 0.3s;
      }
      .btn-primary:not(:disabled):hover {
        transform: translateY(-2px);
      }
      .btn-primary:disabled {
        opacity: 0.28;
        cursor: not-allowed;
      }
      .btn-ghost {
        height: 44px;
        border: 1px solid var(--line);
        background: transparent;
        color: var(--fg2);
        font-size: 13px;
        letter-spacing: 0.1em;
        cursor: pointer;
        padding: 0 18px;
        display: inline-flex;
        align-items: center;
        gap: 8px;
      }
      .btn-ghost:hover:not(:disabled) {
        border-color: var(--fg2);
        color: var(--fg);
      }
      .btn-ghost:disabled {
        opacity: 0.35;
        cursor: not-allowed;
      }
      .text-btn {
        border: none;
        background: none;
        color: var(--fg3);
        font-size: 12px;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        gap: 5px;
        padding: 4px 6px;
      }
      .text-btn:hover:not(:disabled) {
        color: var(--fg);
      }
      .text-btn:disabled {
        opacity: 0.4;
        cursor: not-allowed;
      }
      .text-btn .ic {
        font-size: 13px;
      }
      .sm {
        height: 40px;
        font-size: 12.5px;
        padding: 0 16px;
      }

      /* ============ 主体布局 ============ */
      main {
        flex: 1;
        min-height: 0;
        display: grid;
        grid-template-columns: minmax(400px, 46fr) 54fr;
      }
      .left {
        border-right: 1px solid var(--line);
        display: flex;
        flex-direction: column;
        gap: 14px;
        padding: 22px 24px;
        min-height: 0;
        animation: rise 0.6s 0.08s cubic-bezier(0.22, 1, 0.36, 1) both;
      }
      .right {
        overflow-y: auto;
        padding: 24px 32px 44px;
        min-height: 0;
        animation: rise 0.6s 0.16s cubic-bezier(0.22, 1, 0.36, 1) both;
      }
      .right-inner {
        max-width: 720px;
      }
      .sec-label {
        display: flex;
        align-items: center;
        gap: 12px;
        font-size: 11px;
        letter-spacing: 0.2em;
        color: var(--fg2);
        font-weight: 500;
        white-space: nowrap;
        min-width: 0;
      }
      .sec-label span {
        font-family: "JetBrains Mono", Consolas, monospace;
        font-size: 9px;
        letter-spacing: 0.26em;
        color: var(--fg3);
      }
      .sec-label::after {
        content: "";
        flex: 1;
        height: 1px;
        background: var(--line);
      }
      .gap {
        margin-top: 30px;
      }
      .panel-head {
        display: flex;
        align-items: center;
        gap: 10px;
      }
      .panel-head .sec-label {
        flex: 1;
      }

      /* ============ 左栏:输入 ============ */
      /* 缩放控件组(demo2 的 zoomOut/zoomLbl/zoomIn/zoomFit + 原始尺寸 1:1) */
      .zoom-group {
        display: flex;
        border: 1px solid var(--line);
      }
      .zoom-group > * + * {
        border-left: 1px solid var(--line);
      }
      .vt-btn {
        width: 34px;
        height: 32px;
        border: none;
        background: transparent;
        color: var(--fg3);
        cursor: pointer;
        display: grid;
        place-items: center;
      }
      .vt-btn.txt {
        font-family: "JetBrains Mono", Consolas, monospace;
        font-size: 10.5px;
      }
      .vt-btn:hover:not([aria-pressed="true"]) {
        color: var(--fg);
      }
      .vt-btn[aria-pressed="true"] {
        background: var(--fg);
        color: var(--bg);
      }
      .vt-btn .ic {
        font-size: 15px;
      }
      .zoom-lbl {
        min-width: 70px;
        padding: 0 8px;
        display: grid;
        place-items: center;
        font-family: "JetBrains Mono", Consolas, monospace;
        font-size: 10.5px;
        color: var(--fg2);
        font-variant-numeric: tabular-nums;
        white-space: nowrap;
      }
      .drop {
        flex: 1;
        min-height: 0;
        position: relative;
        border: 1px solid var(--line);
        cursor: pointer;
        outline: none;
        overflow: hidden;
      }
      .drop:hover,
      .drop:focus-visible {
        border-color: var(--fg3);
      }
      .drop.dragging {
        border-color: var(--fg);
        background: color-mix(in srgb, var(--fg) 4%, transparent);
      }
      .drop.no-click {
        cursor: default;
      }
      .corner {
        position: absolute;
        width: 15px;
        height: 15px;
        border: 0 solid var(--fg);
        transition: all 0.35s cubic-bezier(0.22, 1, 0.36, 1);
        z-index: 2;
        pointer-events: none;
      }
      .c-tl {
        top: -1px;
        left: -1px;
        border-top-width: 1.5px;
        border-left-width: 1.5px;
      }
      .c-tr {
        top: -1px;
        right: -1px;
        border-top-width: 1.5px;
        border-right-width: 1.5px;
      }
      .c-bl {
        bottom: -1px;
        left: -1px;
        border-bottom-width: 1.5px;
        border-left-width: 1.5px;
      }
      .c-br {
        bottom: -1px;
        right: -1px;
        border-bottom-width: 1.5px;
        border-right-width: 1.5px;
      }
      .drop:hover .corner,
      .drop.dragging .corner {
        width: 20px;
        height: 20px;
      }
      .drop:hover .c-tl,
      .drop.dragging .c-tl {
        transform: translate(-5px, -5px);
      }
      .drop:hover .c-tr,
      .drop.dragging .c-tr {
        transform: translate(5px, -5px);
      }
      .drop:hover .c-bl,
      .drop.dragging .c-bl {
        transform: translate(-5px, 5px);
      }
      .drop:hover .c-br,
      .drop.dragging .c-br {
        transform: translate(5px, 5px);
      }
      .drop.has-image:hover .corner {
        transform: none;
      }
      .empty-state {
        position: absolute;
        inset: 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 13px;
        text-align: center;
        padding: 24px;
        pointer-events: none;
      }
      .empty-state > .ic {
        font-size: 44px;
        color: var(--fg3);
        transition:
          color 0.3s,
          transform 0.3s;
      }
      .drop:hover .empty-state > .ic,
      .drop.dragging .empty-state > .ic {
        color: var(--fg);
        transform: translateY(-3px);
      }
      .drop.dragging .empty-state > .ic {
        transform: scale(1.1);
      }
      .empty-title {
        font-size: 14.5px;
        font-weight: 500;
        letter-spacing: 0.04em;
      }
      .empty-sub {
        font-size: 12.5px;
        color: var(--fg2);
      }
      .empty-sub kbd {
        font-family: "JetBrains Mono", Consolas, monospace;
        font-size: 10.5px;
        border: 1px solid var(--line);
        padding: 1px 5px;
        color: var(--fg2);
      }
      .empty-meta {
        font-family: "JetBrains Mono", Consolas, monospace;
        font-size: 10px;
        letter-spacing: 0.14em;
        color: var(--fg3);
        margin-top: 5px;
      }
      /* 预览 + 叠加画布 */
      /* 预览 + 叠加画布:stage 的像素尺寸 = 原图尺寸 × 当前缩放(由 JS 经 CSSOM 写入),
   img 与 canvas 都以 100% 填满 stage → 叠框在任何缩放下都与图像严格对齐。
   margin:auto 居中:内容小于容器时居中,大于容器时可正常滚动(不会被裁掉起始边)。
   scrollbar-gutter:stable:滚动条槽位恒定保留,clientWidth/Height 不随是否溢出变化,
   适应窗口(fitScale)的测量因此稳定,不会出现"适配后多出/少掉一条滚动条"的抖动。 */
      .stage-wrap {
        position: absolute;
        inset: 16px;
        display: grid;
        overflow: auto;
        scrollbar-gutter: stable;
      }
      .stage {
        position: relative;
        margin: auto;
        line-height: 0;
      }
      .stage img {
        display: block;
        width: 100%;
        height: 100%;
        animation: rise 0.4s cubic-bezier(0.22, 1, 0.36, 1) both;
      }
      .stage canvas {
        position: absolute;
        inset: 0;
        cursor: crosshair;
      }
      /* 透明文本层(Step 2)。职责划分:**DOM 层负责「选中并复制」,Canvas 继续负责视觉框与高亮**。
   库只给出文本 + 坐标,浏览器里的选择交互属于宿主呈现层,因此这一层只存在于自带的网页 Demo 里。
   · 层本身 `pointer-events:none`,只有 span 可交互 → 空白处仍然点得到叠框;
   · span 的定位完全由 `transform: matrix()` 给出,矩阵由 word polygon 的两条边(p0→p1、p0→p3)
     求出,所以倾斜/旋转的行**不会**被替换成轴对齐外接矩形(那是丢旋转,不是近似);
   · 字形透明(`color:transparent`)→ 不遮挡图像,选中时由 ::selection 给出可见高亮;
   · 静态规则写在本 `<style>`(带 nonce)里,动态的 fontSize/transform 走 CSSOM ——
     主页面的 CSP 是 `style-src 'nonce-…'`,**没有** `'unsafe-inline'`,内联 `style=` 属性会被拒绝。 */
      .text-layer {
        position: absolute;
        inset: 0;
        z-index: 1;
        pointer-events: none;
      }
      .text-layer[hidden] {
        display: none;
      }
      .tl-line {
        position: absolute;
        inset: 0;
        pointer-events: none;
      }
      /* 探测元素与 span 必须**逐字**同一套字体口径,否则量出来的推进宽与实际渲染不符,
         仿射的第一列就会算错(宽度是按「推进宽 ÷ 字号」的比值换算的)。 */
      .tl-word,
      .tl-probe {
        font-family: "Segoe UI", "Microsoft YaHei", sans-serif;
        font-weight: 400;
        letter-spacing: 0;
        white-space: pre;
      }
      .tl-word {
        position: absolute;
        left: 0;
        top: 0;
        margin: 0;
        padding: 0;
        border: 0;
        line-height: 1;
        transform-origin: 0 0;
        color: transparent;
        cursor: text;
        pointer-events: auto;
        user-select: text;
        -webkit-user-select: text;
      }
      .tl-word::selection {
        background: color-mix(in srgb, var(--fg) 34%, transparent);
      }
      .tl-probe {
        position: absolute;
        left: 0;
        top: 0;
        font-size: 100px;
        line-height: 1;
        visibility: hidden;
        pointer-events: none;
      }
      .scanline {
        position: absolute;
        left: 0;
        right: 0;
        top: -2px;
        height: 1.5px;
        background: var(--fg);
        opacity: 0;
        pointer-events: none;
        z-index: 2;
        box-shadow: 0 0 14px 1px color-mix(in srgb, var(--fg) 45%, transparent);
      }
      .stage.scanning .scanline {
        opacity: 0.9;
        animation: scanMove 2.6s cubic-bezier(0.45, 0.05, 0.55, 0.95) infinite;
      }
      /* 文件信息行 */
      .file-meta {
        display: flex;
        align-items: center;
        gap: 9px;
        min-width: 0;
        font-family: "JetBrains Mono", Consolas, monospace;
        font-size: 11.5px;
        color: var(--fg2);
      }
      .file-meta > .ic {
        font-size: 14px;
        color: var(--fg3);
        flex: none;
      }
      .file-meta .meta-text {
        flex: 1;
        min-width: 0;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .file-meta .meta-text b {
        color: var(--fg);
        font-weight: 500;
      }
      /* 上传进度 / 任务行 */
      .prog {
        display: flex;
        flex-direction: column;
        gap: 8px;
      }
      .prog-row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 12px;
        font-size: 12.5px;
        color: var(--fg2);
      }
      .prog-row b {
        font-family: "JetBrains Mono", Consolas, monospace;
        font-weight: 500;
        color: var(--fg);
      }
      .job-line {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 12px;
        border: 1px solid var(--line);
        padding: 10px 14px;
        font-size: 12.5px;
        color: var(--fg2);
      }
      .job-line .jl-state {
        display: flex;
        align-items: center;
        gap: 8px;
        min-width: 0;
      }
      .job-line .ic {
        font-size: 14px;
        flex: none;
      }
      .job-line b {
        color: var(--fg);
        font-weight: 500;
      }
      .actions {
        display: flex;
        align-items: center;
        gap: 12px;
      }
      .actions .btn-primary {
        flex: 1;
      }

      /* ============ 右上:引擎面板 ============ */
      .engine-panel {
        margin-top: 14px;
      }
      .eng-state {
        display: flex;
        align-items: center;
        gap: 10px;
        font-size: 15px;
        padding: 13px 0 12px;
      }
      .eng-state .ic {
        font-size: 18px;
      }
      .eng-state b {
        font-family: "Noto Serif SC", "Songti SC", SimSun, serif;
        font-weight: 700;
        letter-spacing: 0.04em;
      }
      .eng-state .eng-note {
        font-family: "JetBrains Mono", Consolas, monospace;
        font-size: 10.5px;
        color: var(--fg3);
        letter-spacing: 0.08em;
        margin-left: 4px;
      }
      .eng-warn {
        font-size: 12px;
        color: var(--fg2);
        line-height: 1.8;
        border-left: 2px solid var(--fg);
        padding: 2px 0 2px 12px;
        margin: 2px 0 6px;
        display: flex;
        gap: 8px;
        align-items: flex-start;
      }
      .eng-warn .ic {
        font-size: 14px;
        flex: none;
        margin-top: 3px;
      }
      .eng-kv {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 14px 20px;
        border-top: 1px solid var(--line);
        padding-top: 14px;
      }
      .eng-kv > div {
        min-width: 0;
      }
      .eng-kv dt {
        font-size: 10px;
        letter-spacing: 0.14em;
        color: var(--fg3);
        margin-bottom: 4px;
      }
      .eng-kv dd {
        font-family: "JetBrains Mono", Consolas, monospace;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .eng-kv dd.warn-dd {
        font-weight: 600;
        color: var(--fg);
      }
      .eng-kv dd.warn-dd .ic {
        font-size: 13px;
      }
      .eng-kv dd.ep-unknown {
        color: var(--fg3);
        border-bottom: 1px dashed var(--line);
      } /* 未知 ≠ 否:虚线标记,不只靠颜色 */
      .eng-retry {
        margin-top: 14px;
      }

      /* 队列就绪状态(docs/05 §8.1 双队列):文本队列与公式队列**分别**给出结论。
   公式缺失只影响公式队列,绝不呈现为"整页失败";文字 + 图标 + 边框三重线索,不只靠颜色。 */
      .eng-q {
        display: flex;
        align-items: flex-start;
        gap: 9px;
        margin-top: 14px;
        border-left: 2px solid var(--line);
        padding: 7px 0 7px 12px;
        font-size: 12px;
        line-height: 1.7;
      }
      .eng-q .ic {
        font-size: 14px;
        flex: none;
        margin-top: 3px;
      }
      .eng-q-txt {
        min-width: 0;
        font-family: "JetBrains Mono", Consolas, monospace;
        font-size: 11.5px;
      }
      .eng-q-txt b {
        font-family: "Noto Sans SC", "Microsoft YaHei", sans-serif;
        font-weight: 600;
        font-size: 12px;
        letter-spacing: 0.04em;
      }
      .eng-q-ok {
        border-left-style: solid;
        border-left-color: var(--fg);
      }
      .eng-q-warn {
        border-left-style: dashed;
        border-left-color: var(--fg);
      } /* 警告=虚线,区分于实线就绪 */
      .eng-q-off {
        color: var(--fg2);
      }
      .eng-q-off .ic {
        color: var(--fg3);
      }

      /* 识别模式选择器(E16.2)。四项 = `queue` × `table` 的全部可表达组合。
    禁用项除颜色外还用**虚线边框**与行内文字点名缺失角色;选中项用 `aria-checked`
    与左侧实心条双重标记,不依赖颜色。 */
      .mode-row {
        margin-top: 14px;
        border: 1px dashed var(--line);
        padding: 10px 14px 12px;
        min-width: 0;
      }
      .mode-legend {
        font-size: 11.5px;
        font-weight: 600;
        letter-spacing: 0.04em;
        color: var(--fg2);
        padding: 0 6px;
      }
      .mode-opts {
        display: grid;
        grid-template-columns: repeat(2, minmax(0, 1fr));
        gap: 7px;
        margin-top: 4px;
      }
      .mode-opt {
        display: flex;
        align-items: flex-start;
        gap: 8px;
        text-align: left;
        border: 1px solid var(--line);
        background: none;
        color: var(--fg);
        padding: 8px 10px;
        cursor: pointer;
        min-width: 0;
        font: inherit;
      }
      .mode-opt .mo-dot {
        flex: none;
        width: 9px;
        height: 9px;
        margin-top: 4px;
        border: 1px solid var(--fg3);
        border-radius: 50%;
      }
      .mode-opt .mo-body {
        min-width: 0;
        display: flex;
        flex-direction: column;
        gap: 2px;
      }
      .mode-opt .mo-name {
        font-size: 12.5px;
        font-weight: 600;
      }
      .mode-opt .mo-desc {
        font-size: 11px;
        color: var(--fg2);
        line-height: 1.5;
      }
      .mode-opt[aria-checked="true"] {
        border-color: var(--fg);
        border-style: solid;
      }
      .mode-opt[aria-checked="true"] .mo-dot {
        background: var(--fg);
        border-color: var(--fg);
        box-shadow: inset 0 0 0 2px var(--bg);
      }
      .mode-opt[aria-disabled="true"] {
        border-style: dashed;
        cursor: not-allowed;
        opacity: 0.62;
      }
      .mode-cap {
        display: block;
        margin-top: 8px;
        font-size: 11.5px;
        color: var(--fg2);
        line-height: 1.7;
      }

      /* ============ 右中:区域列表 ============ */
      .region-list {
        margin-top: 12px;
      }
      .region-item {
        display: flex;
        gap: 14px;
        width: 100%;
        text-align: left;
        border: none;
        background: none;
        border-left: 3px solid transparent;
        border-bottom: 1px solid var(--line);
        cursor: pointer;
        padding: 12px 10px 12px 12px;
        animation: rise 0.45s cubic-bezier(0.22, 1, 0.36, 1) both;
      }
      .region-item:first-child {
        border-top: 1px solid var(--line);
      }
      .region-item:hover {
        background: color-mix(in srgb, var(--fg) 3%, transparent);
      }
      .region-item.sel {
        border-left-color: var(--fg);
        background: var(--surface);
      }
      .ri-idx {
        font-family: "JetBrains Mono", Consolas, monospace;
        font-size: 11px;
        color: var(--fg3);
        padding-top: 2px;
        min-width: 22px;
      }
      .region-item.sel .ri-idx {
        background: var(--fg);
        color: var(--bg);
        padding: 1px 4px;
      }
      .ri-body {
        flex: 1;
        min-width: 0;
        display: flex;
        flex-direction: column;
        gap: 6px;
      }
      .ri-line {
        display: flex;
        align-items: baseline;
        gap: 10px;
        flex-wrap: wrap;
      }
      .tag {
        font-style: normal;
        font-size: 10px;
        letter-spacing: 0.12em;
        border: 1px solid var(--fg2);
        padding: 1px 6px;
        color: var(--fg2);
        flex: none;
      }
      .tag-fx {
        border-style: dashed;
      }
      .ri-text {
        font-size: 14px;
        line-height: 1.6;
        word-break: break-all;
      }
      .ri-sub {
        font-family: "JetBrains Mono", Consolas, monospace;
        font-size: 10.5px;
        color: var(--fg3);
      }
      /* ============ 表格区域卡片(E16.3) ============ */
      .tag-tbl {
        border-style: solid;
        border-width: 2px;
      }
      .tag-tbl-in {
        border-style: dotted;
        border-color: var(--fg3);
        color: var(--fg3);
      }
      .rt-badge {
        font-style: normal;
        font-size: 10px;
        letter-spacing: 0.08em;
        border: 1px solid var(--fg2);
        padding: 1px 6px;
        color: var(--fg2);
        flex: none;
      }
      /* 低置信必须**看得见**:不只换颜色,还加粗边框 + 反色底 + 卡片左侧虚线。 */
      .rt-badge-low {
        border-width: 2px;
        border-color: var(--fg);
        background: var(--fg);
        color: var(--bg);
        font-weight: 600;
      }
      .region-table.rt-low {
        border-left: 3px dashed var(--fg2);
      }
      .rt-wrap {
        overflow-x: auto;
        max-width: 100%;
        padding: 2px 0;
      }
      .rt-wrap table {
        border-collapse: collapse;
        font-size: 12.5px;
        line-height: 1.5;
      }
      .rt-wrap td,
      .rt-wrap th {
        border: 1px solid var(--line);
        padding: 3px 7px;
        vertical-align: top;
        white-space: pre-wrap;
      }
      .rt-wrap thead td,
      .rt-wrap thead th {
        background: var(--surface);
      }
      /* 表格渲染按钮(E24)。默认只显示 HTML 原文,点击才把净化后的表格放进 DOM:
         与公式"默认原文、按需渲染"同构,也避免一张大表的几百个单元格把结果列表撑爆。 */
      .rt-actions {
        display: flex;
        align-items: center;
        gap: 8px;
        margin: 6px 0 0;
      }
      .rt-btn {
        font: inherit;
        font-size: 12px;
        line-height: 1.6;
        padding: 1px 10px;
        border: 1px solid var(--line);
        border-radius: 999px;
        background: transparent;
        color: var(--fg2);
        cursor: pointer;
      }
      .rt-btn:hover {
        border-color: var(--fg2);
        color: var(--fg);
      }
      .rt-hint {
        font-size: 11px;
        color: var(--fg3);
      }
      .rt-raw {
        margin: 6px 0 0;
        padding: 8px 10px;
        max-height: 220px;
        overflow: auto;
        border-radius: 6px;
        background: var(--surface);
        color: var(--fg2);
        font-size: 11px;
        line-height: 1.55;
        white-space: pre-wrap;
        word-break: break-all;
      }
      .rt-raw > code {
        font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
      }
      .rt-wrap[hidden],
      .rt-raw[hidden] {
        display: none;
      }
      /* 被表格消费的文本行:按钮 + 兄弟 details 组成一组,分隔线只画在组底。 */
      .ri-fold-wrap {
        display: flex;
        flex-direction: column;
      }
      .ri-folded {
        opacity: 0.72;
        border-bottom: none;
      }
      .ri-fold {
        border-bottom: 1px solid var(--line);
        padding: 0 10px 10px 12px;
      }
      .ri-fold > summary {
        cursor: pointer;
        font-size: 11px;
        color: var(--fg3);
        padding: 2px 0;
      }
      .ri-fold-body {
        font-size: 13px;
        line-height: 1.6;
        word-break: break-all;
        color: var(--fg2);
        padding: 6px 0 2px;
      }
      .empty-inline {
        padding: 52px 20px;
        text-align: center;
        color: var(--fg3);
        font-size: 13px;
        line-height: 2;
      }
      .empty-inline .ic {
        font-size: 36px;
        display: block;
        margin: 0 auto 14px;
      }

      /* 区域列表入场延迟(不用 style 属性,改用 nth-child) */
      .region-item:nth-child(1) {
        animation-delay: 0.04s;
      }
      .region-item:nth-child(2) {
        animation-delay: 0.1s;
      }
      .region-item:nth-child(3) {
        animation-delay: 0.16s;
      }
      .region-item:nth-child(4) {
        animation-delay: 0.22s;
      }
      .region-item:nth-child(5) {
        animation-delay: 0.28s;
      }
      .region-item:nth-child(6) {
        animation-delay: 0.34s;
      }
      .region-item:nth-child(7) {
        animation-delay: 0.4s;
      }
      .region-item:nth-child(8) {
        animation-delay: 0.46s;
      }
      .region-item:nth-child(n + 9) {
        animation-delay: 0.52s;
      }

      /* ============ 右下:导出与诊断 ============ */
      .export-row {
        display: flex;
        gap: 12px;
        margin-top: 14px;
        flex-wrap: wrap;
      }
      .export-row .btn-ghost {
        flex: 1;
        min-width: 120px;
      }
      /* M4 评估:一行输入 + 一张小表(复用诊断表的排版,不新增视觉语言) */
      .eval-row {
        display: flex;
        gap: 10px;
        margin-top: 14px;
        align-items: stretch;
      }
      .eval-input {
        flex: 1;
        min-width: 0;
        background: transparent;
        color: var(--fg);
        border: 1px solid var(--line);
        border-radius: 2px;
        padding: 8px 10px;
        font-family: "JetBrains Mono", Consolas, monospace;
        font-size: 11.5px;
      }
      .eval-input:focus-visible {
        outline: 2px solid var(--fg);
        outline-offset: 1px;
      }
      .eval-out {
        margin-top: 12px;
        border: 1px solid var(--line);
        padding: 12px 14px;
      }
      .eval-out .diag-table td:first-child {
        text-align: left;
      }
      .eval-sum {
        font-size: 12px;
        color: var(--fg);
        margin: 0 0 10px;
        line-height: 1.8;
      }
      .eval-sum b {
        font-weight: 600;
      }
      .diag {
        margin-top: 22px;
        border: 1px solid var(--line);
      }
      .diag summary {
        list-style: none;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 12px 16px;
        font-size: 13px;
        color: var(--fg2);
        user-select: none;
      }
      .diag summary::-webkit-details-marker {
        display: none;
      }
      .diag summary:hover {
        color: var(--fg);
      }
      .diag summary .ic {
        font-size: 15px;
      }
      .diag .chev {
        margin-left: auto;
        transition: transform 0.3s;
      }
      .diag[open] .chev {
        transform: rotate(180deg);
      }
      .diag-body {
        border-top: 1px solid var(--line);
        padding: 18px 18px 20px;
      }
      .diag-sec {
        font-size: 10.5px;
        letter-spacing: 0.18em;
        color: var(--fg3);
        margin: 16px 0 10px;
      }
      .diag-sec:first-child {
        margin-top: 0;
      }
      .diag-table {
        border-collapse: collapse;
        width: 100%;
        font-size: 12px;
      }
      .diag-table td {
        border-bottom: 1px solid var(--line);
        padding: 7px 2px;
        color: var(--fg2);
      }
      .diag-table td:last-child {
        text-align: right;
        color: var(--fg);
      }
      .diag-table tr.total td {
        color: var(--fg);
        font-weight: 600;
        border-bottom: none;
      }
      .diag-line {
        font-family: "JetBrains Mono", Consolas, monospace;
        font-size: 11.5px;
        color: var(--fg2);
        line-height: 1.9;
        word-break: break-all;
      }
      .diag-note {
        font-size: 11.5px;
        color: var(--fg3);
        line-height: 1.9;
        margin-top: 16px;
        border-left: 2px solid var(--line);
        padding-left: 12px;
      }
      /* 流动日志(详细模式):最近请求一行 + 失败响应体原文。
   页面是**单色**设计(没有红色语义色),因此成功/失败用字重与明度区分,不引入新色相。 */
      .flow-ok {
        color: var(--fg2);
      }
      .flow-bad {
        color: var(--fg);
        font-weight: 600;
      }
      .flow-body {
        font-family: "JetBrains Mono", Consolas, monospace;
        font-size: 11px;
        color: var(--fg2);
        background: var(--surface);
        border: 1px solid var(--line);
        padding: 10px 12px;
        margin: 0 0 10px;
        white-space: pre-wrap;
        word-break: break-all;
        max-height: 220px;
        overflow: auto;
      }
      .diag-line label {
        cursor: pointer;
      }
      .foot-note {
        font-family: "JetBrains Mono", Consolas, monospace;
        font-size: 10px;
        letter-spacing: 0.14em;
        color: var(--fg3);
        margin-top: 30px;
      }

      /* ============ Toast ============ */
      .toasts {
        position: fixed;
        right: 20px;
        bottom: 20px;
        display: flex;
        flex-direction: column;
        gap: 10px;
        z-index: 80;
        max-width: min(360px, calc(100vw - 40px));
      }
      .toast {
        display: flex;
        align-items: flex-start;
        gap: 10px;
        background: var(--surface);
        border: 1px solid var(--line);
        padding: 12px 16px;
        font-size: 13px;
        line-height: 1.6;
        box-shadow: var(--shadow);
        animation: toastIn 0.4s cubic-bezier(0.22, 1, 0.36, 1) both;
      }
      .toast .ic {
        font-size: 15px;
        flex: none;
        margin-top: 2px;
      }
      .toast.out {
        animation: toastOut 0.35s ease forwards;
      }

      /* ============ 响应式 ============ */
      @media (max-width: 960px) {
        body {
          height: auto;
          overflow: auto;
        }
        main {
          grid-template-columns: 1fr;
        }
        .left {
          border-right: none;
          border-bottom: 1px solid var(--line);
        }
        .drop {
          min-height: 340px;
        }
        .eng-kv {
          grid-template-columns: repeat(2, 1fr);
        }
        .banner-main {
          flex-direction: column;
        }
        .banner-act {
          align-items: flex-start;
        }
      }

      /* ============ 公式渲染工具条(KaTeX / MathJax 可切换) ============ */
      .fx-render-bar {
        display: flex;
        align-items: center;
        gap: 10px;
        flex-wrap: wrap;
        margin-top: 10px;
        font-size: 11.5px;
        color: var(--fg2);
      }
      .fxr-txt {
        letter-spacing: 0.06em;
      }
      .fxr-hint {
        font-family: "JetBrains Mono", Consolas, monospace;
        font-size: 10.5px;
        color: var(--fg3);
      }
      .seg {
        display: flex;
        border: 1px solid var(--line);
      }
      .seg-btn {
        height: 26px;
        padding: 0 11px;
        border: none;
        background: transparent;
        color: var(--fg3);
        font-size: 11px;
        letter-spacing: 0.04em;
        cursor: pointer;
        font-family: inherit;
        display: inline-flex;
        align-items: center;
      }
      .seg-btn + .seg-btn {
        border-left: 1px solid var(--line);
      }
      .seg-btn:hover:not([aria-pressed="true"]) {
        color: var(--fg);
      }
      .seg-btn[aria-pressed="true"] {
        background: var(--fg);
        color: var(--bg);
      }
      .seg-btn:disabled {
        opacity: 0.4;
        cursor: not-allowed;
      }

      /* 公式区域渲染容器:横向可滚动,避免长公式撑破窄列;字号继承正文,不引入新颜色 */
      .ri-text.fx-slot {
        display: block;
        overflow-x: auto;
        overflow-y: hidden;
        word-break: normal;
        overflow-wrap: anywhere;
        padding: 1px 0;
      }
      .ri-text.fx-slot .katex {
        color: var(--fg);
      }
      .ri-text.fx-slot .katex-display {
        text-align: left;
        margin: 0.15em 0;
      }
      .ri-text.fx-slot mjx-container {
        color: var(--fg);
      }
      /* 渲染失败:左侧竖线标记(形状线索),保留原文 */
      .ri-text.fx-slot.fx-error {
        border-left: 2px solid var(--fg);
        padding-left: 8px;
      }
    </style>
    <script nonce="__CSP_NONCE__">
      window.__RROCR__ = { token: "__SRV_TOKEN__" };
    </script>
  </head>
  <body>
    <!-- ============ 内联 SVG 图标(零外部资源) ============ -->
    <svg width="0" height="0" aria-hidden="true" focusable="false">
      <symbol id="i-scan" viewBox="0 0 24 24">
        <path d="M4 8V6a2 2 0 0 1 2-2h2" />
        <path d="M16 4h2a2 2 0 0 1 2 2v2" />
        <path d="M20 16v2a2 2 0 0 1-2 2h-2" />
        <path d="M8 20H6a2 2 0 0 1-2-2v-2" />
        <path d="M4 12h16" />
      </symbol>
      <symbol id="i-upload" viewBox="0 0 24 24">
        <path d="M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2" />
        <path d="M7 9l5-5 5 5" />
        <path d="M12 4v12" />
      </symbol>
      <symbol id="i-download" viewBox="0 0 24 24">
        <path d="M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2" />
        <path d="M7 10l5 5 5-5" />
        <path d="M12 15V3" />
      </symbol>
      <symbol id="i-image" viewBox="0 0 24 24">
        <rect x="3" y="5" width="18" height="14" rx="2" />
        <circle cx="8.5" cy="10" r="1.5" />
        <path d="M21 15.5l-4.5-4.5L7 20" />
      </symbol>
      <symbol id="i-file" viewBox="0 0 24 24">
        <path d="M14 3v4a1 1 0 0 0 1 1h4" />
        <path

          d="M17 21H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7l5 5v11a2 2 0 0 1-2 2z"

        />
      </symbol>
      <symbol id="i-x" viewBox="0 0 24 24">
        <path d="M18 6L6 18M6 6l12 12" />
      </symbol>
      <symbol id="i-check" viewBox="0 0 24 24">
        <path d="M5 12l5 5L20 7" />
      </symbol>
      <symbol id="i-copy" viewBox="0 0 24 24">
        <rect x="8" y="8" width="12" height="12" rx="2" />
        <path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2" />
      </symbol>
      <symbol id="i-sun" viewBox="0 0 24 24">
        <circle cx="12" cy="12" r="4" />
        <path

          d="M3 12h1M20 12h1M12 3v1M12 20v1M5.6 5.6l.7.7M17.7 17.7l.7.7M18.4 5.6l-.7.7M6.3 17.7l-.7.7"

        />
      </symbol>
      <symbol id="i-moon" viewBox="0 0 24 24">
        <path

          d="M12 3c.13 0 .26 0 .39 0a7.5 7.5 0 0 0 7.92 12.44A9 9 0 1 1 12 3z"

        />
      </symbol>
      <symbol id="i-cloud-off" viewBox="0 0 24 24">
        <path d="M3 3l18 18" />
        <path

          d="M6 17a4.5 4.5 0 0 1-.3-9A6 6 0 0 1 16.7 6.5c.22 0 .48.02.7.07"

        />
        <path d="M10.5 17H15" />
      </symbol>
      <symbol id="i-package" viewBox="0 0 24 24">
        <path d="M12 3l8 4.5v9L12 21l-8-4.5v-9L12 3z" />
        <path d="M12 12l8-4.5M12 12v9M12 12L4 7.5" />
      </symbol>
      <symbol id="i-alert" viewBox="0 0 24 24">
        <path

          d="M10.24 3.96L2.5 17.5a1.9 1.9 0 0 0 1.65 2.85h15.7a1.9 1.9 0 0 0 1.65-2.85L13.76 3.96a2 2 0 0 0-3.52 0z"

        />
        <path d="M12 9v4M12 17h.01" />
      </symbol>
      <symbol id="i-loader" viewBox="0 0 24 24">
        <path d="M12 3a9 9 0 1 0 9 9" />
      </symbol>
      <symbol id="i-refresh" viewBox="0 0 24 24">
        <path d="M20 12a8 8 0 1 1-2.34-5.66" />
        <path d="M20 4v4h-4" />
      </symbol>
      <symbol id="i-clock" viewBox="0 0 24 24">
        <circle cx="12" cy="12" r="9" />
        <path d="M12 7v5l3 2" />
      </symbol>
      <symbol id="i-chevron" viewBox="0 0 24 24">
        <path d="M6 9l6 6 6-6" />
      </symbol>
      <symbol id="i-fit" viewBox="0 0 24 24">
        <path d="M4 8V6a2 2 0 0 1 2-2h2" />
        <path d="M16 4h2a2 2 0 0 1 2 2v2" />
        <path d="M20 16v2a2 2 0 0 1-2 2h-2" />
        <path d="M8 20H6a2 2 0 0 1-2-2v-2" />
        <path d="M9 12h6" />
      </symbol>
      <symbol id="i-zoom-in" viewBox="0 0 24 24">
        <circle cx="10" cy="10" r="7" />
        <path d="M21 21l-6-6" />
        <path d="M10 7v6M7 10h6" />
      </symbol>
      <symbol id="i-zoom-out" viewBox="0 0 24 24">
        <circle cx="10" cy="10" r="7" />
        <path d="M21 21l-6-6" />
        <path d="M7 10h6" />
      </symbol>
      <symbol id="i-clipboard" viewBox="0 0 24 24">
        <path

          d="M9 4H7a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2h-2"

        />
        <rect x="9" y="2" width="6" height="4" rx="1" />
      </symbol>
      <symbol id="i-info" viewBox="0 0 24 24">
        <circle cx="12" cy="12" r="9" />
        <path d="M12 8h.01M11 12h1v4h1" />
      </symbol>
    </svg>

    <!-- ============ 顶栏 ============ -->
    <header>
      <div class="brand">
        <div class="brand-mark">
          <svg class="ic" aria-hidden="true" focusable="false">
            <use href="#i-scan" />
          </svg>
        </div>
        <div>
          <div class="brand-name">RapidStructure · 本地评估台</div>
          <div class="brand-en">
            LOCAL&nbsp;EVAL&nbsp;CONSOLE&nbsp;·&nbsp;LOOPBACK&nbsp;ONLY
          </div>
        </div>
      </div>
      <div class="head-right">
        <div class="engine-pill" id="enginePill" aria-live="polite"></div>
        <div class="head-sep"></div>
        <button class="icon-btn" id="themeBtn" aria-label="切换深浅色主题">
          <svg class="ic i-moon" aria-hidden="true" focusable="false">
            <use href="#i-moon" />
          </svg>
          <svg class="ic i-sun" aria-hidden="true" focusable="false">
            <use href="#i-sun" />
          </svg>
        </button>
      </div>
    </header>

    <!-- 离线预览标识(serve 注入令牌后不显示) -->
    <div class="demo-strip" id="demoStrip" hidden>
      <svg class="ic" aria-hidden="true" focusable="false">
        <use href="#i-info" />
      </svg>
      离线预览模式 — 本页未经 serve
      注入令牌:界面与交互完整可用,数据为内置演示数据。
    </div>

    <!-- 模型状态横幅(缺失 / 损坏 / 下载进度,§9.2) -->
    <div

      class="banner"

      id="banner"

      role="region"

      aria-label="模型状态"

      hidden

    ></div>

    <main>
      <!-- ============ 左:输入图像 ============ -->
      <section class="left" aria-label="输入图像">
        <div class="panel-head">
          <div class="sec-label">输入图像 <span>INPUT</span></div>
          <!-- 缩放控件组(demo2 的 zoomOut/zoomLbl/zoomIn/zoomFit;1:1 即 demo3 原“原始尺寸”模式) -->
          <div

            class="zoom-group"

            id="zoomGroup"

            role="group"

            aria-label="缩放与视图"

            hidden

          >
            <button

              class="vt-btn"

              id="zoomOut"

              type="button"

              title="缩小(-)"

              aria-label="缩小"

            >
              <svg class="ic" aria-hidden="true" focusable="false">
                <use href="#i-zoom-out" />
              </svg>
            </button>
            <span

              class="zoom-lbl"

              id="zoomLbl"

              aria-live="polite"

              title="当前显示比例"

              >100%</span

            >
            <button

              class="vt-btn"

              id="zoomIn"

              type="button"

              title="放大(+)"

              aria-label="放大"

            >
              <svg class="ic" aria-hidden="true" focusable="false">
                <use href="#i-zoom-in" />
              </svg>
            </button>
            <button

              class="vt-btn"

              id="zoomFit"

              type="button"

              aria-pressed="true"

              title="适应窗口"

              aria-label="适应窗口"

            >
              <svg class="ic" aria-hidden="true" focusable="false">
                <use href="#i-fit" />
              </svg>
            </button>
            <button

              class="vt-btn txt"

              id="zoomActual"

              type="button"

              aria-pressed="false"

              title="原始尺寸 100%(0)"

              aria-label="原始尺寸(100%)"

            >
              1:1
            </button>
          </div>
          <button class="text-btn" id="clearBtn" hidden title="移除图像">
            <svg class="ic" aria-hidden="true" focusable="false">
              <use href="#i-x" /></svg

            >移除
          </button>
        </div>

        <div

          class="drop"

          id="drop"

          tabindex="0"

          role="button"

          aria-label="拖入图像,或按 Enter 选择文件"

        >
          <span class="corner c-tl"></span><span class="corner c-tr"></span>
          <span class="corner c-bl"></span><span class="corner c-br"></span>
          <div class="empty-state" id="emptyState">
            <svg class="ic" aria-hidden="true" focusable="false">
              <use href="#i-image" />
            </svg>
            <div class="empty-title">拖拽图像至此处</div>
            <div class="empty-sub">
              或点击选择文件 · 支持粘贴 <kbd>Ctrl</kbd> + <kbd>V</kbd>
            </div>
            <div class="empty-meta">IMAGE/*&nbsp;·&nbsp;识别全程在本机完成</div>
          </div>
          <div class="stage-wrap" id="stageWrap" hidden>
            <div class="stage" id="stage">
              <img id="view" alt="待识别图像预览" />
              <canvas id="overlay" aria-hidden="true"></canvas>
              <!-- 透明文本层:词/字级 span 由 JS 用 createElement + CSSOM 生成(见 renderTextLayer)。
                   aria-hidden:这层是**给鼠标用的**辅助层,键盘/读屏用户的等价入口是右栏的区域列表
                   (那里有完整的文本与阅读顺序);两层同时进可及树会让同一段文字被读两次。 -->
              <div class="text-layer" id="textLayer" hidden aria-hidden="true"></div>
              <div class="scanline"></div>
            </div>
          </div>
        </div>

        <div class="file-meta" id="fileMeta" hidden>
          <svg class="ic" aria-hidden="true" focusable="false">
            <use href="#i-file" />
          </svg>
          <span class="meta-text" id="metaText"></span>
          <button

            class="text-btn"

            id="annotatedBtn"

            hidden

            title="下载叠加检测框的标注图"

          >
            <svg class="ic" aria-hidden="true" focusable="false">
              <use href="#i-download" /></svg

            >下载标注图
          </button>
        </div>

        <!-- 上传进度:XHR upload.onprogress,取消上传 = xhr.abort()(§9.1) -->
        <div class="prog" id="uploadProg" hidden>
          <div class="prog-row">
            <span>上传中 <b id="upPct">0%</b></span>
            <button class="text-btn" id="abortUpBtn">
              <svg class="ic" aria-hidden="true" focusable="false">
                <use href="#i-x" /></svg

              >取消上传
            </button>
          </div>
          <div class="bar"><i id="upBar"></i></div>
        </div>

        <!-- 任务状态行:取消识别 = POST /api/jobs/{id}/cancel(与取消上传分开,§4.3) -->
        <div class="job-line" id="jobLine" hidden aria-live="polite">
          <span class="jl-state" id="jlText"></span>
          <button class="text-btn" id="cancelJobBtn">取消识别</button>
        </div>

        <!-- 识别模式选择器(E16.2)。四项就是**全部**可表达的组合:`queue` 决定排哪条队列,
         `table` 决定那条队列是否额外跑表格阶段(docs/11 §4.2)。每一项的禁用态由
         renderModeRow() 依据 modelsReadyFor() 逐个写入;不可用时在 #modeCap 里**点名**缺哪个
         角色(不只靠颜色/透明度)。放在提交按钮**之前**:模型未就绪时用户先看到原因,再看到按钮。 -->
        <fieldset class="mode-row" id="modeRow" hidden>
          <legend class="mode-legend">识别模式</legend>
          <div class="mode-opts" id="modeOpts" role="radiogroup" aria-describedby="modeCap"></div>
          <span class="mode-cap" id="modeCap" aria-live="polite"></span>
        </fieldset>

        <!-- 框粒度选择器(Step 2)。三档就是 `WordOutputMode` 的**全部**取值(src/api.rs 的
         `as_str`/`from_name`/`ALL` 是唯一词表来源),缺省 off:不请求逐词/逐字框时,响应体与
         后处理开销都不增加。放在识别模式**之后**、提交按钮之前,理由与模式选择器相同——
         用户先看到会发出去什么,再按提交。#wordsCap 点名每档的实际含义,包括
         「字级框是 CTC 后处理估计」这条不能省略的口径。 -->
        <fieldset class="mode-row" id="wordsRow" hidden>
          <legend class="mode-legend">框粒度</legend>
          <div class="mode-opts" id="wordsOpts" role="radiogroup" aria-describedby="wordsCap"></div>
          <span class="mode-cap" id="wordsCap" aria-live="polite"></span>
        </fieldset>

        <div class="actions">
          <!-- 从剪贴板取图(demo2 的 pasteBtn):与拖放/选择文件共用 handleFile 入口 -->
          <button

            class="btn-ghost"

            id="pasteBtn"

            type="button"

            title="从剪贴板读取图像(等同 Ctrl+V)"

          >
            <svg class="ic" aria-hidden="true" focusable="false">
              <use href="#i-clipboard" /></svg

            >从剪贴板
          </button>
          <button class="btn-primary" id="ocrBtn" disabled>
            <svg class="ic" aria-hidden="true" focusable="false" id="ocrIco">
              <use href="#i-scan" />
            </svg>
            <span id="ocrLbl">等待图像输入</span>
          </button>
        </div>
      </section>

      <!-- ============ 右:状态 / 区域 / 导出诊断 ============ -->
      <section class="right" aria-label="识别结果">
        <div class="right-inner">
          <div class="sec-label">引擎状态 <span>ENGINE</span></div>
          <div class="engine-panel" id="enginePanel"></div>
          <!-- 重新校验(A2):POST /api/models/reverify —— 清掉校验缓存 → 冷验证本次运行会用到的
           每个模型文件 → 如果引擎此前就绪则**重建会话**。它是"确定性地重新读盘"的入口
           (docs/05 §4.2):模型文件在运行期被换掉时,只有它会同时刷新"报告的状态"与
           "内存里真正在服务的会话"。放在常驻位置(而不是模型横幅里)是因为横幅在模型
           齐备时是隐藏的,而这个动作在齐备时同样有意义。 -->
          <div class="verify-row">
            <button

              class="btn-ghost sm"

              id="verifyBtn"

              type="button"

              title="清掉校验缓存,重新读盘核对本次运行会用到的每个模型文件,并重建引擎会话"

            >
              <svg class="ic" aria-hidden="true" focusable="false">
                <use href="#i-refresh" /></svg

              >重新校验
            </button>
            <p class="verify-hint" id="verifyHint">
              POST /api/models/reverify · 重新读盘核对模型并重建引擎会话
            </p>
          </div>
          <div class="verify-out" id="verifyOut" role="status" hidden></div>

          <div class="sec-label gap">
            识别区域 <span>REGIONS&nbsp;·&nbsp;阅读顺序</span>
            <button class="text-btn" id="copyAllBtn" disabled>
              <svg class="ic" aria-hidden="true" focusable="false">
                <use href="#i-copy" /></svg

              >复制全文
            </button>
          </div>
          <!-- 公式渲染工具条:只在结果里出现公式区域时显示(renderRegions 控制 hidden)。
     三个分段按钮与 .vt-btn 共用同一视觉语言;按 aria-pressed 表达当前引擎。 -->
          <div

            class="fx-render-bar"

            id="fxRenderBar"

            role="group"

            aria-label="公式渲染模式"

            hidden

          >
            <span class="fxr-txt">公式渲染</span>
            <div class="seg">
              <button

                class="seg-btn"

                type="button"

                data-fx-mode="off"

                aria-pressed="true"

              >
                原文
              </button>
              <button

                class="seg-btn"

                type="button"

                data-fx-mode="katex"

                aria-pressed="false"

              >
                KaTeX
              </button>
              <button

                class="seg-btn"

                type="button"

                data-fx-mode="mathjax"

                aria-pressed="false"

              >
                MathJax
              </button>
            </div>
            <span class="fxr-hint" id="fxRenderHint"

              >首次切换会从同源路径懒加载所选引擎</span

            >
          </div>
          <div class="region-list" id="regionList"></div>

          <div class="sec-label gap">导出 <span>EXPORT</span></div>
          <div class="export-row">
            <button class="btn-ghost" id="expJson" disabled>JSON</button>
            <button class="btn-ghost" id="expMd" disabled>Markdown</button>
            <button

              class="btn-ghost"

              id="expHtml"

              disabled

              title="静态报告,不含脚本"

            >
              HTML(静态)
            </button>
          </div>

          <!-- M4 评估:复用库的 evaluation(CER / 精确匹配),不另写指标。
           请求体只有 {manifest} —— 与本机 `rapidstruct evaluate --manifest` 同格式。 -->
          <div class="sec-label gap">
            评估 <span>EVALUATE&nbsp;·&nbsp;CER</span>
          </div>
          <div class="eval-row">
            <input

              type="text"

              id="evalPath"

              class="eval-input"

              spellcheck="false"

              placeholder="已标注清单的绝对路径(与 rapidstruct evaluate --manifest 同格式)"

              aria-label="标注清单路径"

            />
            <button class="btn-ghost" id="evalBtn">评估</button>
          </div>
          <div class="eval-out" id="evalOut" aria-live="polite" hidden></div>

          <details class="diag" id="diag">
            <summary>
              <svg class="ic" aria-hidden="true" focusable="false">
                <use href="#i-clock" />
              </svg>
              诊断面板
              <svg class="ic chev" aria-hidden="true" focusable="false">
                <use href="#i-chevron" />
              </svg>
            </summary>
            <div class="diag-body" id="diagBody"></div>
          </details>

          <p class="foot-note">
            RAPIDSTRUCTURE&nbsp;SERVE&nbsp;·&nbsp;127.0.0.1&nbsp;·&nbsp;图像与模型不出本机
          </p>
        </div>
      </section>
    </main>

    <div class="toasts" id="toasts" aria-live="polite"></div>
    <input type="file" id="fileInput" accept="image/*" hidden />

    <script nonce="__CSP_NONCE__">
      (function () {
        "use strict";

        /* ================= 环境判定与常量 ================= */
        /* serve 启动时替换 __SRV_TOKEN__;若仍是占位符,说明页面未经 serve 注入 → 离线预览模式 */
        const INJ = window.__RROCR__ || {};
        const TOKEN = INJ.token || "";
        const DEMO = !TOKEN || TOKEN.indexOf("__") === 0;

        const $ = (id) => document.getElementById(id);
        const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
        const esc = (s) =>
          String(s).replace(
            /[&<>"']/g,
            (c) =>
              ({
                "&": "&amp;",
                "<": "&lt;",
                ">": "&gt;",
                '"': "&quot;",
                "'": "&#39;",
              })[c],
          );
        const ic = (n, cls) =>
          `<svg class="ic ${cls || ""}" aria-hidden="true" focusable="false"><use href="#i-${n}"/></svg>`;

        /* §11.1 错误码 → 用户可读文案 */
        const ERR_TEXT = {
          unauthorized: "令牌校验失败,请通过 rapidstruct serve --open 打开本页",
          bad_origin: "Origin 校验失败(非本机来源)",
          bad_host: "Host 校验失败(防 DNS rebinding)",
          payload_too_large:
            "请求体或下载总量超出上限(--max-body-mb / --max-download-mb)",
          result_too_large: "结果序列化超出上限(--max-result-mb)",
          export_too_large:
            "导出文档超出上限(--max-export-mb),请改用“下载标注图”(annotated.png 不受该预算限制)",
          original_evicted:
            "该任务的原图已被保留预算释放(410),标注图无法再生成;识别结果仍可查看,重新上传即可再标注",
          busy: "队列已满(503 busy),请稍后重试",
          models_missing: "模型文件缺失,请先在横幅中下载",
          models_corrupt: "模型文件损坏,建议重新下载",
          downloads_disabled: "服务未开启 --allow-download,无法下载模型",
          insufficient_disk_space: "磁盘空间不足(507)",
          unsupported_input: "无法解码该图像或超出像素上限(24 Mpx)",
          job_not_finished: "识别尚未完成",
          job_evicted: "结果已被淘汰(410),请重新识别",
          not_cancellable: "推理进行中,当前版本不支持中断",
          job_finished: "任务已结束,无法取消",
          download_failed: "模型下载失败",
          download_timeout: "模型下载超时",
          internal: "服务内部错误",
        };

        const ROLE_ZH = {
          detector: "检测",
          recognizer: "识别",
          classifier: "方向分类",
          dictionary: "字典",
          tokenizer: "词表",
          formula_detector: "公式检测",
          formula_recognizer: "公式识别",
          table_structure: "表格结构",
        };

        /* ================= 应用状态 ================= */
        const state = {
          status: null /* 规范化后的 /api/status */,
          models: null /* 规范化后的 /api/models */,
          image: null /* {file,url,w,h} */,
          view: {
            mode: "fit",
            scale: 1,
          } /* 显示缩放(唯一来源):fit = 适应窗口,custom = 百分比 */,
          uploading: false,
          xhr: null /* 当前上传 XHR(用于 abort) */,
          job: null /* {id,kind,queue,state,position,...} */,
          result: null /* {regions,plain,timings,raw} */,
          selected: -1,
          dlActive: false /* 模型下载进行中(真实模式) */,
          dlSetId:
            null /* 正在下载的集合 id(决定哪个按钮禁用;绝不默认 sets[0]) */,
          dlJob:
            null /* 下载任务:{id, set_id, state, elapsed_ms, error} —— 与 OCR 任务同属 job 生命周期 */,
          /* 识别模式(E16.2):'text' | 'formula' | 'text-table' | 'formula-table'。
     取代了 E16 之前的布尔 `formula` —— 那个开关只能表达"跑不跑公式",而表格是
     **正交**的第二维(`queue` × `table`),布尔量装不下四种组合。默认 'text',
     与旧版"公式路由默认关闭"的行为逐字相同(§10.8)。 */
          mode: "text",
          /* 框粒度(Step 2):'off' | 'words' | 'chars',与服务端的 `WordOutputMode`(src/api.rs)
     同一词表、同一缺省。off 时请求里**不带** `words=`,因此缺省路径的响应体与本页早期版本一致。 */
          words: "off",
          diag: [] /* 协议/契约错误记录(渲染进诊断面板;同时 toast 一次) */,
          verifying: false /* "重新校验"进行中(按钮禁用,避免重复提交) */,
          verifyOut:
            null /* 上一次 POST /api/models/reverify 的结论 {value} 或 {error} */,
          netFail: false /* 真实模式:本地服务不可达 */,
          /* 页面侧流动日志(详细模式,默认关闭):每一次 XHR 的方法/URL/状态/耗时/错误码,
     失败时还留响应体原文。目的只有一个——"什么都没渲染"时**不打开 devtools**
     也能看见是哪一次请求、以什么状态、返回了什么。开关见 flowVerboseInitial()。 */
          verbose: false,
          flow: [] /* 最近 20 次请求,最新在前 */,
          flowSeq: 0,
          fx: {
            mode: "off",
          } /* 公式渲染引擎:'off' | 'katex' | 'mathjax'(懒加载,见 FX_LIBS) */,
        };

        const demo = {
          /* 离线预览模式的内部状态 */
          phase:
            "boot" /* boot → waitmodels → building → ready(公式模型不影响文本就绪) */,
          upAbort: false,
          dlActive: false,
          dlPct: 0,
          dlFile: "",
          dlSetId: null,
          /* 文本模型集在离线预览里**已齐备**,公式集**不齐备** —— 这样"文本就绪 / 公式缺失"
     这个关键区分在离线预览下直接可见(§10.8 公式路由默认关闭、M4 公式与普通 OCR 分离)。 */
          textReady: true,
          buildMs: 1500,
        };

        /* ================= 工具 ================= */
        function fmtBytes(b) {
          if (b == null) return "—";
          if (b < 1024) return b + " B";
          const u = ["KB", "MB", "GB"];
          let i = -1;
          do {
            b /= 1024;
            i++;
          } while (b >= 1024 && i < 2);
          return b.toFixed(b >= 100 ? 0 : 1) + " " + u[i];
        }
        function hostOf(u) {
          try {
            return new URL(u).host;
          } catch {
            return "";
          }
        }
        /* §7.5:/api/status 必须同时给出 requested / selected_ep / fallback_to_cpu。
   字段缺失时必须能表达“未知”,不得用默认值冒充——fallback 的 null 与 false 语义不同。 */
        const firstText = (...vals) => {
          for (const v of vals)
            if (v != null && String(v).trim() !== "") return String(v);
          return null; /* null = 未知 */
        };
        const firstBool = (...vals) => {
          for (const v of vals) {
            if (typeof v === "boolean") return v;
            if (v === "true") return true;
            if (v === "false") return false;
          }
          return null; /* null = 未知(≠ false) */
        };
        function emptyStatus(engState) {
          /* 规范化 status 的空壳:三字段均为未知 */
          return {
            state: engState || "unknown",
            requested: null,
            selected_ep: null,
            fallback: null,
            ort: "—",
            fingerprint: null,
            memory: null,
            queues: null,
            limits: null,
          };
        }
        function isTextField(el) {
          /* 文本框聚焦时不得劫持按键 / 拦截粘贴(§9.4) */
          if (!el || !el.tagName) return false;
          const tag = el.tagName.toUpperCase();
          return (
            tag === "INPUT" ||
            tag === "TEXTAREA" ||
            tag === "SELECT" ||
            el.isContentEditable === true
          );
        }
        function zhQueue(q) {
          return q === "formula" ? "公式" : "文本";
        }
        function jobActive() {
          return !!(
            state.job &&
            (state.job.state === "queued" || state.job.state === "running")
          );
        }

        /* ============ 队列就绪判定(docs/05 §8.1 双队列 / §10.8 公式路由默认关闭) ============
  模型集的**就绪是按队列分别判定的**,不存在"任一集合不齐备就整页不可用"这种全局结论:
    · text    → 只需普通 OCR 模型集齐备:detector + recognizer + dictionary;
    · formula → 需要公式模型集齐备:formula_recognizer。
  公式模型缺失(566 MB,默认不下载)绝不允许阻塞普通文本 OCR;反之亦然。
  后端以 `files[].role` + `files[].state` 表达每个文件的状态(§5.4 / ModelSetStatus),
  因此这里按**角色**取并集判定,而不是挑某一个集合 id —— 服务端将来拆/并集合都不影响。

  M4 的一处数据修正:公式**检测**模型(pix2text-mfd-1.5.onnx)在 FormulaPolicy 里是可选的、
  也没有可信的下载来源,因此它**不是**公式集合的成员(assets/default_models.yaml 的
  `formula:` 段注释、库的 `ModelRequest::formula_roles()` 只要求 formula_recognizer)。
  把它当成必需角色会让开关永远不可用;它是否存在由服务端在 `/api/models` 的
  `formula.detector` / `formula.routing` 里回答(见 modelsReadyFor)。 */
        const QUEUE_ROLES = {
          text: ["detector", "recognizer", "dictionary"],
          formula: ["formula_recognizer"],
          /* 这里**故意没有 table**(E22):表格的结构模型可以完全不在任何模型集合里
     (`--table-model` 从模型目录之外指定,例如 models/table/manifest.json 的 slanet-plus.onnx),
     按 role 去 `sets[].files[]` 找会把它误判成"缺失"并永久置灰一个其实可用的模式。
     表格的就绪由服务端的 `/api/models.table` 块回答(`routing` / `complete` / `missing` /
     `structure.state`),见 `modelsReadyFor()` 里的提前返回。 */
        };
        function modelFiles() {
          const m = state.models;
          if (!m || !Array.isArray(m.sets))
            return null; /* 尚未取到 /api/models */
          if (m.error) return null;
          return m.sets.flatMap((s) => s.files || []);
        }
        /* 返回 {ready, missing:[角色中文名], fatal:bool, reason:string|null}。
   fatal = 连模型清单都没有(请求失败 / 尚未返回)——此时才不允许提交任何队列。
   损坏(corrupt)与缺失一样都是"不可用",但文案必须区分(§5.2 损坏建议重新下载)。
   formula 还额外要求服务端的**公式路由可用**(`/api/models.formula.routing`):
   M4 的公式管线需要页面公式检测模型(--formula-detector),没有它就只处理调用方显式声明的
   区域,而 HTTP 请求里没有这种区域——那样"成功"的公式任务永远产不出公式区域。
   服务端把理由写在 `formula.disabled_reason` 里,这里原样显示(§9.4:不只靠禁用态)。 */
        function modelsReadyFor(queue) {
          const files = modelFiles();
          if (files === null)
            return { ready: false, missing: [], fatal: true, reason: null };
          /* 表格是**唯一一条**其结构模型可能不在任何集合里的管线:`--table-model` 从模型目录之外
   取文件(它自己有 `models/table/manifest.json`),而 `models/serve/manifest.json` 声明的是
   五个 role,里面**没有** `table_structure`。所以表格的就绪判定**不能**像 text/formula 那样
   去 `sets[].files[]` 里按 role 找 —— 那会永久置灰,即使服务端明明在 `/api/models.table` 里
   给出 `routing: true`、`complete: true`、`structure.state: "present"`(E22 修的正是这条:
   页面把"集合里没有这个角色"误当成"模型缺失")。
   表格就绪判定以服务端的 `table` 块为权威(与 `pipelines.table` 同形);`planRowsHtml()` 早就
   按同一口径把集合之外的文件显示成"命令行指定",判定层与展示层必须共用一个来源。 */
           if (queue === "table") {
             const t = state.models && state.models.table;
             if (!t)
               return {
                 ready: false,
                 missing: [],
                 fatal: false,
                 reason: "服务端未返回表格路由状态(/api/models.table)",
               };
             if (t.routing === false)
               return {
                 ready: false,
                 missing: [],
                 fatal: false,
                 reason: t.reason || defaultRouteReason("table"),
               };
             const bad = [];
             if (t.inPlan === false) bad.push("不在本次运行计划里");
             (t.missing || []).forEach((n) => bad.push(String(n)));
             (t.corrupt || []).forEach((n) => bad.push(String(n) + "(损坏)"));
             (t.blocked || []).forEach((n) => bad.push(String(n)));
             if (!t.complete || bad.length)
               return {
                 ready: false,
                 missing: bad,
                 fatal: false,
                 reason: t.reason || null,
               };
             return { ready: true, missing: [], fatal: false, reason: null };
           }
           const need = QUEUE_ROLES[queue] || QUEUE_ROLES.text;
          const missing = [];
          need.forEach((role) => {
            const f = files.find((x) => x.role === role);
            const zh = ROLE_ZH[role] || role;
            if (!f) missing.push(zh);
            else if (f.state === "corrupt") missing.push(zh + "(损坏)");
            else if (f.state !== "present") missing.push(zh);
          });
          if (missing.length)
            return { ready: false, missing, fatal: false, reason: null };
          /* 公式在角色齐备之后还额外要求服务端的**路由可用**:M4 的公式管线需要页面公式检测
  模型(--formula-detector),没有它就只处理调用方显式声明的区域,而 HTTP 请求里没有这种
  区域——那样"成功"的公式任务永远产不出公式区域。表格的那一份判断已经在上面的提前返回里
  做完了(它的模型可以不在集合里);两种情况都把服务端给出的理由原样显示(§9.4:不只靠
  禁用态)。注意 `normalizeModels()` 已经把 `disabled_reason` 改名叫 `reason`,这里必须读
  内部名——E22 之前这里读的是 `route.disabled_reason`(恒 undefined,于是服务端的理由被
  `defaultRouteReason()` 的兜底文案顶掉)。 */
          if (queue === "formula") {
            const route = state.models && state.models.formula;
            if (route && route.routing === false) {
              return {
                ready: false,
                missing: [],
                fatal: false,
                reason: route.reason || defaultRouteReason(queue),
              };
            }
          }
         return { ready: true, missing: [], fatal: false, reason: null };
       }
       /* 服务端没给理由时的兜底文案(正常路径下不会走到:两条路由都由服务端写 disabled_reason)。 */
       function defaultRouteReason(queue) {
         return queue === "table"
           ? "服务端未启用表格路由(--table-model)"
           : "服务端未启用公式路由(--formula-detector)";
       }
       /* 一条路由不可用时的一行理由(缺失角色优先,其次是服务端的路由说明)。 */
       function routeBlockedText(st) {
         if (!st || st.ready) return "";
         const missing = (st.missing || []).join("、");
         if (missing) return `缺少 ${missing}`;
         return st.reason || "模型状态(/api/models 尚未返回)";
       }
       /* 公式路由的旧名(保持既有调用点与文案不变)。 */
       function formulaBlockedText(st) {
         return routeBlockedText(st);
       }
       /* 表格路由的一行理由(E16.2.2)。 */
       function tableBlockedText(st) {
         return routeBlockedText(st);
       }
       /* 四种识别模式 = `queue` × `table` 的全部组合(E16.2.1)。
  每一项声明它需要哪些路由就绪;页面据此**逐个**禁用,而不是"公式/表格一起灰掉"。 */
       const MODES = [
         {
           id: "text",
           name: "文本",
           desc: "queue=text",
           queue: "text",
           table: false,
         },
         {
           id: "formula",
           name: "文本 + 公式",
           desc: "queue=formula",
           queue: "formula",
           table: false,
         },
         {
           id: "text-table",
           name: "文本 + 表格",
           desc: "queue=text&table=1",
           queue: "text",
           table: true,
         },
         {
           id: "formula-table",
           name: "文本 + 公式 + 表格",
           desc: "queue=formula&table=1",
           queue: "formula",
           table: true,
         },
       ];
       function modeById(id) {
         return MODES.find((m) => m.id === id) || MODES[0];
       }
       /* 框粒度的三档(Step 2)。词表必须与服务端 `WordOutputMode::ALL` 逐字一致:`as_str` /
  `from_name` 是线上**唯一**词表(那边的注释写明「入口各写一套取值」必须在测试里当场暴露),
  所以 CLI、serve 查询串、这一页三者只能出现 `off` / `words` / `chars` 三个名字。
  `hint` 是给用户看的实话:字级框来自 CTC 后处理(Step 3 起是 forced alignment 的帧区间铺格,
  帧数不够时退回整行平均字宽并记账),不是字符检测模型给出的像素级边界,因此不能宣称精确字符定位。 */
       const WORDS_MODES = [
         {
           id: "off",
           name: "仅行框",
           desc: "不发 words 参数",
           hint: "不请求逐词/逐字框:响应体与后处理开销都不增加,图上也不能拖选文本。",
         },
         {
           id: "words",
           name: "逐词框",
           desc: "words=words",
           hint: "请求 kind=token 的词级框,文本层用词级 span。切词会丢弃空白字符,因此跨 token 拖选可能少掉空格。",
         },
         {
           id: "chars",
           name: "逐字框",
           desc: "words=chars",
           hint: "请求 kind=char 的字级框,文本层用字符级 span。坐标由 CTC forced alignment 的帧区间铺格得出(比例字体下每字宽度不同),仍不是字符检测模型的像素级边界;对齐装不下时退回整行平均字宽估计。",
         },
       ];
       const WORDS_KEY = "rrocr-words-mode"; /* 与 rrocr-fx-mode 同一存法 */
       function wordsModeById(id) {
         return WORDS_MODES.find((m) => m.id === id) || WORDS_MODES[0];
       }
       /* 查询串:**只有非 off 才发** `&words=`。serve 的 `parse_words` 在参数缺席时按 Off 处理,
  因此不发参数与显式 `words=off` 在线上等价,而流动日志里"页面到底发了什么"仍然一眼可见。 */
       function wordsQuery() {
         return state.words === "off" ? "" : "&words=" + state.words;
       }
       /* 状态初始化:从 localStorage 恢复框粒度(默认 'off',行为与未接入本档时逐字相同) */
       (function initWordsMode() {
         try {
           const m = localStorage.getItem(WORDS_KEY);
           if (m === "off" || m === "words" || m === "chars") state.words = m;
         } catch {}
       })();
       /* 一项模式的可用性:它需要的**每一条**路由都必须就绪。
  返回 {ok, why};`why` 是给用户看的文字(点名缺哪个角色 / 哪条路由没开)。 */
       function modeAvailability(mode) {
         const text = modelsReadyFor("text");
         if (!text.ready)
           return {
             ok: false,
             why: text.fatal
               ? "尚未取得 /api/models 模型状态"
               : `文本队列不可用:${routeBlockedText(text)}`,
           };
         if (mode.queue === "formula") {
           const fx = modelsReadyFor("formula");
           if (!fx.ready)
             return { ok: false, why: `公式队列不可用:${routeBlockedText(fx)}` };
         }
         if (mode.table) {
           const tb = modelsReadyFor("table");
           if (!tb.ready)
             return { ok: false, why: `表格路由不可用:${routeBlockedText(tb)}` };
         }
         return { ok: true, why: "" };
       }

        function toast(msg, type, icon) {
          const el = document.createElement("div");
          el.className = "toast " + (type || "ok");
          el.innerHTML =
            ic(icon || (type === "err" ? "alert" : "check")) +
            `<span>${esc(msg)}</span>`;
          $("toasts").appendChild(el);
          setTimeout(() => {
            el.classList.add("out");
            setTimeout(() => el.remove(), 400);
          }, 3400);
        }
        function dismissToasts() {
          [...$("toasts").children].forEach((t) => {
            t.classList.add("out");
            setTimeout(() => t.remove(), 350);
          });
        }
        function errText(e) {
          if (!e) return "请求失败";
          if (e.aborted) return "已取消上传";
          if (e.status === 0)
            return "无法连接本地服务,请确认 rapidstruct serve 正在运行";
          if (e.code && ERR_TEXT[e.code]) return ERR_TEXT[e.code];
          return "请求失败" + (e.status ? `(HTTP ${e.status})` : "");
        }
        /* 失败文案:人话(§11.1 的错误码文案)+ **机器可读的** HTTP 状态与错误码。
   两者都要有:只说人话无法与 serve 的流动日志(`RAPID_STRUCTURE_SERVE_LOG=flow`)逐条对上,
   只说状态码用户不知道为什么。 */
        function failText(what, e) {
          const ids = [
            e && e.status ? `HTTP ${e.status}` : null,
            (e && e.code) || null,
          ]
            .filter(Boolean)
            .join(" ");
          return (
            (what ? what + ":" : "") + errText(e) + (ids ? ` — ${ids}` : "")
          );
        }
        function toastErr(e) {
          toast(failText("请求失败", e), "err");
        }
        /* 诊断面板的一条留痕:**可见**(toast)之外还有**可查**(此处)的一条。 */
        function diagPush(line) {
          state.diag = [line].concat(state.diag).slice(0, 12);
          renderDiag();
        }

        /* 保存附件(blob 下载,不经过 <a href>,因为 /api/* 均需令牌头) */
        function saveBlob(blob, name) {
          const a = document.createElement("a");
          const u = URL.createObjectURL(blob);
          a.href = u;
          a.download = name;
          document.body.appendChild(a);
          a.click();
          a.remove();
          setTimeout(() => URL.revokeObjectURL(u), 4000);
        }

        /* ================= 页面侧流动日志(详细模式,默认关闭) =================
   报告者的要求:"不打开 devtools 也能看见为什么什么都没渲染"。
   - `?verbose=1` / `?verbose=0` 设定,或按 Ctrl+Alt+L 切换;选择记在 localStorage;
   - 诊断面板出现"最近请求"一节:方法、URL、HTTP 状态、耗时、错误码,
     **失败时附响应体原文**(截断到 4 KB,避免把诊断面板变成内存黑洞);
   - 关闭时不做任何记录以外的事,也不渲染这一节(除非最近一次请求失败——
     那条**永远**显示,因为"什么都没渲染"正是它的用途)。
   服务端对应开关:`RAPID_STRUCTURE_SERVE_LOG=flow`(docs/05 §17)。 */
        const VERBOSE_KEY = "rrocr-verbose";
        function flowVerboseInitial() {
          let q = null;
          try {
            q = new URLSearchParams(location.search).get("verbose");
          } catch {}
          if (q === "1" || q === "true") return true;
          if (q === "0" || q === "false") return false;
          try {
            return localStorage.getItem(VERBOSE_KEY) === "1";
          } catch {
            return false;
          }
        }
        function setFlowVerbose(on, quiet) {
          state.verbose = !!on;
          try {
            localStorage.setItem(VERBOSE_KEY, state.verbose ? "1" : "0");
          } catch {}
          renderDiag();
          if (!quiet)
            toast(
              state.verbose
                ? "详细模式已开启:诊断面板展示最近请求与失败响应体"
                : "详细模式已关闭",
              "ok",
              "info",
            );
        }
        function flowPush(rec) {
          state.flowSeq += 1;
          rec.seq = state.flowSeq;
          state.flow = [rec].concat(state.flow).slice(0, 20);
          if (state.verbose) renderDiag();
          else if (rec.status === 0 || rec.status >= 400)
            renderDiag(); /* 失败永远留痕 */
        }
        /* 供详细模式与失败留痕共用:一次请求的一行(+ 失败时的响应体原文)。 */
        function flowRowHtml(r, withBody) {
          const ok = r.status >= 200 && r.status < 300;
          const cls = r.status === 0 ? "flow-bad" : ok ? "flow-ok" : "flow-bad";
          const when = new Date().toLocaleTimeString();
          const head =
            `<span class="${cls}">${esc(String(r.status || "—"))}</span> ` +
            `<b>${esc(r.method)}</b> ${esc(r.url)} · ${r.ms}ms` +
            (r.note ? ` · ${esc(r.note)}` : "") +
            (r.code ? ` · ${esc(r.code)}` : "");
          const body =
            withBody && r.body
              ? `<pre class="flow-body">${esc(String(r.body).slice(0, 4000))}</pre>`
              : "";
          return `<p class="diag-line">${when} · ${head}</p>${body}`;
        }
        function flowHtml() {
          const failed = state.flow.find(
            (r) => r.status === 0 || r.status >= 400,
          );
          const rows = state.verbose
            ? state.flow.slice(0, 12)
            : failed
              ? [failed]
              : [];
          const toggle =
            `<p class="diag-line"><label><input type="checkbox" id="flowToggle"` +
            (state.verbose ? " checked" : "") +
            `> 详细模式(?verbose=1 或 Ctrl+Alt+L):` +
            `显示最近请求与失败响应体</label></p>`;
          /* 开关**永远**在诊断面板里:一个只有知道 URL 参数的人才能打开的开关不算可用,
     而"为什么什么都没渲染"恰恰是用户在最需要它的时候才会来找的东西。 */
          if (!rows.length) {
            return (
              `<div class="diag-sec">最近请求</div>${toggle}` +
              `<p class="diag-line">${
                state.verbose
                  ? "尚无请求记录。"
                  : "详细模式关闭;最近一次请求失败时会自动在此列出。"
              }</p>`
            );
          }
          return (
            `<div class="diag-sec">最近请求${state.verbose ? " · 详细模式" : " · 最近一次失败"}</div>` +
            toggle +
            rows.map((r) => flowRowHtml(r, true)).join("") +
            `<p class="diag-note">这里的每一行都与服务端的流动日志

     (<code>RAPID_STRUCTURE_SERVE_LOG=flow</code>,行内有请求 id)对应:同一次上传可以先看这里的

     URL/状态/响应体,再按请求 id 到服务端日志里追同一个请求的准入与任务生命周期。</p>`
          );
        }

        /* 详细模式的初值来自 URL 查询串 / localStorage(见 flowVerboseInitial)。
   在启动渲染(renderDiag)之前求值,因此开关状态在首屏就正确。 */
        state.verbose = flowVerboseInitial();

        /* ================= API 层(XHR,统一携带令牌 + 记录流动日志) ================= */
        function recordFlow(method, url, started, status, code, text, note) {
          flowPush({
            method,
            url,
            status,
            code: code || null,
            ms: Date.now() - started,
            note: note || null,
            body: text == null ? null : String(text),
          });
        }
        function xhrSend(method, url, body, opts) {
          opts = opts || {};
          const started = Date.now();
          return new Promise((resolve, reject) => {
            const x = new XMLHttpRequest();
            x.open(method, url, true);
            x.setRequestHeader("X-RapidStructure-Token", TOKEN);
            if (opts.contentType)
              x.setRequestHeader("Content-Type", opts.contentType);
            else if (opts.octet)
              x.setRequestHeader("Content-Type", "application/octet-stream");
            if (opts.onProgress)
              x.upload.onprogress = (ev) => {
                if (ev.lengthComputable) opts.onProgress(ev.loaded / ev.total);
              };
            x.onload = () => {
              let data = null;
              try {
                data = JSON.parse(x.responseText);
              } catch {}
              if (x.status >= 200 && x.status < 300) {
                recordFlow(method, url, started, x.status, null, null);
                resolve(data);
              } else {
                recordFlow(
                  method,
                  url,
                  started,
                  x.status,
                  data && data.code,
                  x.responseText,
                );
                reject({
                  status: x.status,
                  code: data && data.code,
                  body: data,
                  raw: x.responseText,
                });
              }
            };
            x.onerror = () => {
              recordFlow(method, url, started, 0, null, null, "网络错误");
              reject({ status: 0 });
            };
            x.onabort = () => {
              recordFlow(method, url, started, 0, null, null, "已取消");
              reject({ aborted: true });
            };
            x.ontimeout = () => {
              recordFlow(method, url, started, 0, null, null, "超时");
              reject({ status: 0 });
            };
            if (opts.getXhr) opts.getXhr(x);
            x.send(body || null);
          });
        }
        const apiJson = (m, p, b) => xhrSend(m, p, b);
        /* JSON 请求体:Content-Type 必须是 application/json(§4.2 契约),body 为已序列化字符串 */
        const apiSendJson = (m, p, obj) =>
          xhrSend(m, p, JSON.stringify(obj), {
            contentType: "application/json",
          });
        function apiBlob(path) {
          const started = Date.now();
          return new Promise((resolve, reject) => {
            const x = new XMLHttpRequest();
            x.open("GET", path, true);
            x.responseType = "blob";
            x.setRequestHeader("X-RapidStructure-Token", TOKEN);
            x.onload = async () => {
              if (x.status >= 200 && x.status < 300) {
                recordFlow("GET", path, started, x.status, null, null);
                return resolve(x.response);
              }
              let code = null,
                body = null,
                text = null;
              try {
                text = await x.response.text();
                body = JSON.parse(text);
                code = body.code;
              } catch {}
              recordFlow("GET", path, started, x.status, code, text);
              reject({ status: x.status, code, body });
            };
            x.onerror = () => {
              recordFlow("GET", path, started, 0, null, null, "网络错误");
              reject({ status: 0 });
            };
            x.send(null);
          });
        }

        /* ================= 响应映射(**字段冻结**,不做别名兼容) =================
  Rust 侧就是契约(src/api.rs):
    OcrOutput { schema_version, image, stages, regions: Vec<OcrRegion>, timings, engine }
    OcrRegion { source, kind: "text"|"formula", polygon, detection, classification,
                recognition: Option<RecognitionOutcome>, formula: Option<FormulaOutcome> }
    Polygon   { points: [[f32;2]; 4] }   ← 恰好四点,原图像素坐标
    RecognitionOutcome { text: String, score: f32, words }

  因此这里**只接受** regions / kind / polygon.points / recognition.text /
  recognition.score / formula 这几个名字。历史上为"容忍后端改名"而存在的
  区域列表别名、多边形别名(box / coords / poly / 扁平四边形)、文本别名与分数别名
  等回退分支已**全部删除**(详见本段下方 git 历史,本文件里不再保留任何别名标识符):
  字段改名必须在**页面可见地**失败,不允许被前端悄悄吞掉。
  必需字段缺失或结构非法 → 记录 `响应字段缺失: <路径>`,toast + 诊断面板各出现一次。 */
        function pget(o, k) {
          return o && typeof o === "object" ? o[k] : undefined;
        }
        function checkFinite(v, path, errors) {
          if (typeof v !== "number" || !Number.isFinite(v)) {
            errors.push(path);
            return null;
          }
          return v;
        }
        /* RegionSource 是 Rust enum,serde 默认外部标签:Detected{..} → {"Detected":{"detector_index":n}},
   Input → {"Input":null}(单元变体序列化成 null)。因此"调用方声明区域"既能是 "Input" 字符串,
   也能是 {Input:null} 对象 —— 两种都算 Input,其余一律按"检测出的区域"要求多边形。 */
        function isInputRegion(src) {
          if (src === "Input") return true;
          if (src && typeof src === "object" && !Array.isArray(src))
            return Object.prototype.hasOwnProperty.call(src, "Input");
          return false;
        }
        /* 一个四点多边形(`Polygon` = `[[f32;2]; 4]`)的**唯一**判据:恰好四点、每点恰好两个有限数。
   区域框与逐词/逐字框共用这一份判据(`points` 的来源不同、规则完全相同),所以路径由调用方
   传入:报错点名的仍是各自的完整响应路径,而不会把所有多边形错误都说成 `regions[k].polygon`。 */
        function parseQuad(pts, path, errors) {
          if (!Array.isArray(pts) || pts.length !== 4) {
            errors.push(`${path}.points`);
            return null;
          }
          const out = [];
          for (let k = 0; k < 4; k++) {
            const p = pts[k];
            if (!Array.isArray(p) || p.length !== 2) {
              errors.push(`${path}.points[${k}]`);
              return null;
            }
            const x = checkFinite(p[0], `${path}.points[${k}][0]`, errors);
            const y = checkFinite(p[1], `${path}.points[${k}][1]`, errors);
            if (x === null || y === null) return null;
            out.push([x, y]);
          }
          return out;
        }
        function parsePolygon(r, i, errors) {
          if (r == null || r.polygon === undefined || r.polygon === null) {
            /* Polygon 在 Rust 里是 Option:Input 区域允许没有多边形(调用方显式声明的区域就是多边形本身);
       检测出的区域没有多边形则无法叠框,必须如实报错而不是静默丢弃。 */
            if (!isInputRegion(r && r.source))
              errors.push(`regions[${i}].polygon`);
            return null;
          }
          const pts = pget(r.polygon, "points");
          return parseQuad(pts, `regions[${i}].polygon`, errors);
        }
        /* 逐词/逐字框(Step 1 的 `recognition.words`,档位由请求里的 `words=` 决定)。
   这是**可选路径**,与上面的必需字段不同一档,理由就在线上的缺省档是 `off`:
   · `words` **缺席或 null** = 本次请求没开这一档 → 合法,文本层自然不出现。不能报错,
     否则被 SHA-256 钉住的那份 off 档真实响应体(42 区域)会假失败;
   · `words` **在场但形状非法** = 服务端与本页对线上形状的理解已经分叉 → 必须**可见地**
     失败并点名路径,绝不允许“少画几个 span”地静默降级(与必需字段同一判据)。
   只接受 `text` / `score` / `polygon.points` / `kind` 四个名字(`OcrWord`,src/api.rs);
   `kind` 的线上拼写只有 `token` / `char`(`WordKind` 的 `rename_all = "snake_case"`,
   与 `RegionKind`、`TableCellMatch` 同一口径)。 */
        function parseWords(rec, i, errors) {
          const words = pget(rec, "words");
          if (words === undefined || words === null) return null;
          if (!Array.isArray(words)) {
            errors.push(`regions[${i}].recognition.words`);
            return null;
          }
          const out = [];
          for (let k = 0; k < words.length; k++) {
            const w = words[k];
            const path = `regions[${i}].recognition.words[${k}]`;
            if (w === null || typeof w !== "object" || Array.isArray(w)) {
              errors.push(path);
              continue;
            }
            const text = pget(w, "text");
            if (typeof text !== "string") errors.push(`${path}.text`);
            const kind = pget(w, "kind");
            if (kind !== "token" && kind !== "char") errors.push(`${path}.kind`);
            const score = checkFinite(
              pget(w, "score"),
              `${path}.score`,
              errors,
            );
            if (w.polygon === undefined || w.polygon === null) {
              /* word 没有自己的框就没有任何几何可用(拿区域框顶替会说谎:它盖住的是一整行),
           而缺失不是合法档位 —— `OcrWord.polygon` 在 Rust 里不是 Option。 */
              errors.push(`${path}.polygon`);
              continue;
            }
            const quad = parseQuad(
              pget(w.polygon, "points"),
              `${path}.polygon`,
              errors,
            );
            if (typeof text !== "string" || score === null || quad === null)
              continue;
            out.push({ text, score, kind, polygon: quad });
          }
          return out;
        }
        function parseRecognition(r, i, errors) {
          const rec = r && r.recognition;
          if (rec === undefined || rec === null) {
            errors.push(`regions[${i}].recognition`);
            return null;
          }
          const text = pget(rec, "text");
          if (typeof text !== "string")
            errors.push(`regions[${i}].recognition.text`);
          const score = checkFinite(
            pget(rec, "score"),
            `regions[${i}].recognition.score`,
            errors,
          );
          /* 可选档:off 时得到 null(合法缺失),开了才得到数组。它不能影响必需字段已经
           成立的区域是否可渲染,因此只在必需字段都合法时才读。 */
          const words =
            typeof text === "string" && score !== null
              ? parseWords(rec, i, errors)
              : null;
          if (typeof text !== "string" || score === null) return null;
          return { text, score, words };
        }
        function parseFormula(r, i, errors) {
          const f = r && r.formula;
          if (f === undefined || f === null) {
            errors.push(`regions[${i}].formula`);
            return null;
          }
          const latex = pget(f, "latex");
          if (typeof latex !== "string")
            errors.push(`regions[${i}].formula.latex`);
          if (typeof latex !== "string") return null;
          return { latex: latex, model_id: pget(f, "model_id") };
        }
        /* 单元格文本是**模型产物**,必须当不可信数据看。这里的净化是**白名单重建**,
   不是"删掉危险标签":解析 → 只保留白名单元素 → 其余元素降级成文本(保留文字、
   丢掉标签)→ 属性一律丢弃,只留 colspan/rowspan 两个正整数属性 → 由我们自己的
   字符串拼接重新产出(文本一律 esc())。因此输出的每一个字符都是我们写出来的,
   原 HTML 一个字节都不会被拼回去。
   **刻意不用正则**:HTML 的容错解析规则用正则是写不对的,而"正则净化"漏掉任何一个
   变体就是一个可执行注入点(docs/11 §4.3 E16.3.2 明确禁止)。
   `DOMParser` 解析 `text/html` 得到的文档是**惰性**的:脚本不执行、图片不加载。 */
        /* 表格净化白名单:由 assets/table_html_whitelist.json 经
           tools/generate-table-whitelist.mjs 生成,**请勿手改**。下方标记区之间的内容
           每次生成都被整段重写;fingerprint 测试断言它与权威规范、与 Rust 侧
           src/output/table_whitelist.rs 三者一致。 */
        /* <generated:table-whitelist> */
        const TABLE_ALLOWED_TAGS = ["html", "body", "table", "thead", "tbody", "tfoot", "caption", "colgroup", "col", "tr", "th", "td", "br", "sub", "sup", "b", "i", "u", "em", "strong", "span", "p", "div", "ul", "ol", "li", "code", "small"];
        const TABLE_ALLOWED_ATTRS = ["colspan", "rowspan"];
        const TABLE_MIN_SPAN = 1;
        const TABLE_MAX_SPAN = 64;
        /* fingerprint=rapid-structure/table-html-whitelist/v1 sha256=32cf61e192b52ea82bd3d74cd735c90a8edd840bd126f835f29d399b6f77d789 */
        /* </generated:table-whitelist> */
        function sanitizeTableHtml(html) {
          if (typeof html !== "string" || html === "") return "";
          let doc;
          try {
            doc = new DOMParser().parseFromString(html, "text/html");
          } catch (_) {
            return "";
          }
          const out = [];
          const walk = (node) => {
            node.childNodes.forEach((child) => {
              if (child.nodeType === 3) {
                out.push(esc(child.nodeValue || ""));
                return;
              }
              if (child.nodeType !== 1) return; /* 注释、CDATA 一律丢弃 */
              const tag = child.tagName.toLowerCase();
              if (TABLE_ALLOWED_TAGS.indexOf(tag) < 0) {
                walk(child); /* 不在白名单:保留它的文字,丢掉它的标签 */
                return;
              }
              if (tag === "br") {
                out.push("<br>");
                return;
              }
              let attrs = "";
              if (tag === "td" || tag === "th") {
                TABLE_ALLOWED_ATTRS.forEach((name) => {
                  const raw = child.getAttribute(name);
                  if (raw === null) return;
                  const n = Number(raw);
                  /* 只接受 [TABLE_MIN_SPAN, TABLE_MAX_SPAN] 的整数:`colspan="0"`、
                     `colspan="abc"`、`colspan="1e9"`、`colspan="65"` 一律当作没写
                     (HTML 规范里 0 是"跨到最后一列",我们不复刻这个特例——宁可少一个
                     属性,不可多一个面)。下界与引擎侧一致,保证双重净化幂等。 */
                  if (Number.isInteger(n) && n >= TABLE_MIN_SPAN && n <= TABLE_MAX_SPAN)
                    attrs += " " + name + '="' + n + '"';
                });
              }
              out.push("<" + tag + attrs + ">");
              walk(child);
              out.push("</" + tag + ">");
            });
          };
          walk(doc.body);
          return out.join("");
        }
        /* 表格区域(E16.3)。必需字段与文本/公式区域同级:`table.html` 与 `table.cells`
   缺失就是契约破坏,必须**可见地**失败而不是渲染一张空表。其余字段(行数/列数/置信档/
   降级原因/空洞数/被消费行下标)只影响展示,缺失时按"未知"呈现,不报错。 */
        function parseTable(r, i, errors) {
          const t = r && r.table;
          if (t === undefined || t === null) {
            errors.push(`regions[${i}].table`);
            return null;
          }
          const html = pget(t, "html");
          if (typeof html !== "string") errors.push(`regions[${i}].table.html`);
          const cells = pget(t, "cells");
          if (!Array.isArray(cells)) errors.push(`regions[${i}].table.cells`);
          if (typeof html !== "string" || !Array.isArray(cells)) return null;
          const tableHtml = pget(t, "table_html");
          const rows = pget(t, "rows"),
            cols = pget(t, "cols");
          const degradations = pget(t, "degradations");
          const lineIdx = pget(t, "source_line_indices");
          const confidence = pget(t, "confidence");
          return {
            /* 嵌进页面的是**只有 `<table>` 外壳**的变体:外层 `<html><body>` 由页面自己给,
               再套一层会产出嵌套的 body。服务端没给时回落到完整 html。 */
            html:
              typeof tableHtml === "string" && tableHtml !== ""
                ? tableHtml
                : html,
            cells: cells,
            rows: Number.isInteger(rows) ? rows : null,
            cols: Number.isInteger(cols) ? cols : null,
            confidence: confidence === "high" || confidence === "low" ? confidence : null,
            degradations: Array.isArray(degradations) ? degradations : [],
            holes: Number.isInteger(pget(t, "holes")) ? pget(t, "holes") : null,
            sourceLineIndices: Array.isArray(lineIdx)
              ? lineIdx.filter((n) => Number.isInteger(n))
              : [],
            modelId: pget(t, "model_id") || null,
            /* Markdown 呈现(E16.3.7):复制全文时按阅读顺序插进结果里。
               它是**有损**表示(span 表达不出来),所以只用于纯文本出口,不用它渲染页面。 */
            markdown: typeof pget(t, "markdown") === "string" ? pget(t, "markdown") : "",
          };
        }
        /* 降级原因的人话(与 TableDegradation 的 serde 形状一致:{kind, holes?})。 */
        function degradationText(d) {
          if (!d || typeof d !== "object") return "未知降级";
          if (d.kind === "grid_holes")
            return Number.isInteger(d.holes)
              ? `网格空洞 ${d.holes} 格`
              : "网格空洞";
          if (d.kind === "truncated") return "结构被截断(未见到结束符就用尽步数)";
          return `未知降级(${String(d.kind)})`;
        }
        function normalizeResult(r) {
          const errors = [];
          if (r === null || typeof r !== "object" || Array.isArray(r)) {
            contractFail(["(响应体不是 JSON 对象)"]);
            return null;
          }
          if (!Array.isArray(r.regions)) {
            contractFail(["regions"]);
            return null;
          }
          const regions = r.regions
            .map((x, i) => {
              if (x === null || typeof x !== "object") {
                errors.push(`regions[${i}]`);
                return null;
              }
              const kind = pget(x, "kind");
              if (kind !== "text" && kind !== "formula" && kind !== "table")
                errors.push(`regions[${i}].kind`);
              const polygon = parsePolygon(x, i, errors);
              let text = "",
                conf = null,
                words = null,
                formula = null,
                table = null;
              if (kind === "formula") {
                /* 公式区域**不携带** CTC 文本结果(RegionKind::Formula 语义,src/api.rs:460),
         文本字段为空是正确行为,不是缺字段;真正必需的是 formula.latex。 */
                formula = parseFormula(x, i, errors);
                if (formula) text = formula.latex;
              } else if (kind === "table") {
                /* 表格区域同样**不携带** CTC 文本结果(RegionKind::Table,src/api.rs:497):
         单元格文本在 table.cells[].text 里,不是 recognition.text。 */
                table = parseTable(x, i, errors);
              } else {
                const rec = parseRecognition(x, i, errors);
                if (rec) {
                  text = rec.text;
                  conf = rec.score;
                  words = rec.words;
                }
              }
              return kind === "text" || kind === "formula" || kind === "table"
                ? { text, conf, words, polygon, kind, formula, table, order: i + 1 }
                : null;
            })
            .filter(Boolean);
          if (errors.length) {
            contractFail(errors);
            return null;
          }
          /* 诊断面板使用的其余字段(source / detection / classification 仅按需读取,
     缺字段不影响结果渲染,因此不参与上面的必需字段校验) */
          return {
            regions,
            plain:
              typeof r.plain_text === "string"
                ? r.plain_text
                : regions
                    .map((x) => x.text)
                    .filter((s) => s !== "")
                    .join("\n"),
            timings:
              r.timings && typeof r.timings === "object" ? r.timings : {},
            /* 时间账本:服务端由库的 TimingLedger 计算(命名分量 + 口径残差 + 库自己写的解释文案),
       前端只展示、不重新测量、也不自己解释残差(M3 / §10.6)。 */
            ledger:
              r.timing_ledger && typeof r.timing_ledger === "object"
                ? r.timing_ledger
                : null,
            raw: r,
          };
        }
        /* 契约失败:**可见**(toast)+ **可查**(诊断面板),并明确点名出错的响应路径 */
        function contractFail(paths) {
          const list = paths.slice(0, 4);
          const more =
            paths.length > list.length ? ` 等 ${paths.length} 处` : "";
          state.result = null;
          /* 逆序压栈,使最早出错的那条排在最上面。 */
          list
            .map((p) => `响应字段缺失: ${p}`)
            .reverse()
            .forEach(diagPush);
          renderDiag();
          toast(
            `响应字段缺失: ${list.join("、")}${more} — 前端按冻结契约解析 /api/jobs/{id}/result,不做别名兼容`,
            "err",
            "alert",
          );
        }
        function normalizeStatus(s) {
          const eng = s.engine || {},
            prov = s.provider || {};
          return {
            state: eng.state || s.state || "unknown",
            requested: firstText(
              prov.requested,
              s.requested_provider,
            ) /* null = 未知 */,
            selected_ep: firstText(
              prov.selected_ep,
              s.selected_ep,
            ) /* null = 未知 */,
            fallback: firstBool(
              prov.fallback_to_cpu,
              s.fallback_to_cpu,
            ) /* null = 未知 ≠ false */,
            ort: (s.ort && s.ort.version) || s.ort_version || "—",
            fingerprint:
              (s.ort && s.ort.fingerprint) || s.ort_fingerprint || null,
            memory:
              (s.memory && s.memory.peak_working_set_bytes) != null
                ? s.memory.peak_working_set_bytes
                : s.peak_memory_bytes,
            memorySource: (s.memory && s.memory.source) || null,
            queues: s.queues || null,
            limits:
              s.limits ||
              null /* §9.1 请求体上限:handleFile 的早期校验依赖该字段 */,
          };
        }
        function normalizeModels(m) {
          /* 三条管线各自一份结论(E16.2)。顶层 `complete/missing/corrupt/blocked` 是**文本
      管线**作用域(引擎要加载的就是那些文件);公式与表格缺失都不得让普通 OCR 变成 409。
      表格块(`m.table`)由服务端给出,与公式块同形;服务端没返回时留 `null`(= 未知),
      **不**当成 `routing: false` —— 未知与"明确关闭"必须区分(§9.4)。 */
          const route = (b) =>
            b
              ? {
                  complete: !!b.complete,
                  missing: b.missing || [],
                  /* corrupt/blocked 与 missing 一样是"不可用",但来源不同(校验失败 / 被启动期
      参数挡住),文案要分开说,所以三个清单都带出来(E22)。 */
                  corrupt: b.corrupt || [],
                  blocked: b.blocked || [],
                  routing: b.routing !== false,
                  reason: b.disabled_reason || null,
                  inPlan: !!b.in_plan,
                }
              : null;
          return {
            source: m.source || "default_table",
            downloadsAllowed: !!m.downloads_allowed,
            formula: m.formula
              ? Object.assign(route(m.formula), {
                  detector: m.formula.detector || null,
                })
              : null,
            table: m.table
              ? Object.assign(route(m.table), {
                  structure: m.table.structure || null,
                })
              : null,
            /* 逐管线的文件清单与**模型计划**(E16.1)。`files` 是名字数组,`plan` 是
     带 role/state/声明摘要的对象数组 —— 页面只用它显示"哪个文件被哪条管线使用",
     **绝不自己拼路径**(服务端刻意不返回绝对路径)。 */
            pipelines: m.pipelines || null,
            sets: (m.sets || []).map((s) => ({
              id: s.id,
              complete: !!s.complete,
              bytes: s.download_bytes_total,
              family: s.family || null,
              version: s.version || null,
              files: (s.files || []).map((f) => ({
                name: f.name,
                role: f.role || "",
                state: f.state || "missing",
                size: f.size_bytes,
                url: f.source_url || "",
                sha: f.sha256 || "",
              })),
            })),
          };
        }

        /* ================= 主题(View Transitions 圆形扩散) ================= */
        /* 初始主题:localStorage → 系统偏好;切换逻辑紧随其后,同属本文件唯一的 IIFE(此处不闭合) */
        const saved = localStorage.getItem("rrocr-theme");
        const t =
          saved ||
          (matchMedia("(prefers-color-scheme: dark)").matches
            ? "dark"
            : "light");
        document.documentElement.dataset.theme = t;
        $("themeBtn").addEventListener("click", (e) => {
          const next =
            document.documentElement.dataset.theme === "light"
              ? "dark"
              : "light";
          const apply = () => {
            document.documentElement.dataset.theme = next;
            localStorage.setItem("rrocr-theme", next);
          };
          const redraw = () => {
            if (state.result) drawOverlays();
          };
          if (!document.startViewTransition) {
            apply();
            redraw();
            return;
          }
          const x = e.clientX || innerWidth - 40,
            y = e.clientY || 40;
          const r = Math.hypot(
            Math.max(x, innerWidth - x),
            Math.max(y, innerHeight - y),
          );
          const vt = document.startViewTransition(apply);
          vt.ready.then(() => {
            document.documentElement.animate(
              {
                clipPath: [
                  `circle(0px at ${x}px ${y}px)`,
                  `circle(${r}px at ${x}px ${y}px)`,
                ],
              },
              {
                duration: 600,
                easing: "cubic-bezier(.4,0,.2,1)",
                pseudoElement: "::view-transition-new(root)",
              },
            );
          });
          vt.finished.then(redraw);
        });

        /* ================= 图像载入(createObjectURL + revoke,§9.3) ================= */
        const imgEl = $("view"),
          canvas = $("overlay"),
          stage = $("stage"),
          stageWrap = $("stageWrap"),
          drop = $("drop");
        const ctx = canvas.getContext("2d");

        function setImage(file) {
          if (!file || state.uploading) return false;
          if (jobActive()) {
            toast("当前任务进行中,请等待完成后再更换图像", "err", "info");
            return false;
          }
          if (state.image)
            URL.revokeObjectURL(state.image.url); /* 替换即释放 */
          clearJob();
          clearResult(false);
          const url = URL.createObjectURL(file);
          state.image = { file, url, w: 0, h: 0 };
          imgEl.onerror = () => {
            /* 文件头合法但无法解码 */
            if (!state.image) return;
            toast("无法解码该图像,请更换文件", "err");
            clearImage();
          };
          imgEl.onload = () => {
            state.image.w = imgEl.naturalWidth;
            state.image.h = imgEl.naturalHeight;
            state.view = {
              mode: "fit",
              scale: 1,
            }; /* 新图先适应窗口(与既有行为一致) */
            applyZoom(); /* 图像与叠加画布同时定尺寸并重绘 */
            renderMeta();
            renderButton();
          };
          imgEl.src = url;
          $("emptyState").hidden = true;
          $("stageWrap").hidden = false;
          $("clearBtn").hidden = false;
          $("zoomGroup").hidden = false;
          $("fileMeta").hidden = false;
          drop.classList.add("has-image");
          return true;
        }
        /* ================= 任务生命周期:beginJob / endJob 是**仅有的**两个所有者 =================
   报告者看到的症状(上传后左栏一直转、右栏永远没有结果)的根因就在这里:
   旧实现的 submitImage 先 `state.job = {...}`,紧接着调用 `clearResult(false)`,而
   clearResult 里有一句 `state.job = null` —— 刚被 202 接受的任务在下一行就被上一次的
   清场吃掉了。于是 renderJob() 看到"没有任务"(隐藏任务行)、scanOn() 点亮扫描动画、
   startPolling() 的 tick() 在 `if(!j) return;` 直接返回:**页面一次 GET /api/jobs/{id}
   都不会发出**,扫描动画因此永不停止,右栏永远是空状态。

   设计上的修法不是调换两行的顺序(那只是掩盖"谁负责清场"的模糊),而是把两件事拆开:
   - `clearResult()` 只重置**上一次的识别结果**;
   - `clearJob()` 只重置**任务状态行**;
   - `beginJob()` 是唯一的入队入口,`endJob()` 是唯一的终结入口,两者一起管住
     `state.job` 与扫描动画。任何终结路径(成功、失败、取消、淘汰、契约失败、
     HTTP 错误)都必须走 `endJob()`,因此"某条分支忘了关动画"不再可能出现。 */
        function clearJob() {
          state.job = null;
          scanOff();
          renderJob();
          renderButton();
        }
        function beginJob(submitted, queueFallback, poll, mode) {
          state.job = {
            id: submitted.job_id,
            kind: submitted.kind || "text",
            /* 队列以服务端返回为准(公式任务进公式队列);缺失时按本次请求的队列推断,仅用于展示 */
            queue: submitted.queue || queueFallback || "text",
            /* 本次请求选的识别模式(E16.2.5)。202 的响应体里**没有**表格标志
      (`{job_id,queue,position,state}`),所以它只能由提交方传进来;不传时按
      队列推断(= 旧行为),绝不给一个"看起来像真的"默认值。 */
            mode: mode || null,
            state: submitted.state || "queued",
            position: submitted.position,
            queued_ms: 0,
            elapsed_ms: 0,
          };
          pollFails = 0;
          renderJob();
          renderButton();
          scanOn();
          /* `poll === false` 只用于离线预览:它自带进度,不轮询真实端点。 */
          if (poll !== false) startPolling();
        }
        function endJob(message, type, icon) {
          scanOff();
          state.job = null;
          renderJob();
          renderButton();
          if (message) toast(message, type || "err", icon);
        }
        function clearResult(resetList) {
          state.result = null;
          state.selected = -1;
          clearTextLayer(); /* 旧结果的文本层不能留在新图上:坐标与文本都属于上一张图 */
          drawOverlays();
          ["copyAllBtn", "expJson", "expMd", "expHtml"].forEach(
            (id) => ($(id).disabled = true),
          );
          $("annotatedBtn").hidden = true;
          if (resetList !== false) {
            renderRegions();
            renderDiag();
          }
        }
        function clearImage() {
          if (state.uploading || jobActive()) return;
          if (state.image) URL.revokeObjectURL(state.image.url);
          state.image = null;
          imgEl.onerror = null;
          imgEl.removeAttribute("src");
          clearJob();
          clearResult();
          stage.style.width =
            ""; /* 撤销缩放尺寸(CSSOM,标记里无 style 属性) */
          stage.style.height = "";
          state.view = { mode: "fit", scale: 1 };
          $("emptyState").hidden = false;
          $("stageWrap").hidden = true;
          $("clearBtn").hidden = true;
          $("zoomGroup").hidden = true;
          $("fileMeta").hidden = true;
          drop.classList.remove("has-image");
          renderButton();
        }
        addEventListener("beforeunload", () => {
          /* 离开页面释放 blob */
          if (state.image) URL.revokeObjectURL(state.image.url);
        });

        /* ================= 叠加画布(devicePixelRatio + 原图坐标线性换算,§9.3) ================= */
        /* 画布与 stage 同尺寸(stage = 图像显示框),缩放放大后画布面积可能远超浏览器上限,
   因此按面积上限压低采样率:叠框坐标系仍是 CSS 像素,缩放再大也与图像对齐,只是分辨率下降。 */
        const CANVAS_MAX_PX = 24e6;
        function layoutCanvas() {
          const w = stage.clientWidth,
            h = stage.clientHeight;
          if (!w || !h) return;
          const q = Math.max(
            0.1,
            Math.min(devicePixelRatio || 1, Math.sqrt(CANVAS_MAX_PX / (w * h))),
          );
          canvas.width = Math.max(1, Math.round(w * q)); /* 像素尺寸 × 采样率 */
          canvas.height = Math.max(1, Math.round(h * q));
          canvas.style.width = w + "px"; /* CSSOM 赋值,不受 CSP 限制 */
          canvas.style.height = h + "px";
          ctx.setTransform(canvas.width / w, 0, 0, canvas.height / h, 0, 0);
          drawOverlays();
          /* 文本层与叠框共用这一个布局时机:两者都只依赖 stage 的显示尺寸,分开排就会有一帧错位。 */
          layoutTextLayer();
        }
        function fgRGBA(a) {
          const c = getComputedStyle(document.documentElement)
            .getPropertyValue("--fg")
            .trim();
          const n = parseInt(c.slice(1), 16);
          return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${a})`;
        }
        function drawOverlays() {
          const w = stage.clientWidth,
            h = stage.clientHeight;
          if (!w) return;
          ctx.clearRect(0, 0, w, h);
          if (!state.result || !state.image || !state.image.w) return;
          const sx = w / state.image.w,
            sy = h / state.image.h; /* 两轴分别换算:与 img 显示框严格一致 */
          state.result.regions.forEach((r, i) => {
            if (!r.polygon) return;
            const pts = r.polygon.map((p) => [p[0] * sx, p[1] * sy]);
            ctx.beginPath();
            ctx.moveTo(pts[0][0], pts[0][1]);
            for (let k = 1; k < pts.length; k++)
              ctx.lineTo(pts[k][0], pts[k][1]);
            ctx.closePath();
            if (i === state.selected) {
              ctx.fillStyle = fgRGBA(0.1);
              ctx.fill();
              ctx.setLineDash([]);
              ctx.lineWidth = 2;
              ctx.strokeStyle = fgRGBA(0.95);
            } else {
              ctx.setLineDash(
                r.kind === "formula" ? [5, 4] : [],
              ); /* 公式虚线框(第二视觉线索) */
              ctx.lineWidth = 1;
              ctx.strokeStyle = fgRGBA(0.45);
            }
            ctx.stroke();
            ctx.setLineDash([]);
            if (i === state.selected) {
              /* 选中:角点方块(不只靠颜色) */
              ctx.fillStyle = fgRGBA(0.95);
              pts.forEach((p) => ctx.fillRect(p[0] - 2.5, p[1] - 2.5, 5, 5));
            }
          });
        }
        /* stage 变化(缩放 / 换图)→ 重算画布;容器变化(窗口 resize)→ 适应模式重新适配、自定义缩放保持倍数 */
        new ResizeObserver(() => layoutCanvas()).observe(stage);
        new ResizeObserver(() => {
          if (state.image) applyZoom();
          else layoutCanvas();
        }).observe(stageWrap);

        /* 点击画布 → 命中区域 → 双向高亮 */
        canvas.addEventListener("click", (e) => {
          if (!state.result || !state.image) return;
          const r = canvas.getBoundingClientRect();
          const px = ((e.clientX - r.left) / r.width) * state.image.w;
          const py = ((e.clientY - r.top) / r.height) * state.image.h;
          let hit = -1;
          state.result.regions.forEach((g, i) => {
            if (hit >= 0 || !g.polygon) return;
            if (pointInPoly(px, py, g.polygon)) hit = i;
          });
          selectRegion(hit); /* -1 = 取消选中 */
        });
        function pointInPoly(x, y, p) {
          let inside = false;
          for (let i = 0, j = p.length - 1; i < p.length; j = i++) {
            if (
              p[i][1] > y !== p[j][1] > y &&
              x <
                ((p[j][0] - p[i][0]) * (y - p[i][1])) / (p[j][1] - p[i][1]) +
                  p[i][0]
            )
              inside = !inside;
          }
          return inside;
        }
        function selectRegion(i) {
          state.selected = i;
          const items = [...document.querySelectorAll(".region-item")];
          items.forEach((el, idx) => {
            el.classList.toggle("sel", idx === i);
            el.setAttribute("aria-pressed", idx === i ? "true" : "false");
          });
          drawOverlays();
          if (i >= 0 && items[i])
            items[i].scrollIntoView({ block: "nearest", behavior: "smooth" });
        }

        /* ================= 透明文本层(Step 2:DOM 层负责选中与复制)=================
   职责划分:库只提供**文本 + 几何**,浏览器里的选择/复制属于宿主呈现层——所以这一层只存在于
   自带的网页 Demo,crate 本身不依赖 DOM/剪贴板。Canvas 继续画叠框与高亮(它无法被选中),
   DOM 文本层只负责“拖得动、复制得出来”,两者共用同一套坐标换算,所以不会互相错位。

   几何口径必须与 `drawOverlays()` **逐字相同**:`sx = stage.clientWidth / 原图宽`、
   `sy = stage.clientHeight / 原图高`(两轴分别换算,与 `<img>` 的显示框严格一致)。
   在此基础上,每个 span 摆到自己的 word 四边形上:
   · 第一列 = p0→p1(字形的右方向,与产出方 `word_boxes.rs` 把这条边当作 crop 宽度的约定同一);
   · 第二列 = p0→p3(字形的下方向);平移量 = p0。
   **这是仿射,不是轴对齐外接矩形**:倾斜的行会被剪切着跟随叠框,而不是被扶正成大盒子。
   局限也要说清:竖排文本按**直立字形**处理——产出方的 `order_points` 已按 y、x 重排过角点,
   角点身份(哪一个是裁剪图的左上)在线上已经没了,因此无法从四边形还原 90° 旋转。这是
   CTC 后处理框本身的局限,不是这里新增的近似(字符定位精度属于 Step 4 的基准)。 */
        const textLayer = $("textLayer");
        const TL_PROBE_EM = 100; /* 探测字号(px):推进宽按比值换算,缩放时不必重新测量 */
        let tlProbe = null;
        const tlAdvance = new Map(); /* text -> 推进宽 ÷ 字号 */
        /* 每项记住 **原图坐标**的四边形:显示尺寸变了只重算 transform,不重建 DOM、不重新测量。 */
        let tlItems = [];

        function tlProbeEl() {
          if (!tlProbe) {
            tlProbe = document.createElement("span");
            tlProbe.className = "tl-probe";
            tlProbe.setAttribute("aria-hidden", "true");
            stage.appendChild(tlProbe); /* 绝对定位 + visibility:hidden → 不参与布局 */
          }
          return tlProbe;
        }
        /* 一次测量、长期复用:推进宽 ÷ 字号是字体的线性属性,因此任何缩放都只用比值。
           `white-space:pre` 下纯空白的 textContent 仍然有宽度(本层不依赖它:真实切词丢空白)。 */
        function tlAdvanceRatio(text) {
          const hit = tlAdvance.get(text);
          if (hit !== undefined) return hit;
          const p = tlProbeEl();
          p.textContent = text;
          const w = p.getBoundingClientRect().width;
          const ratio = w > 0 ? w / TL_PROBE_EM : 0;
          tlAdvance.set(text, ratio);
          return ratio;
        }
        function clearTextLayer() {
          tlItems = [];
          textLayer.textContent = "";
          textLayer.hidden = true;
        }
        /* 结果到达后建一次 DOM。元素全部用 createElement + textContent 生成:
           识别文本是**模型产物**,绝不进 innerHTML(与表格 HTML 同一口径,门禁 G8)。 */
        function renderTextLayer() {
          clearTextLayer();
          const res = state.result;
          if (!res || !state.image || !state.image.w || !state.image.h) return;
          const frag = document.createDocumentFragment();
          res.regions.forEach((r, ri) => {
            if (
              !r ||
              r.kind !== "text" ||
              !Array.isArray(r.words) ||
              r.words.length === 0
            )
              return;
            const line = document.createElement("div");
            line.className = "tl-line";
            line.setAttribute("data-ri", String(ri));
            let made = 0;
            r.words.forEach((w) => {
              if (
                !w ||
                typeof w.text !== "string" ||
                w.text === "" ||
                !Array.isArray(w.polygon) ||
                w.polygon.length !== 4
              )
                return;
              const span = document.createElement("span");
              span.className = "tl-word";
              span.setAttribute("data-ri", String(ri));
              /* 档位以**载荷**为准(`kind` 是服务端给的 token/char),不靠页面自己的选择推断:
           两边不一致时用户看到的应该是真实形状,而不是你以为的那一档。 */
              span.setAttribute("data-kind", w.kind === "char" ? "char" : "token");
              span.textContent = w.text;
              line.appendChild(span);
              tlItems.push({ span, quad: w.polygon });
              made += 1;
            });
            if (made) frag.appendChild(line);
          });
          /* 没有任何 word 框(off 档 / 本图无文本区域)→ 层保持隐藏,页面行为与改动前逐字相同。 */
          if (tlItems.length === 0) return;
          textLayer.appendChild(frag);
          textLayer.hidden = false;
          layoutTextLayer();
        }
        /* 只重算几何(`layoutCanvas()` 与叠框同一时机被叫到):缩放/换图/窗口变化都走这里。 */
        function layoutTextLayer() {
          if (textLayer.hidden || !state.image || !state.image.w || !state.image.h)
            return;
          const w = stage.clientWidth,
            h = stage.clientHeight;
          if (!w || !h) return;
          const sx = w / state.image.w,
            sy = h / state.image.h;
          for (const item of tlItems) {
            const q = item.quad;
            const x0 = q[0][0] * sx,
              y0 = q[0][1] * sy;
            const ux = q[1][0] * sx - x0,
              uy = q[1][1] * sy - y0; /* 字形右方向(p0→p1) */
            const dx = q[3][0] * sx - x0,
              dy = q[3][1] * sy - y0; /* 字形下方向(p0→p3) */
            const boxH = Math.hypot(dx, dy);
            const boxW = tlAdvanceRatio(item.span.textContent) * boxH;
            const s = item.span.style;
            /* 低于半个像素的盒子无法承载可选中的字形(小字号 + 适应窗口的组合下会出现):
           直接不显示,而不是把一个字符压成看不见的斑点——那会让选区多出一个无宽度的空项。 */
            if (!(boxH > 0.5) || !(boxW > 0.5)) {
              s.display = "none";
              continue;
            }
            s.display = "";
            s.fontSize = boxH.toFixed(2) + "px"; /* CSSOM:内联 style 属性会被 CSP 拒绝 */
            s.transform =
              "matrix(" +
              [ux / boxW, uy / boxW, dx / boxH, dy / boxH, x0, y0]
                .map((v) => v.toFixed(5))
                .join(",") +
              ")";
          }
        }
        /* span 点击 → 反向定位到区域(与叠框点击、右栏列表点击同一个入口 selectRegion)。
           拖选结束时浏览器也会派发一次 click,所以**有选区时不抢选中态**:用户正在选文字,
           不该顺手被改成“选中这个区域”(那会同时触发列表项 scrollIntoView,选区看起来在漂)。 */
        textLayer.addEventListener("click", (e) => {
          const el = e.target.closest("[data-ri]");
          if (!el) return;
          const sel = document.getSelection && document.getSelection();
          if (sel && !sel.isCollapsed) return;
          const i = Number(el.getAttribute("data-ri"));
          if (!Number.isInteger(i) || i < 0) return;
          selectRegion(i);
        });
        /* 请求了逐词/逐字框但载荷里没有 → **必须可见**。静默“少一层文字”会让人以为功能坏了
           却又说不清哪一段。档位是在提交那一刻固定的,所以这里能确定地知道本次开了哪一档。
           它**不是**契约校验的一部分(`words` 是可选路径,off 档缺失完全合法),因此走 toast +
           诊断面板,而不是 contractFail 那条“响应字段缺失”的口径。 */
        function checkWordsDelivery() {
          if (DEMO || state.words === "off" || !state.result) return;
          const got = state.result.regions.some(
            (r) => r && r.kind === "text" && Array.isArray(r.words) && r.words.length,
          );
          if (got) return;
          const msg =
            "请求了 words=" +
            state.words +
            ",但响应里没有任何 recognition.words(本图没有文本区域,或识别阶段未产出词框)";
          diagPush(msg);
          toast(msg, "err", "alert");
        }

        /* ================= 输入事件(拖放 / 选择 / 粘贴 / 键盘,§9.4) ================= */
        let dragDepth = 0;
        drop.addEventListener("dragenter", (e) => {
          e.preventDefault();
          dragDepth++;
          drop.classList.add("dragging");
        });
        drop.addEventListener("dragover", (e) => e.preventDefault());
        drop.addEventListener("dragleave", () => {
          if (--dragDepth <= 0) {
            dragDepth = 0;
            drop.classList.remove("dragging");
          }
        });
        drop.addEventListener("drop", (e) => {
          e.preventDefault();
          dragDepth = 0;
          drop.classList.remove("dragging");
          const f = e.dataTransfer.files && e.dataTransfer.files[0];
          if (f) handleFile(f);
        });
        document.addEventListener("dragover", (e) => e.preventDefault());
        document.addEventListener("drop", (e) => e.preventDefault());
        drop.addEventListener("click", () => {
          if (!state.uploading) $("fileInput").click();
        });
        drop.addEventListener("keydown", (e) => {
          if (e.key === "Enter" || e.key === " ") {
            e.preventDefault();
            $("fileInput").click();
          }
        });
        $("fileInput").addEventListener("change", (e) => {
          if (e.target.files[0]) handleFile(e.target.files[0]);
          e.target.value = "";
        });
        document.addEventListener("paste", (e) => {
          /* Ctrl+V 粘贴截图(demo2 的 paste 路径) */
          if (isTextField(e.target)) return; /* 文本框内粘贴不拦截 */
          const items = e.clipboardData ? [...e.clipboardData.items] : [];
          const item = items.find((i) => i.type.startsWith("image/"));
          if (!item)
            return toast(
              "剪贴板中没有图像",
              "err",
              "info",
            ); /* 明确提示,不静默失败 */
          intakePaste(item.getAsFile(), "key");
        });
        /* 从剪贴板取图按钮(navigator.clipboard.read;127.0.0.1 属安全上下文,需页面聚焦) */
        $("pasteBtn").addEventListener("click", async () => {
          if (!navigator.clipboard || !navigator.clipboard.read)
            return toast(
              "当前浏览器不支持读取剪贴板,请改用 Ctrl+V 粘贴",
              "err",
              "info",
            );
          try {
            for (const it of await navigator.clipboard.read()) {
              const type = it.types.find((t) => t.startsWith("image/"));
              if (type) return intakePaste(await it.getType(type), "button");
            }
            toast(
              "剪贴板中没有图像",
              "err",
              "info",
            ); /* 剪贴板为空 / 只有文本 */
          } catch {
            toast(
              "无法读取剪贴板(需本页聚焦且已授权),请改用 Ctrl+V 粘贴",
              "err",
              "info",
            );
          }
        });
        /* 粘贴入口:与拖放 / 文件选择共用 handleFile → 校验、预览、上传进度、取消上传行为完全一致 */
        function intakePaste(f, from) {
          if (state.uploading)
            return toast("上传进行中,请等待完成后再粘贴", "err", "info");
          if (handleFile(f))
            toast(
              from === "button" ? "已从剪贴板载入图像" : "已粘贴剪贴板图像",
              "ok",
              "image",
            );
        }
        $("clearBtn").addEventListener("click", clearImage);
        /* Esc:关闭高亮与提示(§9.4);+ / - / 0 缩放(文本框内、带修饰键时不劫持,保留浏览器快捷键) */
        document.addEventListener("keydown", (e) => {
          if (e.key === "Escape") {
            selectRegion(-1);
            dismissToasts();
            return;
          }
          /* 详细模式开关:Ctrl+Alt+L(等价的 URL 形式是 ?verbose=1 / ?verbose=0)。
     放在最前面,因为它与是否有图像、是否在文本框里都无关。 */
          if (e.ctrlKey && e.altKey && (e.key === "l" || e.key === "L")) {
            e.preventDefault();
            setFlowVerbose(!state.verbose);
            return;
          }
          if (
            !state.image ||
            e.ctrlKey ||
            e.metaKey ||
            e.altKey ||
            isTextField(e.target)
          )
            return;
          if (e.key === "+" || e.key === "=") {
            e.preventDefault();
            zoomBy(ZOOM_STEP);
          } else if (e.key === "-" || e.key === "_") {
            e.preventDefault();
            zoomBy(1 / ZOOM_STEP);
          } else if (e.key === "0") {
            e.preventDefault();
            setZoom(1, "custom");
          }
        });

        /* 统一的文件入口:拖放 / 文件选择 / 粘贴都走这里;返回是否真的载入成功(供粘贴提示) */
        function handleFile(f) {
          if (!f) return false;
          if (!f.type.startsWith("image/")) {
            toast("仅支持图像文件", "err");
            return false;
          }
          const max =
            state.status &&
            state.status.limits &&
            state.status.limits.max_body_bytes;
          if (max && f.size > max) {
            toast(
              `图像 ${fmtBytes(f.size)} 超出请求体上限 ${fmtBytes(max)}`,
              "err",
            );
            return false;
          }
          return setImage(f);
        }

        /* ================= 缩放 / 适应窗口(demo2 的 zoomOut/zoomLbl/zoomIn/zoomFit,§9.3) ================= */
        /* 显示尺寸只有一个来源:state.view.mode/scale。stage 的像素尺寸 = 原图尺寸 × scale,
   img 与 canvas 都以 100% 填满 stage → 图像与叠加层永远一起缩放、严格对齐;
   尺寸经 CSSOM(element.style.width/height)写入,标记里没有任何 style 属性(nonce CSP)。 */
        const ZOOM_MAX = 4; /* 相对原图的最大放大倍数 */
        const ZOOM_STEP = 1.25; /* 与 demo2 相同:放大 ×1.25,缩小 ÷1.25 */
        function fitScale() {
          const i = state.image;
          if (!i || !i.w || !i.h) return 1;
          const cw = stageWrap.clientWidth,
            ch = stageWrap.clientHeight;
          if (!cw || !ch)
            return (
              state.view.scale || 1
            ); /* 容器尚未布局:保持现值,不写入垃圾缩放 */
          return Math.min(
            1,
            cw / i.w,
            ch / i.h,
          ); /* 与既有「适应窗口」一致:不放大超过原始尺寸 */
        }
        function applyZoom() {
          const i = state.image;
          if (!i || !i.w || !i.h) return;
          if (state.view.mode === "fit") state.view.scale = fitScale();
          stage.style.width =
            Math.max(1, Math.round(i.w * state.view.scale)) + "px";
          stage.style.height =
            Math.max(1, Math.round(i.h * state.view.scale)) + "px";
          updateZoomUI();
          layoutCanvas(); /* 画布随 stage 同步尺寸并重绘叠框 */
        }
        function setZoom(scale, mode) {
          const lo =
            fitScale() / 4; /* 下限:适应比例的 1/4,避免超大图被压到不可读 */
          state.view = {
            mode: mode || "custom",
            scale: Math.min(Math.max(scale, lo), ZOOM_MAX),
          };
          applyZoom();
        }
        function zoomBy(f) {
          setZoom(state.view.scale * f);
        }
        function updateZoomUI() {
          const i = state.image;
          if (!i) return;
          const pct = Math.round(state.view.scale * 100);
          const lbl = $("zoomLbl");
          lbl.textContent =
            (state.view.mode === "fit" ? "适应 · " : "") + pct + "%";
          lbl.title =
            `显示 ${Math.round(i.w * state.view.scale)}×${Math.round(i.h * state.view.scale)} px · ` +
            `原图 ${i.w}×${i.h} px`;
          $("zoomFit").setAttribute(
            "aria-pressed",
            state.view.mode === "fit" ? "true" : "false",
          );
          $("zoomActual").setAttribute(
            "aria-pressed",
            state.view.mode === "custom" && pct === 100 ? "true" : "false",
          );
        }
        $("zoomIn").addEventListener("click", () => zoomBy(ZOOM_STEP));
        $("zoomOut").addEventListener("click", () => zoomBy(1 / ZOOM_STEP));
        $("zoomFit").addEventListener("click", () =>
          setZoom(1, "fit"),
        ); /* 具体倍数由 fitScale() 决定 */
        $("zoomActual").addEventListener("click", () =>
          setZoom(1, "custom"),
        ); /* demo3 原「原始尺寸」模式 */

        /* ================= 渲染:顶栏状态点 / 引擎面板 ================= */
        const ENG_MAP = {
          loading: ["loader", "引擎加载中", "load"],
          ready: ["ok", "引擎就绪", "ok"],
          rebuilding: ["refresh", "引擎重建中", "load"],
          failed: ["alert", "引擎不可用", "fail"],
          waiting_models: ["cloud-off", "等待模型就绪", "warn"],
          /* 服务端(src/bin/serve/state.rs 的 EngineState)在模型不齐备时报的是
     blocked_models_missing(docs/05 §7.6 的枚举名);离线预览模式报 waiting_models。
     两者是同一件事,展示必须一致,否则真实模式下会退化成"状态未知"。 */
          blocked_models_missing: ["cloud-off", "等待模型就绪", "warn"],
          unknown: ["info", "状态未知", "dim"],
        };
        function engIcon(icn) {
          if (icn === "ok") return '<span class="dot ok"></span>';
          return ic(icn, icn === "loader" || icn === "refresh" ? "spin" : "");
        }
        function renderPill() {
          const s = state.status || emptyStatus("loading");
          const m = ENG_MAP[s.state] || ENG_MAP.unknown;
          const label = state.netFail ? "服务未连接" : m[1];
          $("enginePill").innerHTML =
            (state.netFail ? ic("alert") : engIcon(m[0])) +
            `<span>${label}</span>`;
        }
        /* §7.5:requested / selected_ep / fallback_to_cpu 三字段必须成组、分别出现。
   字段缺失(旧响应、演示数据不全、服务不可达)时显式渲染「未知」,
   不得留空、不得崩溃,更不得用 false 冒充缺失(false 只表示"明确未回退")。 */
        const EP_UNKNOWN = "— · 未知";
        function epDd(id, v, what) {
          return v == null
            ? `<dd id="${id}" class="ep-unknown" title="响应未提供 ${what} 字段(旧版服务 / 演示数据缺失)">${EP_UNKNOWN}</dd>`
            : `<dd id="${id}">${esc(v)}</dd>`;
        }
        function epDl(s, extra) {
          const fb = s.fallback;
          const fbCell =
            fb === true
              ? `<dd id="epFallback" class="warn-dd" title="请求的 provider 不可用,实际在 CPU 上执行">${ic("alert")} 是 · 已回退 CPU</dd>`
              : fb === false
                ? '<dd id="epFallback" title="实际使用的 EP 与请求一致">否 · 未回退</dd>'
                : `<dd id="epFallback" class="ep-unknown" title="响应未提供 fallback_to_cpu 字段(旧版服务 / 演示数据缺失)">${EP_UNKNOWN}</dd>`;
          return `<dl class="eng-kv">

      <div><dt>REQUESTED</dt>${epDd("epRequested", s.requested, "requested")}</div>

      <div><dt>SELECTED_EP</dt>${epDd("epSelected", s.selected_ep, "selected_ep")}</div>

      <div><dt>FALLBACK_TO_CPU</dt>${fbCell}</div>${extra || ""}

    </dl>`;
        }
        /* 队列就绪行:把"文本就绪 / 公式缺失"与"文本缺失"明确区分开。
   公式集合缺失**只写成公式队列不可用**,绝不呈现为整页失败(§10.8 公式路由默认关闭)。 */
        function queueReadyHtml() {
          const t = modelsReadyFor("text"),
            f = modelsReadyFor("formula"),
            b = modelsReadyFor("table");
          if (t.fatal)
            return `<div class="eng-q eng-q-warn" id="qReady">

      ${ic("alert")}<span class="eng-q-txt"><b>模型状态未知</b><br>尚未取得 /api/models 的模型集状态,无法判断任何队列是否可提交。</span></div>`;
          const textCell = t.ready
            ? "<b>文本队列 · 就绪</b><br>detector + recognizer + dictionary 齐备 → POST /api/ocr 可提交。"
            : `<b>文本队列 · 不可用</b><br>缺少 ${esc(t.missing.join("、"))} → POST /api/ocr 会被服务端以 409 models_missing 拒绝。`;
          const fxCell = f.ready
            ? "<b>公式队列 · 就绪</b><br>公式模型集齐备,可在左侧开启公式识别路由。"
            : `<b>公式队列 · 不可用(不影响普通 OCR)</b><br>${esc(formulaBlockedText(f))};` +
              "公式路由默认关闭(§10.8),普通文本 OCR 照常可用。";
          const tblCell = b.ready
            ? "<b>表格队列 · 就绪</b><br>表格结构模型集齐备,可在左侧选择「文本 + 表格」或「文本 + 公式 + 表格」。"
            : `<b>表格队列 · 不可用(不影响普通 OCR)</b><br>${esc(tableBlockedText(b))};` +
              "表格路由默认关闭,普通文本 OCR 照常可用。";
          return `<div class="eng-q ${t.ready ? "eng-q-ok" : "eng-q-warn"}" id="qReady">

      ${ic(t.ready ? "check" : "alert")}<span class="eng-q-txt">${textCell}</span></div>

    <div class="eng-q eng-q-off ${f.ready ? "eng-q-ok" : ""}" id="qReadyFormula">

      ${ic(f.ready ? "check" : "info")}<span class="eng-q-txt">${fxCell}</span></div>

    <div class="eng-q eng-q-off ${b.ready ? "eng-q-ok" : ""}" id="qReadyTable">

      ${ic(b.ready ? "check" : "info")}<span class="eng-q-txt">${tblCell}</span></div>`;
        }
        function renderEngine() {
          const s = state.status,
            ep = $("enginePanel");
          if (!s) {
            ep.innerHTML =
              '<div class="eng-state">' +
              ic("loader", "spin") +
              "<b>正在连接本地服务…</b></div>" +
              epDl(emptyStatus("loading"));
            return;
          }
          if (state.netFail) {
            ep.innerHTML =
              '<div class="eng-state">' +
              ic("alert") +
              "<b>无法连接本地服务</b></div>" +
              '<p class="eng-warn">' +
              ic("info") +
              "确认 rapidstruct serve 正在运行(默认 127.0.0.1:8760),且本页由 serve --open 打开。</p>" +
              epDl(s) /* 服务不可达:三字段如实显示为未知 */ +
              '<div class="eng-retry"><button class="btn-ghost sm" id="retryStatus">' +
              ic("refresh") +
              "重试连接</button></div>";
            return;
          }
          const m = ENG_MAP[s.state] || ENG_MAP.unknown;
          const qs = s.queues;
          const queueTxt =
            qs && qs.text
              ? `${qs.text.used != null ? qs.text.used : "—"}/${qs.text.capacity != null ? qs.text.capacity : "—"} · ` +
                `${qs.formula && qs.formula.used != null ? qs.formula.used : "—"}/${qs.formula && qs.formula.capacity != null ? qs.formula.capacity : "—"}`
              : "—";
          const tq = modelsReadyFor("text");
          /* §7.6:引擎状态与模型状态是两件事。若服务端报模型不齐备(blocked_models_missing)
     或离线预览报 waiting_models,而文本集合其实齐备(只差公式),这里必须改写成
     "部分模型集不齐备",不得让公式缺口看起来像全局失败。 */
          const waiting =
            s.state === "waiting_models" ||
            s.state === "blocked_models_missing";
          const head =
            tq.ready && waiting
              ? { icn: "info", txt: "引擎就绪(仅部分模型集不齐备)" }
              : { icn: m[0], txt: m[1] };
          ep.innerHTML =
            `<div class="eng-state">${engIcon(head.icn)}<b>${head.txt}</b>` +
            (DEMO && s.state === "ready"
              ? `<span class="eng-note">ENGINE&nbsp;BUILD&nbsp;${(demo.buildMs / 1000).toFixed(1)}S</span>`
              : "") +
            `</div>` +
            (s.fallback === true
              ? `<p class="eng-warn">${ic("alert")}<span>已回退至 CPU 执行 — 仅表示请求的 provider 不可用,<b>不代表性能结论</b>;请以本页任务的实测耗时为准。</span></p>`
              : "") +
            queueReadyHtml() +
            epDl(
              s,
              `<div><dt>ORT&nbsp;RUNTIME</dt><dd>${esc(s.ort)}</dd></div>` +
                `<div><dt>峰值内存</dt><dd>${s.memory != null ? fmtBytes(s.memory) : "—"}</dd></div>` +
                `<div><dt>队列(文/式)</dt><dd>${queueTxt}</dd></div>`,
            );
        }
        $("enginePanel").addEventListener("click", (e) => {
          if (e.target.closest("#retryStatus")) statusOnce();
        });

        /* ================= 重新校验(POST /api/models/reverify,A2) =================
   请求契约(docs/05 §4.2):POST /api/models/reverify,**请求体为空**(无参数动作,
   任何 body 都是协议级错误)。服务端的三步是:清掉校验缓存 → 冷验证本次运行会用到的
   每个模型文件 → 如果引擎此前就绪则重建会话。返回里必须被如实展示的是:
     computed          这一次真的重算了几个摘要("重新校验"有没有真的发生)
     content_changed   哪些文件是"stat 身份没变、内容变了"(旧身份下的盲区被抓住的那个)
     outcome / engine  重建结论(ready / rolled_back / blocked_models_missing / failed)
   并发时服务端给 503 busy(单飞),这里照常按 ERR_TEXT 解释。
   离线预览模式(无令牌)不发请求,只说明该动作需要真实服务——页面不伪造结论。 */
        function renderVerify() {
          const box = $("verifyOut"),
            hint = $("verifyHint");
          if (!box || !hint) return;
          const busy = state.verifying;
          const btn = $("verifyBtn");
          if (btn) btn.disabled = !!busy;
          hint.textContent = busy
            ? "正在进行:清缓存 → 重新读盘核对 → 重建引擎会话…"
            : "POST /api/models/reverify · 重新读盘核对模型并重建引擎会话";
          const o = state.verifyOut;
          if (!o) {
            box.hidden = true;
            box.innerHTML = "";
            return;
          }
          box.hidden = false;
          if (o.error) {
            const e = o.error;
            /* 服务端的 ErrorBody 是 {code,message,detail};XHR 层的拒绝对象是 {status,code,body}。
       两种形状都如实显示,并且**不**把未知形状渲染成空白。 */
            const code = e.code || (e.body && e.body.code);
            const msg = e.message || (e.body && e.body.message) || "";
            const base =
              ERR_TEXT[code] ||
              "请求失败" + (e.status ? `(HTTP ${e.status})` : "");
            box.innerHTML =
              `<span class="vo-line"><b>重新校验失败</b> — ${esc(base)}</span>` +
              (msg
                ? `<span class="vo-line">服务端原文:${esc(msg)}</span>`
                : "") +
              `<span class="vo-line">本次失败不改写已经在跑的引擎状态(以 /api/status 为准)。</span>`;
            return;
          }
          const c = o.value || {};
          const files = Array.isArray(c.files) ? c.files : [];
          const bad = files.filter((f) => f.state !== "present");
          const changed = Array.isArray(c.content_changed)
            ? c.content_changed
            : [];
          const outcome = c.outcome != null ? String(c.outcome) : "—";
          /* 逐管线结论(A2 新增的 pipelines 块):顶层 missing/corrupt 是**文本**作用域,
     公式模型损坏只影响公式队列——因此这里按 f.pipeline 分开说,不把两者混成一句
     "服务不可用"。服务端没给这块时退回旧的单一结论(不伪造结论)。 */
          const pipes =
            c.pipelines && typeof c.pipelines === "object" ? c.pipelines : null;
          const fp = pipes && pipes.formula ? pipes.formula : null;
          const tp = pipes && pipes.table ? pipes.table : null;
          const blocked = (arr) => (Array.isArray(arr) ? arr : []);
          const badText = fp
            ? files.filter(
                (f) => f.pipeline !== "formula" && f.state !== "present",
              )
            : bad;
          const badFormula = fp
            ? files.filter(
                (f) => f.pipeline === "formula" && f.state !== "present",
              )
            : [];
          const badTable = tp
            ? files.filter(
                (f) => f.pipeline === "table" && f.state !== "present",
              )
            : [];
          box.innerHTML =
            `<span class="vo-line"><b>引擎 ${esc(outcome)}</b>` +
            (c.load_ms != null
              ? ` · 建会话 ${esc(String(c.load_ms))} ms`
              : "") +
            (c.error ? ` · ${esc(errText(c.error))}` : "") +
            `</span>` +
            `<span class="vo-line">本次重算摘要 <b>${c.computed != null ? esc(String(c.computed)) : "—"}</b> 个` +
            ` · 缺失(文本) <b>${Array.isArray(c.missing) ? c.missing.length : "—"}</b>` +
            ` · 损坏(文本) <b>${Array.isArray(c.corrupt) ? c.corrupt.length : "—"}</b>` +
            ` · 内容变化 <b>${changed.length}</b></span>` +
            (fp
              ? `<span class="vo-line">公式管线:<b>${
                  !fp.in_plan
                    ? "不属于本次运行"
                    : blocked(fp.blocked).length
                      ? "阻塞 " + esc(blocked(fp.blocked).join("、"))
                      : "正常"
                }</b>${fp.routing === false ? " · 路由未启用" : ""}${
                  fp.detector && fp.detector.file
                    ? ` · 检测模型 ${esc(fp.detector.file)}(${esc(fp.detector.state || "—")})`
                    : ""
                }</span>`
              : "") +
            (tp
              ? `<span class="vo-line">表格管线:<b>${
                  !tp.in_plan
                    ? "不属于本次运行"
                    : blocked(tp.blocked).length
                      ? "阻塞 " + esc(blocked(tp.blocked).join("、"))
                      : "正常"
                }</b>${tp.routing === false ? " · 路由未启用" : ""}${
                  tp.structure && tp.structure.file
                    ? ` · 结构模型 ${esc(tp.structure.file)}(${esc(tp.structure.state || "—")})`
                    : ""
                }</span>`
              : "") +
            (changed.length
              ? `<span class="vo-line">内容变化(stat 身份未变、首尾 64 KiB 不同):${esc(changed.join("、"))}</span>`
              : "") +
            (files.length
              ? `<div class="vo-files">${files
                  .map(
                    (f) => `<div class="vo-row">

          <span class="vo-name" title="${esc(f.name)}">${esc(f.name)}</span>

          <span class="vo-state ${f.state === "present" ? "ok" : "bad"}">${esc(f.state || "—")}</span>

          <span class="vo-hint">${esc(ROLE_ZH[f.role] || f.role || "")}${f.cause ? " · " + esc(f.cause) : ""}</span>

        </div>`,
                  )
                  .join("")}</div>`
              : "") +
            (badText.length
              ? `<span class="vo-line">服务端现在处于可定位的错误态:普通 OCR 会以 409 拒绝,直到这些文本管线文件恢复。</span>`
              : badFormula.length
                ? `<span class="vo-line">普通 OCR 不受影响;公式队列会以 409(detail.scope=formula)拒绝,直到这些公式文件恢复。</span>`
                : badTable.length
                  ? `<span class="vo-line">普通 OCR 不受影响;表格队列会以 409(detail.scope=table)拒绝,直到这些表格文件恢复。</span>`
                  : `<span class="vo-line">全部文件状态正常:报告的状态与内存里的会话都已按磁盘上的当前内容刷新。</span>`);
        }
        function reverifyModels() {
          if (state.verifying) return;
          if (DEMO) {
            state.verifyOut = {
              error: {
                code: "unavailable",
                message:
                  "离线预览模式没有服务端:重新校验需要通过 rapidstruct serve 打开本页",
              },
            };
            renderVerify();
            toast("离线预览模式没有服务端,无法执行重新校验", "err", "refresh");
            return;
          }
          state.verifying = true;
          state.verifyOut = null;
          renderVerify();
          /* 请求体**必须为空**(docs/05 §4.2:这是无参数动作,任何 body 都是 400)。
     因此走 `xhrSend` 而不是 `apiSendJson`——后者会把 `null` 序列化成字符串 "null"。 */
          xhrSend("POST", "/api/models/reverify", "")
            .then((v) => {
              state.verifying = false;
              state.verifyOut = { value: v };
              renderVerify();
              refreshModels(); /* 模型集/引擎状态都按磁盘上的当前内容重算一遍 */
              statusOnce();
              const n = v && v.computed != null ? v.computed : "—";
              const outcome = v && v.outcome ? v.outcome : "—";
              toast(
                `重新校验完成 · 重算 ${n} 个摘要 · 引擎 ${outcome}`,
                outcome === "ready" ? "ok" : "err",
                "refresh",
              );
            })
            .catch((e) => {
              state.verifying = false;
              state.verifyOut = { error: e };
              renderVerify();
              toastErr(e);
            });
        }
        $("verifyBtn").addEventListener("click", reverifyModels);

        /* ================= 渲染:模型横幅(§9.2) =================
  每一个"不齐备"的模型集**各自**拥有一个下载按钮,按钮携带该集合的 id
  (data-set-id),点击时把这份 id 原样送进 POST /api/models/download 的请求体。
  页面上不存在"全局下载按钮",因此不存在"默认下 sets[0]"这种语义歧义。 */
        /* 模型清单面板(E16.1)。它**总是**渲染全部模型集,不再只在出错时出现:把"一切正常"
   的状态藏起来会让用户无从确认模型到底齐不齐,而"齐备"与"缺失"在页面上的差别应当是
   能否下载,不是"看不看得见"。齐备的集合给"重新校验"(复用 POST /api/models/reverify),
   不齐备的集合保持高亮与按集合下载。
   数据全部来自 /api/models:sets[].files[] 给逐文件状态,pipelines.*.plan 给
   "哪个文件被哪条管线用"的**服务端结论** —— 页面不自己拼路径。
   下载进度按服务端给的粒度如实显示(有 current_file 就点名文件,只有集合级就只说集合级)。 */
        const PIPE_ZH = { text: "文本", formula: "公式", table: "表格" };
        const FILE_STATE_ZH = { present: "就绪", missing: "缺失", corrupt: "损坏" };
        /* 三态用**不同图标 + 不同颜色**,不只靠文字(E16.1.2):就绪 ✓ / 缺失 cloud-off /
   损坏 alert。颜色在 CSS 里,图标在这里。 */
        function fileStateCell(st) {
          const s = st || "missing";
          const icon =
            s === "present" ? "check" : s === "corrupt" ? "alert" : "cloud-off";
          return `<span class="bf-state ${esc(s)}">${ic(icon)}${esc(FILE_STATE_ZH[s] || s)}</span>`;
        }
        /* 模型计划:服务端已经把"哪个文件被哪条管线用"解析好了(pipelines.*.plan),
   页面只呈现。找不到声明集合的文件就是命令行指定的(--formula-detector / --table-model),
   这恰好是"三种模型来源"里唯一不在清单里的那一种,必须能被看见。 */
        function planRowsHtml() {
          const m = state.models;
          const pipes = m && m.pipelines;
          if (!pipes) return "";
          const sets = m.sets || [];
          const rows = [];
          ["text", "formula", "table"].forEach((key) => {
            const p = pipes[key];
            if (!p || !Array.isArray(p.plan) || !p.plan.length) return;
            p.plan.forEach((f) => {
              const owner = sets.find((s) =>
                (s.files || []).some(
                  (x) => x.name === f.name && x.role === f.role,
                ),
              );
              const st = f.state || "missing";
              rows.push(
                `<tr><td>${esc(PIPE_ZH[key] || key)}</td>` +
                  `<td class="pn">${esc(f.name)}</td>` +
                  `<td>${esc(ROLE_ZH[f.role] || f.role || "—")}</td>` +
                  `<td class="ps ps-${esc(st)}">${esc(FILE_STATE_ZH[st] || st)}</td>` +
                  `<td>${f.has_declared_digest ? "已声明" : "未声明"}</td>` +
                  `<td>${owner ? esc(owner.id) : "命令行指定"}</td></tr>`,
              );
            });
          });
          if (!rows.length) return "";
          return `<div class="plan">

      <div class="plan-title">模型计划(服务端解析,页面不拼路径)</div>

      <div class="plan-wrap"><table>

        <thead><tr><th>管线</th><th>文件</th><th>角色</th><th>状态</th><th>摘要</th><th>声明来源</th></tr></thead>

        <tbody>${rows.join("")}</tbody>

      </table></div>

    </div>`;
        }
        function renderBanner() {
          const box = $("banner");
          const m = state.models;
          if (m && m.error) {
            box.hidden = false;
            box.innerHTML = `<div class="banner-main"><span class="banner-ic">${ic("alert")}</span>

      <div class="banner-info"><div class="banner-title"><b>模型状态获取失败</b><span>${esc(errText(m.error))}</span></div></div>

      <div class="banner-act"><button class="btn-ghost sm" id="retryModels">${ic("refresh")}重试</button></div></div>`;
            return;
          }
          if (!m || !m.sets) {
            box.hidden = true;
            return;
          }
          const sets = m.sets;
          const bad = sets.filter((s) => !s.complete);
          box.hidden = false;
          let html = `<div class="banner-main">

      <span class="banner-ic">${ic(bad.length ? "alert" : "check")}</span>

      <div class="banner-info">

        <div class="banner-title">

          <b>模型清单 · ${sets.length} 个集合</b>

          <span>来源 ${esc(m.source)} · ${
            m.downloadsAllowed
              ? "服务已允许下载(--allow-download)"
              : "服务未以 --allow-download 启动,页面不能下载模型"
          } · ${bad.length ? `${bad.length} 个集合不齐备` : "全部齐备"}</span>

        </div>

        <div class="msets">`;
          sets.forEach((set) => {
            const files = set.files || [];
            const pend = files.filter((f) => f.state !== "present");
            const corrupt = pend.filter((f) => f.state === "corrupt").length;
            const missing = pend.length - corrupt;
            const hosts =
              [...new Set(files.map((f) => hostOf(f.url)).filter(Boolean))].join(
                " / ",
              ) || "—";
            const bytes = files.reduce((a, f) => a + (f.size || 0), 0);
            const busy = state.dlSetId === set.id;
            const hasUrl = pend.length > 0 && pend.every((f) => !!f.url);
            let act;
            if (set.complete) {
              act = `<button class="btn-ghost sm btn-mini" data-reverify="1" title="重新读取磁盘上的文件并重算 SHA-256">${ic("refresh")}重新校验</button>`;
            } else if (busy) {
              act = `<button class="btn-primary sm btn-mini" disabled>${ic("loader", "spin")}下载中…</button>`;
            } else {
              /* 不可下载的两种理由分别给出文字说明,按钮仍可点击以便解释(按钮用 aria-disabled,
         不用 disabled 属性——disabled 按钮不派发 click,用户点不出任何解释)。 */
              const why = !hasUrl
                ? "该集合有文件缺少 source_url,服务端无法构造下载请求"
                : !m.downloadsAllowed
                  ? "服务未以 --allow-download 启动,请重启服务并添加该参数"
                  : "";
              act =
                `<button class="btn-primary sm btn-mini" data-set-id="${esc(set.id)}"

               aria-disabled="${why ? "true" : "false"}"

               title="${why ? esc(why) : "仅下载「" + esc(set.id) + "」这一个集合"}">

               ${ic("download")}下载「${esc(set.id)}」· ${fmtBytes(bytes)}</button>` +
                (why ? `<p class="banner-note">${esc(why)}</p>` : "");
            }
            const stTxt = set.complete
              ? "齐备"
              : corrupt
                ? `损坏 ${corrupt}${missing ? " · 缺失 " + missing : ""}`
                : `缺失 ${missing}`;
            html += `<details class="mset${set.complete ? "" : " mset-bad"}" ${set.complete ? "" : "open"}>

      <summary>

        <span class="ms-state ${set.complete ? "ok" : "bad"}">${ic(set.complete ? "check" : corrupt ? "alert" : "cloud-off")}${esc(stTxt)}</span>

        <b class="ms-id">${esc(set.id)}</b>

        <span class="ms-meta">${esc(set.family || "—")} ${esc(set.version || "")} · ${files.length} 个文件 · ${fmtBytes(bytes)} · 来源 ${esc(hosts)}</span>

      </summary>

      <div class="banner-files">${files
        .map(
          (f) => `

        <div class="bf-row">

          ${fileStateCell(f.state)}

          <span class="bf-name" title="${esc(f.name)}">${esc(f.name)}</span>

          <span class="bf-role">${esc(ROLE_ZH[f.role] || f.role || "—")}</span>

          <span class="bf-size">${fmtBytes(f.size)}</span>

        </div>${
          f.sha
            ? `<details class="bf-sha-row"><summary>sha256 ${esc(f.sha.slice(0, 12))}…</summary><code>${esc(f.sha)}</code></details>`
            : ""
        }`,
        )
        .join("")}</div>

      <div class="ms-act">${act}</div>

      ${corrupt ? `<p class="banner-note">损坏文件的哈希校验未通过,建议重新下载;下载完成并通过校验后将以原子方式替换原文件。</p>` : ""}

    </details>`;
          });
          html += `</div>${planRowsHtml()}</div></div>`;
          /* 下载进度:两种模式都来自同一个 job 生命周期(§4.2 kind="model_download")。
     真实模式逐秒轮询 GET /api/jobs/{id} 并显示其 state;演示模式给出实测百分比。 */
          if (state.dlJob) {
            const st = state.dlJob.state || "queued";
            const el =
              state.dlJob.elapsed_ms != null
                ? ` · ${(state.dlJob.elapsed_ms / 1000).toFixed(1)}s`
                : "";
            /* M2:任务视图里的 download{files_done,files_total,bytes_done,bytes_total,current_file}
       是服务端唯一的进度事实来源(逐文件 + 字节)。字节总数未知时退回文件计数。 */
            const dp = state.dlJob.download;
            let pct = null,
              cur = "";
            if (dp && dp.files_total > 0) {
              pct =
                dp.bytes_total > 0
                  ? (dp.bytes_done / dp.bytes_total) * 100
                  : (dp.files_done / dp.files_total) * 100;
              pct = Math.max(0, Math.min(100, pct));
              cur = dp.current_file ? ` · 当前 ${esc(dp.current_file)}` : "";
              cur += ` · ${dp.files_done}/${dp.files_total} 个文件`;
            }
            const pctTxt = pct == null ? "…" : `${pct.toFixed(0)}%`;
            html += `<div class="banner-dl">

      <div class="dl-line"><span>${ic("package")} 下载任务 <b>${esc(state.dlJob.id)}</b> · 集合「${esc(state.dlJob.set_id)}」· 状态 <b>${esc(modelJobZh(st))}</b>${el}${cur}(逐文件下载,完成后自动校验 SHA-256)</span><b>${pctTxt}</b></div>

      <div class="bar${pct == null ? " ind" : ""}"><i id="dlJobBar"></i></div>

      <div class="dl-line"><span>取消下载 = POST /api/jobs/{id}/cancel,与取消识别同一套 job 语义(运行中的下载在<b>文件边界</b>生效)</span>

      <button class="btn-ghost sm" id="dlCancelBtn">${ic("x")}取消下载</button></div></div>`;
          } else if (demo.dlActive) {
            html += `<div class="banner-dl">

      <div class="dl-line"><span>${ic("package")} 正在下载 ${esc(demo.dlFile)} · 逐文件下载,完成后自动校验 SHA-256</span><b>${demo.dlPct.toFixed(0)}%</b></div>

      <div class="bar"><i id="dlBar"></i></div></div>`;
          }
          box.innerHTML = html;
          const bar = $("dlBar");
          if (bar)
            bar.style.width = demo.dlPct + "%"; /* CSSOM,无需内联 style 属性 */
          const jobBar = $("dlJobBar");
          if (
            jobBar &&
            state.dlJob &&
            state.dlJob.download &&
            state.dlJob.download.files_total > 0
          ) {
            const d = state.dlJob.download;
            const p =
              d.bytes_total > 0
                ? (d.bytes_done / d.bytes_total) * 100
                : (d.files_done / d.files_total) * 100;
            jobBar.style.width = Math.max(0, Math.min(100, p)) + "%";
          }
        }
        function modelJobZh(st) {
          return (
            {
              queued: "排队中",
              running: "下载中",
              succeeded: "已完成",
              failed: "失败",
              cancelled: "已取消",
            }[st] || st
          );
        }
        $("banner").addEventListener("click", (e) => {
          const retry = e.target.closest("#retryModels");
          if (retry) return refreshModels();
          const cancel = e.target.closest("#dlCancelBtn");
          if (cancel) return cancelDownload();
          /* 齐备集合的"重新校验":与 #verifyBtn 同一个动作(POST /api/models/reverify)。
             放在清单里,用户不必先去右边找那个按钮。 */
          if (e.target.closest("[data-reverify]")) return reverifyModels();
          const dl = e.target.closest("[data-set-id]");
          if (!dl) return;
          /* aria-disabled 的按钮仍然可点:这一次点击只用来解释"为什么不能下" */
          if (dl.getAttribute("aria-disabled") === "true")
            return toast(
              dl.title || "当前不可下载该模型集",
              "err",
              "cloud-off",
            );
          startDownload(dl.dataset.setId);
        });
        function flashBanner() {
          const b = $("banner");
          b.scrollIntoView({ block: "nearest", behavior: "smooth" });
          b.classList.remove("flash");
          void b.offsetWidth;
          b.classList.add("flash");
        }

        /* ================= 模型下载(POST /api/models/download + job 生命周期,§4.2/§6) =================
  请求契约(docs/05 §4.2 + §7.2):POST /api/models/download
    Content-Type: application/json,请求体 {"set_id": "<被点击集合的 id>"}
  §7.2 明确"请求体不得携带 URL"(防 SSRF),因此请求体里**只有** set_id。
  返回 {job_id, queue, state} —— 下载就是 kind="model_download" 的普通 job:
    · 进度/状态:GET  /api/jobs/{id}
    · 取消:      POST /api/jobs/{id}/cancel
  页面里**不存在**第二套下载取消端点:下载任务只能经由上面这套统一 job 语义取消。
  (历史实现曾自行发明一个 models 下的"下载取消"端点——把 /cancel 直接挂在模型下载路径上,
  与 docs/05 §4.2 的端点表不符,已彻底删除;本文件内不存在该路径的任何字面量。) */
        function startDownload(setId) {
          if (demo.dlActive || state.dlJob) return;
          /* 缺失/空 set_id 一律**本地拒绝**,绝不发一个没有 set_id 的请求(那等于让服务端去猜集合) */
          const id = setId == null ? "" : String(setId).trim();
          if (!id) {
            const msg =
              "未指定模型集 set_id,已本地拒绝该下载请求(不发送缺 set_id 的请求)";
            state.diag = [msg].concat(state.diag).slice(0, 12);
            renderDiag();
            flashBanner();
            return toast(msg, "err", "cloud-off");
          }
          if (DEMO) return demoDownload(id);
          const set =
            state.models && state.models.sets
              ? state.models.sets.find((s) => s.id === id)
              : null;
          if (!set) {
            const msg = `模型集 ${id} 不在 /api/models 的 sets 中,已本地拒绝该下载请求`;
            state.diag = [msg].concat(state.diag).slice(0, 12);
            renderDiag();
            return toast(msg, "err", "cloud-off");
          }
          state.dlSetId = id;
          state.dlJob = {
            id: null,
            set_id: id,
            state: "queued",
            elapsed_ms: 0,
          };
          renderBanner();
          apiSendJson("POST", "/api/models/download", { set_id: id })
            .then((d) => {
              const jobId = d && d.job_id;
              if (!jobId) {
                throw {
                  code: "internal",
                  message: "响应未返回 job_id(下载任务必须可轮询、可取消)",
                };
              }
              state.dlJob.id = jobId;
              if (d.state) state.dlJob.state = d.state;
              toast(
                `模型集「${id}」下载任务已启动 · job ${jobId}`,
                "ok",
                "package",
              );
              renderBanner();
              pollDownloadJob();
            })
            .catch((e) => {
              state.dlJob = null;
              state.dlSetId = null;
              renderBanner();
              toastErr(e);
            });
        }
        let dlPollTimer = null;
        function pollDownloadJob() {
          clearTimeout(dlPollTimer);
          const j = state.dlJob;
          if (!j || !j.id) return;
          const tick = async () => {
            if (!state.dlJob || state.dlJob.id !== j.id) return;
            try {
              const d = await apiJson("GET", "/api/jobs/" + j.id);
              Object.assign(j, d);
              renderBanner();
              if (j.state === "queued" || j.state === "running") {
                dlPollTimer = setTimeout(tick, document.hidden ? 2000 : 800);
                return;
              }
            } catch (e) {
              if (e && (e.status === 410 || e.status === 404)) {
                toast(
                  e.status === 410
                    ? "下载任务记录已被淘汰(410)"
                    : "下载任务不存在(404)",
                  "err",
                );
              }
              /* 瞬时错误:退避重试,仍以 job 为唯一事实来源 */
              dlPollTimer = setTimeout(tick, 1600);
              return;
            }
            /* 终态:下载任务本身结束,再取一次 /api/models 看各文件是否已 present */
            const st = j.state;
            state.dlJob = null;
            state.dlSetId = null;
            await refreshModels();
            renderBanner();
            renderButton();
            if (st === "succeeded")
              toast(
                `模型集「${j.set_id}」下载完成,引擎将在下次识别时惰性创建`,
                "ok",
                "package",
              );
            else if (st === "failed")
              toast(
                `模型集「${j.set_id}」下载失败:${j.error || "未知错误"}`,
                "err",
              );
            else if (st === "cancelled")
              toast(
                `模型集「${j.set_id}」下载已取消(临时文件已清理,已校验完成的文件保留)`,
                "err",
                "info",
              );
          };
          tick();
        }
        function cancelDownload() {
          const j = state.dlJob;
          if (!j) return;
          if (DEMO) {
            demo.dlActive = false;
            state.dlJob = null;
            state.dlSetId = null;
            renderBanner();
            return toast("已取消下载", "err", "info");
          }
          if (!j.id) {
            return toast("下载任务尚未取得 job_id,无法取消", "err");
          }
          return apiJson("POST", "/api/jobs/" + j.id + "/cancel")
            .then(() =>
              toast(
                "已请求取消下载" +
                  (j.state === "running" ? "(取消在文件边界生效)" : ""),
                "ok",
              ),
            )
            .catch((e) =>
              toastErr(e),
            ); /* 409 not_cancellable / job_finished 如实提示,不假装成功 */
        }

        /* ================= 渲染:文件信息 / 按钮状态 ================= */
        function renderMeta() {
          if (!state.image) return;
          const i = state.image;
          $("metaText").innerHTML =
            `<b>${esc(i.file.name || "clipboard.png")}</b> · ${i.w}×${i.h} · ${fmtBytes(i.file.size)}`;
          $("annotatedBtn").hidden = !state.result;
        }
        function renderButton() {
          const btn = $("ocrBtn"),
            lbl = $("ocrLbl"),
            ico = $("ocrIco");
          const use = (n) => {
            ico.innerHTML = `<use href="#i-${n}"/>`;
          };
          ico.classList.remove("spin");
          if (state.uploading) {
            btn.disabled = true;
            lbl.textContent = "上传中…";
            use("loader");
            ico.classList.add("spin");
            return;
          }
          if (jobActive()) {
            btn.disabled = true;
            lbl.textContent = "识别中…";
            use("loader");
            ico.classList.add("spin");
            return;
          }
          if (!state.image) {
            btn.disabled = true;
            lbl.textContent = "等待图像输入";
            use("scan");
            return;
          }
          /* 提交普通 OCR(文本队列)只看**文本集合**是否齐备:公式模型缺失不影响此处(P1-2) */
          const q = modelsReadyFor("text");
          if (!q.ready) {
            btn.disabled = false; /* 仍可点:点击时解释缺什么 */
            lbl.textContent = q.fatal
              ? "模型状态未知 · 点击查看"
              : `模型缺失 · 点击查看(${q.missing.join("、")})`;
            use("cloud-off");
            return;
          }
          btn.disabled = false;
          if (state.result) {
            lbl.textContent = "重新识别";
            use("refresh");
          } else {
            lbl.textContent = "开始识别";
            use("scan");
          }
        }
        /* 识别模式选择器(E16.2):四项 = `queue` × `table` 的全部可表达组合。
   每一项**独立**判定可用性(文本队列 / 公式路由 / 表格路由),不可用的项在
   `#modeCap` 里**点名**缺哪个角色或哪条路由没开——不只靠颜色/透明度。禁用项仍可
   点击,点它只 toast 理由(照 #banner 的 [data-set-id] 先例:`disabled` 按钮不派发
   click,用户点不出解释)。状态随 /api/models 刷新实时变化,下载完成后自动可用,
   不需要重载页面。 */
        function renderModeRow() {
          const row = $("modeRow"),
            opts = $("modeOpts"),
            cap = $("modeCap");
          row.hidden = false;
          /* 当前模式失效时回落到「文本」(例如表格模型被移走)。绝不能带着一个服务端
     会以 400 拒绝的模式去提交——那样用户看到的是一次莫名其妙的失败。 */
          const before = modeById(state.mode);
          if (before !== MODES[0] && !modeAvailability(before).ok) {
            state.mode = MODES[0].id;
          }
          opts.innerHTML = MODES.map((m) => {
            const av = modeAvailability(m);
            const on = m.id === state.mode;
            const hint = av.ok ? m.desc : av.why;
            return `<button type="button" class="mode-opt" role="radio" data-mode="${m.id}" aria-checked="${on}" aria-disabled="${!av.ok}" title="${esc(hint)}"><span class="mo-dot" aria-hidden="true"></span><span class="mo-body"><span class="mo-name">${esc(m.name)}</span><span class="mo-desc">${esc(m.desc)}</span></span></button>`;
          }).join("");
          const cur = modeById(state.mode);
          const av = modeAvailability(cur);
          cap.textContent = av.ok
            ? `${cur.name}:请求 ${cur.desc}。公式与表格区域各自独立处理,正文文本 OCR 不受影响。`
            : `不可选:${av.why}。可在上方模型清单里按集合下载,或由服务端加 --formula-detector / --table-model 启用。`;
          /* 两个请求面选择器一起刷新:它们都只依赖 `state` + 模型状态,调用点已经很多
     (启动 / 模型轮询 / 下载完成 / 失败),分头调用更容易漏。 */
          renderWordsRow();
        }
        /* 框粒度选择器(Step 2)。与识别模式复用同一套样式与渲染口径,但**可用性判定不同**:
   三档都不依赖额外模型(逐词/逐字框是识别阶段的后处理,recognize 开着就能给),所以没有
   禁用态,只有“这一档实际意味着什么”——包括“字级框是 CTC 估计”这条不能省略的口径。
   切换档位**不会**重跑已完成的识别:`?words=` 在提交那一刻就被固定(serve 侧的
   `RetainedOcr.params`),所以必须提示用户“重新识别才生效”。 */
        function renderWordsRow() {
          const row = $("wordsRow"),
            opts = $("wordsOpts"),
            cap = $("wordsCap");
          row.hidden = false;
          /* 存的值不在词表里(例如用户手改了 localStorage)→ 回落 off,
     绝不带着服务端会以 400 拒绝的档位去提交。 */
          if (!WORDS_MODES.some((m) => m.id === state.words)) state.words = "off";
          opts.innerHTML = WORDS_MODES.map((m) => {
            const on = m.id === state.words;
            return `<button type="button" class="mode-opt" role="radio" data-words="${m.id}" aria-checked="${on}" title="${esc(m.hint)}"><span class="mo-dot" aria-hidden="true"></span><span class="mo-body"><span class="mo-name">${esc(m.name)}</span><span class="mo-desc">${esc(m.desc)}</span></span></button>`;
          }).join("");
          const cur = wordsModeById(state.words);
          cap.textContent =
            cur.id === "off"
              ? "仅行框:不发 words 参数,响应体里没有逐词/逐字框,图上也没有可选中的文本层(叠框与右栏列表照旧)。"
              : `${cur.name}:请求 ${cur.desc}。${cur.hint} 切换档位后需重新识别才会生效。`;
        }
        $("wordsOpts").addEventListener("click", (e) => {
          const btn = e.target.closest("[data-words]");
          if (!btn) return;
          const m = wordsModeById(btn.getAttribute("data-words"));
          if (state.words === m.id) return;
          state.words = m.id;
          try {
            localStorage.setItem(WORDS_KEY, m.id);
          } catch {}
          renderWordsRow();
          toast(
            m.id === "off"
              ? "框粒度:仅行框(重新识别后文本层会消失)"
              : `框粒度:${m.name}(${m.desc})· 重新识别后生效`,
            "ok",
            "check",
          );
        });
        $("modeOpts").addEventListener("click", (e) => {
          const btn = e.target.closest("[data-mode]");
          if (!btn) return;
          const m = modeById(btn.getAttribute("data-mode"));
          const av = modeAvailability(m);
          if (!av.ok) {
            toast(`${m.name} 不可选:${av.why}`, "err", "cloud-off");
            return;
          }
          if (state.mode === m.id) return;
          state.mode = m.id;
          renderModeRow();
          toast(`识别模式:${m.name}(${m.desc})`, "ok", "check");
        });
        $("ocrBtn").addEventListener("click", () => {
          if (state.uploading || jobActive() || !state.image) return;
          /* 门禁有两层:文本队列是普通 OCR 的**硬前提**(与选了什么模式无关),
     当前模式还要它自己那几条路由都就绪。 */
          const q = modelsReadyFor("text");
          if (!q.ready) {
            toast(
              q.fatal
                ? "尚未取得 /api/models 模型状态,无法确认文本模型是否齐备"
                : `普通 OCR 模型集不齐备:缺少 ${q.missing.join("、")},请先在横幅中按集合下载`,
              "err",
              "cloud-off",
            );
            flashBanner();
            return;
          }
          const m = modeById(state.mode);
          const av = modeAvailability(m);
          if (!av.ok) {
            toast(`${m.name} 不可用:${av.why}`, "err", "cloud-off");
            renderModeRow();
            flashBanner();
            return;
          }
          if (DEMO && demo.phase === "waitmodels" && !demo.textReady) {
            toast("演示模式:文本模型尚未就绪", "err", "cloud-off");
            flashBanner();
            return;
          }
          submitImage();
        });

        /* ================= 提交识别(XHR 上传 + 进度 + 取消上传,§9.1) ================= */
        function setUpProgress(p) {
          $("upPct").textContent = Math.round(p * 100) + "%";
          $("upBar").style.width = (p * 100).toFixed(1) + "%"; /* CSSOM */
        }
        $("abortUpBtn").addEventListener("click", () => {
          demo.upAbort = true; /* 演示模式:置取消标志 */
          if (state.xhr) state.xhr.abort(); /* 真实模式:xhr.abort() */
        });
        function showUp(v) {
          $("uploadProg").hidden = !v;
        }

        function submitImage() {
          if (DEMO) return demoUpload();
          state.uploading = true;
          showUp(true);
          setUpProgress(0);
          renderButton();
          drop.classList.add("no-click");
          /* 请求表达由所选模式决定(E16.2):`?queue=` 选管线类别,`?table=1` 是**正交**的
     第二维(表格阶段跑在页面管线内部,没有自己的队列)。旧版这里只有 `?queue=` 一个
     表达,因为当时表格还没接进 serve。缺省即 `queue=text`(不带 `table`),因此"页面
     到底发了什么"在流动日志里一眼可见,不靠默认值推断。 */
          const mode = modeById(state.mode);
          const queue = mode.queue;
          /* 第三个正交参数:`words=`(框粒度,Step 2)。off 时**不带**参数,因此缺省路径的
     请求串与响应体都与接入本档之前一致;非 off 时它直接拼成 `&words=words|chars`,
     与 CLI 的 `--words` / `--chars` 同一个词表(`WordOutputMode::as_str`)。 */
          const url = "/api/ocr?queue=" + queue + (mode.table ? "&table=1" : "") + wordsQuery();
          xhrSend("POST", url, state.image.file, {
            octet: true,
            onProgress: setUpProgress,
            getXhr: (x) => {
              state.xhr = x;
            },
          })
            .then((data) => {
              state.xhr = null;
              state.uploading = false;
              showUp(false);
              drop.classList.remove("no-click");
              renderButton();
              /* 202 的响应体同样是冻结契约:没有 job_id 就无法轮询,必须**可见地**失败,
       绝不允许进入"永远转圈"的状态。 */
              if (
                !data ||
                typeof data.job_id !== "string" ||
                data.job_id === ""
              ) {
                state.result = null;
                diagPush("响应字段缺失: job_id");
                toast(
                  "响应字段缺失: job_id — 前端按冻结契约解析 POST /api/ocr(202 {job_id,queue,position,state})",
                  "err",
                  "alert",
                );
                endJob();
                return;
              }
              clearResult(false); /* 只清上一次的结果:刚建好的任务不受影响 */
              toast(
                "任务已提交(202)· " +
                  mode.name +
                  " · " +
                  zhQueue(data.queue || queue) +
                  "队列" +
                  (mode.table ? " + 表格" : ""),
                "ok",
              );
              beginJob(data, queue, undefined, mode.id);
            })
            .catch((e) => {
              state.xhr = null;
              state.uploading = false;
              showUp(false);
              drop.classList.remove("no-click");
              /* 提交失败也走统一的终结路径:扫描动画是全局状态,任何返回路径都必须清掉它。 */
              endJob(failText("提交失败", e), "err");
            });
        }

        /* ================= 任务轮询(GET /api/jobs/{id},§4.2/§9.1) ================= */
        let pollTimer = null;
        /* 连续失败上限:瞬时错误(网络抖动 / 500)照旧退避重试,但**有限**次。
   旧实现对 404/410 之外的任何错误都无限退避重试,于是一个永久 401 就能让扫描动画
   转到天荒地老——那正是"不要用超时掩盖问题"要避免的另一面:必须有**终点**。
   上限取 8 次、退避从 480 ms 翻倍到 4 s(约 23 s 的重试窗口):真正的瞬时抖动会自愈,
   而一个不会自愈的错误会在 ~23 s 内变成一条**点名原因**的可见错误。 */
        let pollFails = 0;
        const POLL_FAIL_LIMIT = 8;
        function pollBackoff() {
          return Math.min(4000, 480 * Math.pow(2, Math.max(0, pollFails - 1)));
        }
        function startPolling() {
          clearTimeout(pollTimer);
          const tick = async () => {
            const j = state.job;
            if (!j) return;
            let d;
            try {
              d = await apiJson("GET", "/api/jobs/" + j.id);
            } catch (e) {
              /* 每次 catch 都必然终结或重试;终结一律经 endJob(),动画不可能留下。 */
              if (e.status === 410 || e.status === 404) {
                diagPush(
                  `任务终结: ${e.status === 410 ? "结果已被淘汰" : "任务不存在"}(HTTP ${e.status}${e.code ? " " + e.code : ""})`,
                );
                endJob(
                  failText(
                    e.status === 410
                      ? "结果已被淘汰,请重新识别"
                      : "任务不存在",
                    e,
                  ),
                  "err",
                );
                return;
              }
              if (
                e.status === 401 ||
                e.status === 403 ||
                e.status === 400 ||
                e.status === 409
              ) {
                /* 鉴权/契约类:重试不会变好,立刻如实报错。 */
                diagPush(`轮询被拒绝: ${failText("", e).replace(/^:/, "")}`);
                endJob(failText("轮询被拒绝", e), "err");
                return;
              }
              pollFails += 1;
              if (pollFails >= POLL_FAIL_LIMIT) {
                diagPush(
                  `轮询连续失败 ${pollFails} 次: ${failText("", e).replace(/^:/, "")}`,
                );
                endJob(
                  failText(`轮询连续失败 ${pollFails} 次,已停止`, e),
                  "err",
                );
                return;
              }
              /* 瞬时错误:指数退避重试(后台标签页里不加快节奏)。 */
              pollTimer = setTimeout(
                tick,
                document.hidden ? 1600 : pollBackoff(),
              );
              return;
            }
            pollFails = 0;
            Object.assign(j, d);
            renderJob();
            if (j.state === "queued" || j.state === "running") {
              pollTimer = setTimeout(tick, document.hidden ? 1600 : 480);
            } else if (j.state === "succeeded") {
              await fetchResult();
            } else {
              onJobEnd();
            }
          };
          tick();
        }
        async function fetchResult() {
          const j = state.job;
          if (!j) return;
          let r;
          try {
            r = await apiJson("GET", "/api/jobs/" + j.id + "/result");
          } catch (e) {
            if (e.code === "job_not_finished") {
              pollTimer = setTimeout(startPolling, 480);
              return;
            }
            /* 其它任何错误(404/410/413/422/503/…)都是终态:**必须**清场并给出具体原因。 */
            diagPush(`结果获取失败: ${failText("", e).replace(/^:/, "")}`);
            endJob(failText("结果获取失败", e), "err");
            return;
          }
          const parsed = normalizeResult(r);
          if (!parsed) {
            /* 契约失败:normalizeResult 已经 toast + 记诊断(逐字段点名路径)。
       这里同样要清场——旧实现在这条路上会留下永不停止的扫描动画。 */
            endJob(
              "响应不符合冻结契约,结果未渲染(诊断面板已点名具体字段路径)",
              "err",
            );
            return;
          }
          state.result = parsed;
          scanOff(); /* finishJob 之前先熄动画:finishJob 抛错也不会留下动画 */
          finishJob();
        }
        function onJobEnd() {
          const j = state.job;
          if (j && j.state === "failed")
            endJob("识别失败:" + (j.error || "未知错误"), "err");
          else if (j && j.state === "cancelled")
            endJob("任务已取消", "err", "info");
          else endJob();
        }
        function finishJob() {
          renderJob();
          renderRegions();
          checkWordsDelivery(); /* 先记诊断,再渲染诊断面板,否则本次的提示进不了面板 */
          renderDiag();
          renderMeta();
          renderButton();
          ["copyAllBtn", "expJson", "expMd", "expHtml"].forEach(
            (id) => ($(id).disabled = false),
          );
          $("annotatedBtn").hidden = false;
          layoutCanvas();
          renderTextLayer();
          const t = state.result.timings;
          const total =
            t.total_ms != null ? t.total_ms : t.total != null ? t.total : null;
          toast(
            "识别完成" +
              (total != null ? ` · ${(total / 1000).toFixed(2)} s` : ""),
            "ok",
          );
        }

        /* ================= 任务状态行 / 取消识别(§4.3 两种取消严格分开) ================= */
        function renderJob() {
          const jl = $("jobLine"),
            jt = $("jlText"),
            cb = $("cancelJobBtn");
          const j = state.job;
          if (!j) {
            jl.hidden = true;
            return;
          }
          jl.hidden = false;
          let html = "";
          if (j.state === "queued")
            html =
              ic("clock") +
              `<span>排队中 · <b>${zhQueue(j.queue)}队列</b>` +
              (j.mode ? ` · ${esc(modeById(j.mode).name)}` : "") +
              ` · 位置 ${j.position != null ? j.position : "—"}` +
              (j.queued_ms != null
                ? ` · 已等待 ${(j.queued_ms / 1000).toFixed(1)}s`
                : "") +
              "</span>";
          else if (j.state === "running")
            html =
              ic("loader", "spin") +
              `<span>识别中 · 已进行 <b>${((j.elapsed_ms || 0) / 1000).toFixed(1)}s</b></span>`;
          else if (j.state === "succeeded")
            html =
              ic("check") +
              `<span>识别完成 · 耗时 <b>${((j.elapsed_ms || 0) / 1000).toFixed(2)}s</b></span>`;
          else if (j.state === "failed")
            html =
              ic("alert") +
              `<span>失败 · <b>${esc(j.error || "未知错误")}</b></span>`;
          else html = ic("x") + `<span>已取消</span>`;
          jt.innerHTML = html;
          const cancellable = j.state === "queued" || j.state === "running";
          cb.hidden = !cancellable;
          cb.disabled =
            j.state ===
            "running"; /* running → 不可取消,如实呈现,不假装成功 */
          cb.title =
            j.state === "running"
              ? "推理进行中,当前版本不支持中断(not_cancellable)"
              : "从队列中移除该任务";
        }
        $("cancelJobBtn").addEventListener("click", async () => {
          const j = state.job;
          if (!j) return;
          if (DEMO) {
            /* 演示模式没有服务端可问:把状态改成终态后走**同一个**终结路径(onJobEnd → endJob)。 */
            if (j.state === "queued") {
              j.state = "cancelled";
              onJobEnd();
            } else toast("推理进行中,当前版本不支持中断", "err");
            return;
          }
          try {
            await apiJson("POST", "/api/jobs/" + j.id + "/cancel");
            toast("已请求取消", "ok");
          } catch (e) {
            /* 409 not_cancellable / job_finished 如实提示;两条路径都不动扫描动画——
       任务仍在跑(或已经在跑),动画本来就该继续,终结由轮询看到终态时统一清场。 */
            toastErr(e);
            if (e.code === "not_cancellable") $("cancelJobBtn").disabled = true;
          }
        });
        function scanOn() {
          stage.classList.add("scanning");
        }
        function scanOff() {
          stage.classList.remove("scanning");
        }

        /* ================= 公式渲染(KaTeX / MathJax 可切换,本地引用) =================
   用户需求:识别区域里出现公式(RegionKind::Formula)时,可切换"渲染 LaTeX 界面",
   并在 KaTeX 与 MathJax 之间切换。设计约束(与原页一致,逐条列出便于评审):

     · **懒加载**:只在用户第一次切到某个引擎时才注入 <script>/<link>,首屏零额外请求;
     · **本地引用(零 CDN)**:路径见 FX_LIBS,由 serve 同源静态托管(编译期嵌入,
       表由 build.rs 扫描 src/bin/web/static/ 生成);不使用任何 CDN;
     · **nonce 继承**:动态 <script>/<link> 复用启动脚本的 nonce;MathJax 自己注入的
       <style> 通过 options.cspNonce 拿同一个 nonce(否则会被 nonce CSP 拦掉);
       CSP 的 font-src 'self' 只为 KaTeX 的 woff2 字体放行(MathJax 走 SVG 输出不需要);
     · **失败可见**:加载失败 → 一次 toast + 回落原文;单条渲染异常 → 该条加 .fx-error 竖线
       并保留原文,不抛、不静默;
     · **记忆**:引擎选择写 localStorage(键 rrocr-fx-mode),刷新后保持;
     · **降级**:'off' 与未切换时公式区域显示 LaTeX 原文(与旧行为逐字节相同)。

   服务端已就位:KaTeX 0.19.0(js+css+woff2 字体)与 MathJax 4.1.3(tex-svg 组合
   组件)由 serve 以 /static/* 同源提供;页面引用的每个 /static/… 路径都有
   serve::assets 的测试钉住(页面与资源必须同源演进)。 */
        const FX_LIBS = {
          katex: {
            label: "KaTeX",
            js: "/static/katex/katex.min.js",
            css: "/static/katex/katex.min.css",
            /* 判断"可用"的条件:全局对象存在且 render 是可调用函数 */
            ready: () =>
              typeof window.katex !== "undefined" &&
              typeof window.katex.render === "function",
          },
          mathjax: {
            label: "MathJax",
            js: "/static/mathjax/tex-svg.js" /* v4 组合组件:TeX 输入 + SVG 输出(内联路径,不取 web 字体,因此不依赖 font-src) */,
            css: null /* MathJax 自带样式注入(nonce 经 options.cspNonce 继承),无需 <link> */,
            /* v4 的启动是异步的:脚本 onload 后 window.MathJax.startup 未必立刻就绪,
       因此 ready() 同时要求 tex2svgPromise(或退一步 typesetPromise)存在 */
            ready: () =>
              !!(
                window.MathJax &&
                window.MathJax.startup &&
                (typeof window.MathJax.tex2svgPromise === "function" ||
                  typeof window.MathJax.typesetPromise === "function")
              ),
          },
        };
        const FX_MODE_KEY = "rrocr-fx-mode"; /* 'off' | 'katex' | 'mathjax' */

        /* 在 IIFE 顶部已执行;此处复用启动脚本的 nonce。若页面未注入(离线预览),
           得到的可能是占位符字面量本身——这不影响功能,因为没有 CSP 生效。 */
        const FX_NONCE =
          (document.currentScript && document.currentScript.nonce) || "";

        /* MathJax v4 已移除 options.cspNonce(bundle 里根本读不到这个键),它向
           <head> 注入的每个 <style> 都不带 nonce → 在 style-src 'nonce-…' 下被拦,
           取不到 .sheet → setColor/insertRule 抛错、公式静默回退成源码。逐元素排版样式走
           CSSOM(t.style[x]=…)不受 CSP 管,因此唯一需授权的是这些注入的 <style>。
           下面的最小垫片:在节点真正进入 DOM 前,给任何“没有自己 nonce”的
           <style> / <link rel=stylesheet> 盖上本页同一个 nonce(运行时属性赋值,
           不新增 HTML 属性、不放宽 CSP——既不加 unsafe-inline 也不加 'self')。只盖
           style/link,不动 script;离线预览(FX_NONCE 为空)时不安装。 */
        if (FX_NONCE) {
          const fxStampNonce = (node) => {
            if (
              node &&
              node.nodeType === 1 &&
              !node.nonce &&
              (node.tagName === "STYLE" ||
                (node.tagName === "LINK" &&
                  String(node.rel).toLowerCase() === "stylesheet"))
            ) {
              node.nonce = FX_NONCE;
            }
            return node;
          };
          const fxOrigAppend = Node.prototype.appendChild;
          Node.prototype.appendChild = function (node) {
            return fxOrigAppend.call(this, fxStampNonce(node));
          };
          const fxOrigInsert = Node.prototype.insertBefore;
          Node.prototype.insertBefore = function (node, ref) {
            return fxOrigInsert.call(this, fxStampNonce(node), ref);
          };
        }

        const fxLoading =
          {}; /* 每个引擎的加载 Promise 缓存(失败后清空以便重试) */

        /* MathJax 必须在脚本加载**之前**完成配置,否则它启动时会用默认设置处理整页。
   这里不做自动排版(startup.typeset:false),只按需对单个元素排版。 */
        function ensureMathJaxConfig() {
          if (window.MathJax && window.MathJax.startup) return;
          window.MathJax = {
            tex: {
              inlineMath: [["\\(", "\\)"]],
              displayMath: [
                ["$$", "$$"],
                ["\\[", "\\]"],
              ],
              processEscapes: true,
            },
            options: {
              skipHtmlTags: [
                "script",
                "noscript",
                "style",
                "textarea",
                "pre",
                "code",
                "svg",
              ],
              ignoreHtmlClass: "tex2jax_ignore",
              processHtmlClass: "tex2jax_process",
              /* v4 没有 cspNonce 这个选项(会被它当成无效键忽略);MathJax 注入的
                 <style> 靠顶部那个 appendChild/insertBefore 垫片盖上本页 nonce。
                 这里不能再写 cspNonce(写了对 v4 也无意义,只会误导)。 */
            },
            startup: { typeset: false },
          };
        }

        function loadFxLibrary(name) {
          if (fxLoading[name]) return fxLoading[name];
          const lib = FX_LIBS[name];
          if (!lib) return Promise.reject(new Error("未知公式引擎: " + name));
          const p = new Promise((resolve, reject) => {
            if (lib.ready()) return resolve();
            if (name === "mathjax") ensureMathJaxConfig();
            /* CSS:<link rel=stylesheet>,同源路径 + 继承 nonce(CSP style-src 需放行 'self') */
            if (
              lib.css &&
              !document.querySelector(`link[data-fx-css="${name}"]`)
            ) {
              const lk = document.createElement("link");
              lk.rel = "stylesheet";
              lk.href = lib.css;
              lk.dataset.fxCss = name;
              if (FX_NONCE) lk.nonce = FX_NONCE;
              document.head.appendChild(lk);
            }
            const s = document.createElement("script");
            s.src = lib.js;
            s.async = true;
            if (FX_NONCE) s.nonce = FX_NONCE;
            s.dataset.fxJs = name;
            s.onerror = () =>
              reject(new Error(lib.label + " 加载失败:" + lib.js));
            s.onload = () => {
              if (name !== "mathjax") {
                return lib.ready()
                  ? resolve()
                  : reject(new Error(lib.label + " 已加载但未挂载到 window"));
              }
              /* MathJax:轮询 startup,最多等 10 s(正常几十毫秒内完成) */
              const t0 = Date.now();
              const check = () => {
                if (lib.ready()) return resolve();
                if (Date.now() - t0 > 10000)
                  return reject(new Error("MathJax 启动超时"));
                setTimeout(check, 50);
              };
              check();
            };
            document.head.appendChild(s);
          });
          fxLoading[name] = p;
          p.catch(() => {
            fxLoading[name] = null;
          }); /* 失败后允许重试 */
          return p;
        }

        /* 单条公式渲染。成功加 .fx-rendered;失败清空、加 .fx-error、抛给调用方计数。
   两条引擎路径都返回 Promise,调用方按顺序 await,避免同一列内多引擎并发造成重排。 */
        async function renderFormula(el, latex, engine) {
          el.classList.remove("fx-rendered", "fx-error");
          if (!latex || !latex.trim()) return; /* 空 latex 视为"空",不渲染 */
          if (engine === "katex") {
            try {
              katex.render(latex, el, {
                displayMode: true,
                throwOnError: true,
                strict: "ignore",
                output: "html",
              });
              el.classList.add("fx-rendered");
            } catch (e) {
              el.textContent = latex;
              el.classList.add("fx-error");
              throw e;
            }
            return;
          }
          if (engine === "mathjax") {
            const MJ = window.MathJax;
            try {
              /* 先等 startup 就绪。startup.promise 会 resolve;a11y 语音的 blob worker
                 被 CSP(worker-src 未设→回落 script-src)拦下并不影响这里——它只关掉
                 屏幕朗读,不拦视觉 SVG。 */
              if (MJ.startup && MJ.startup.promise) {
                try {
                  await MJ.startup.promise;
                } catch (_) {
                  /* startup 报错也继续往下试同步 API */
                }
              }
              /* v4 常规公式走**同步** tex2svg,立即产出 <mjx-container><svg>;只有它抛
                 “MathJax retry — asynchronous action required”(需按需加载扩展包)时,
                 才回退到异步 tex2svgPromise。异步链依赖 rAF,隐藏标签页里会挂起,所以同步优先。
                 我们只发 tex-svg(SVG 自包含、不需额外 web 字体),因此不再保留 chtml 分支。 */
              let node = null;
              if (typeof MJ.tex2svg === "function") {
                try {
                  node = MJ.tex2svg(latex, { display: true });
                } catch (_) {
                  node = null;
                }
              }
              if (!node && typeof MJ.tex2svgPromise === "function") {
                node = await MJ.tex2svgPromise(latex, { display: true });
              }
              if (!node) throw new Error("MathJax 未产出可渲染节点");
              el.replaceChildren(node);
              el.classList.add("fx-rendered");
            } catch (e) {
              el.textContent = latex;
              el.classList.add("fx-error");
              throw e;
            }
          }
        }

        /* 序列号:快速连续切换引擎时,旧一轮渲染要么在新一轮开始前看到 seq 变化而提前退出,
   要么在新一轮重置 .fx-slot 之后写入——两者都不会把旧引擎的结果残留到新引擎上。 */
        let fxRenderSeq = 0;
        async function applyFormulaRender() {
          const seq = ++fxRenderSeq;
          const slots = document.querySelectorAll(".fx-slot");
          if (!slots.length) return;
          const mode = state.fx.mode;
          /* 先把所有槽位重置为 LaTeX 原文(可重入、可回退),再按需加载与渲染 */
          slots.forEach((el) => {
            el.classList.remove("fx-rendered", "fx-error");
            el.textContent = el.dataset.latex || "";
          });
          if (mode === "off") return;
          try {
            await loadFxLibrary(mode);
          } catch (err) {
            if (seq !== fxRenderSeq) return;
            toast(err.message + " — 公式以 LaTeX 原文显示", "err", "alert");
            const hint = $("fxRenderHint");
            if (hint) hint.textContent = err.message;
            return;
          }
          if (seq !== fxRenderSeq) return;
          const hint = $("fxRenderHint");
          if (hint)
            hint.textContent = "已启用 " + FX_LIBS[mode].label + "(同源加载)";
          for (const el of slots) {
            if (seq !== fxRenderSeq) return;
            const latex = el.dataset.latex || "";
            if (!latex) continue;
            try {
              await renderFormula(el, latex, mode);
            } catch (e) {
              /* 单条失败:原文已经在 DOM 里,不再逐条 toast(诊断面板依然能看到契约层错误) */
            }
          }
        }
        /* 工具条服务于**两种**区域,但语义不同(E16.3.5):
   · 有公式区域 → 三态引擎选择(原文 / KaTeX / MathJax)可用;
   · 只有表格区域 → 表格只有**一种**呈现(净化后的真实 HTML),没有引擎可选,
     三个按钮隐藏、文案改成"表格渲染";渲染由**每个表格自己的**按钮触发(E24)。
   两者同时存在时工具条仍服务于公式(表格不受引擎选择影响)。 */
        function updateFxBarUI() {
          const bar = $("fxRenderBar");
          if (!bar) return;
          const regions = (state.result && state.result.regions) || [];
          const hasFormula = regions.some((r) => r.kind === "formula");
          bar.querySelectorAll("[data-fx-mode]").forEach((b) => {
            b.hidden = !hasFormula;
            b.setAttribute(
              "aria-pressed",
              b.dataset.fxMode === state.fx.mode ? "true" : "false",
            );
          });
          const label = bar.querySelector(".fxr-txt");
          if (label) label.textContent = hasFormula ? "公式渲染" : "表格渲染";
          const hint = $("fxRenderHint");
          if (hint)
            hint.textContent = hasFormula
              ? "首次切换会从同源路径懒加载所选引擎"
              : "点每个表格区域的「渲染表格」按钮就地渲染(先过白名单净化)";
        }
        $("fxRenderBar").addEventListener("click", (e) => {
          const btn = e.target.closest("[data-fx-mode]");
          if (!btn) return;
          const mode = btn.dataset.fxMode;
          if (mode === state.fx.mode) return;
          state.fx.mode = mode;
          try {
            localStorage.setItem(FX_MODE_KEY, mode);
          } catch {}
          updateFxBarUI();
          applyFormulaRender();
        });
        /* 状态初始化:从 localStorage 恢复引擎选择(默认 'off',行为与旧版本逐字节相同) */
        (function initFxMode() {
          try {
            const m = localStorage.getItem(FX_MODE_KEY);
            if (m === "katex" || m === "mathjax" || m === "off")
              state.fx.mode = m;
          } catch {}
        })();

        /* ================= 渲染:区域列表(阅读顺序 / 点击↔高亮,§9.2) ================= */
        /* ================= 渲染:区域列表(阅读顺序 / 点击↔高亮,§9.2) =================
   三类区域(RegionKind):text / formula / table。
   · 公式区域额外承担"渲染 LaTeX 界面"的入口:LaTeX 放 data-latex 属性,DOM 初始为原文,
     由 applyFormulaRender() 按需替换(降级路径因此自然成立);
   · 表格区域(E16.3)渲染**净化后**的真实 HTML 表格 + 一条信息条;
   · 被表格消费的页级文本行(sourceLineIndices)默认折叠,展开仍可读。
   工具条只在结果里真的含公式或表格区域时出现(两者都没有 → 不出现,页面保持原状)。 */
        function renderRegions() {
          const wrap = $("regionList");
          const bar = $("fxRenderBar");
          if (!state.result) {
            if (bar) bar.hidden = true;
            wrap.innerHTML = `<div class="empty-inline">${ic("scan")}<p>识别完成后,区域将按阅读顺序在此列出;<br>点击列表项可在图像上定位高亮,点击图中区域可反向定位。</p></div>`;
            return;
          }
          const regions = state.result.regions;
          const hasFormula = regions.some((r) => r.kind === "formula");
          const hasTable = regions.some((r) => r.kind === "table");
          if (bar) {
            bar.hidden = !(hasFormula || hasTable);
            if (hasFormula || hasTable) updateFxBarUI();
          }
          /* 被表格消费的页级文本行(E16.3.4):服务端**保留**这些区域(阅读顺序与 polygon
     语义都靠它们),页面默认把它们折叠起来并标注"已归入表格 N"。同一行被多张表消费时
     记第一张 —— 表格之间不共享单元格文本,后来的引用是重复引用。 */
          const consumedBy = new Map();
          regions.forEach((r, i) => {
            if (r.kind === "table" && r.table)
              r.table.sourceLineIndices.forEach((n) => {
                if (!consumedBy.has(n)) consumedBy.set(n, i + 1);
              });
          });
          wrap.innerHTML = regions
            .map((r, i) => {
              const conf =
                r.conf != null
                  ? (r.conf > 1 ? r.conf : r.conf * 100).toFixed(1) + "%"
                  : "—";
              const poly = r.polygon
                ? r.polygon
                    .map((p) => Math.round(p[0]) + "," + Math.round(p[1]))
                    .join(" ")
                : "";
              const bb = r.polygon
                ? (() => {
                    const xs = r.polygon.map((p) => p[0]),
                      ys = r.polygon.map((p) => p[1]);
                    return `${Math.round(Math.min(...xs))},${Math.round(Math.min(...ys))} → ${Math.round(Math.max(...xs))},${Math.round(Math.max(...ys))}`;
                  })()
                : "—";
              if (r.kind === "table") return tableRegionHtml(r, i, poly, bb);
              const isFx = r.kind === "formula";
              /* 公式区域:原文放 data-latex(esc 后仍能被 dataset 还原),DOM 初始显示原文,
       渲染引擎就绪后由 applyFormulaRender 替换;文本区域保持旧结构不变。 */
              const textCell = isFx
                ? `<span class="ri-text fx-slot" data-latex="${esc(r.text)}">${esc(r.text) || "(空)"}</span>`
                : `<span class="ri-text">${esc(r.text) || "(空)"}</span>`;
              const owner = consumedBy.get(i);
              const row = `<button class="region-item${owner ? " ri-folded" : ""}" data-i="${i}" aria-pressed="false" ${poly ? `title="polygon: ${esc(poly)}"` : ""}>

      <span class="ri-idx">${String(i + 1).padStart(2, "0")}</span>

      <span class="ri-body">

        <span class="ri-line">

          <i class="tag ${isFx ? "tag-fx" : "tag-txt"}">${isFx ? "公式" : "文本"}</i>

          ${textCell}

          ${owner ? `<i class="tag tag-tbl-in">已归入表格 ${owner}</i>` : ""}

        </span>

        <span class="ri-sub">conf ${conf} · ${bb}</span>

      </span>

    </button>`;
              if (!owner) return row;
              /* 折叠态:按钮本身仍可点(定位高亮照旧),展开用**兄弟** details ——
        details 是交互内容,不能嵌在 button 里。 */
              return `<div class="ri-fold-wrap">${row}<details class="ri-fold"><summary>展开原文</summary><div class="ri-fold-body">${esc(r.text) || "(空)"}</div></details></div>`;
            })
            .join("");
          /* 表格的 HTML 原文与"待渲染的文本"同源:原文行从 data-table-html 写回
     (getAttribute 拿回的是**未转义**的原文)。两份会分叉,所以 DOM 里只留属性一份。 */
          wrap.querySelectorAll(".region-table [data-table-html]").forEach((btn) => {
            const body = btn.closest(".ri-body");
            const code = body && body.querySelector(".rt-raw > code");
            if (code) code.textContent = btn.getAttribute("data-table-html") || "";
          });
          if (hasFormula) applyFormulaRender();
        }

        /* 一张表格区域的卡片(E16.3.3)。信息条里的 low 必须**文字可见地**标注:
   它表示逻辑网格有空洞或被截断(表格仍然被完整产出),把两者都当"成功"是不允许的。
   嵌入的 HTML 一律先过 sanitizeTableHtml()(门禁 G8)——表格 HTML 是**模型产物**。
   E24:默认**不渲染**,只显示 HTML 原文 + 一个「渲染表格」按钮(与公式"默认原文、
   按需渲染"同构)。点击才由 toggleTableRender() 走净化入口把表格放进 .rt-wrap。
   原文与待渲染文本是**同一份**:只存在于按钮的 data-table-html 属性里(esc 后仍能被
   getAttribute 还原),原文行由 renderRegions() 写进去——两份会分叉。 */
        function tableRegionHtml(r, i, poly, bb) {
          const t = r.table || {};
          const cells = Array.isArray(t.cells) ? t.cells : [];
          const low = t.confidence === "low";
          const badge = low
            ? "低置信(网格空洞或截断)"
            : t.confidence === "high"
              ? "高置信"
              : "置信未知";
          const grid =
            t.rows != null && t.cols != null
              ? `${t.rows} × ${t.cols}`
              : "网格未知";
          const matched = cells.filter(
            (c) => c && (c.match_kind === "single" || c.match_kind === "multiple"),
          ).length;
          const degen =
            Array.isArray(t.degradations) && t.degradations.length
              ? t.degradations.map(degradationText).join(";")
              : "无降级";
          const consumed = Array.isArray(t.sourceLineIndices)
            ? t.sourceLineIndices.length
            : 0;
          const html = typeof t.html === "string" ? t.html : "";
          return `<div class="region-item region-table${low ? " rt-low" : ""}" data-i="${i}" aria-pressed="false" ${poly ? `title="polygon: ${esc(poly)}"` : ""}>

      <span class="ri-idx">${String(i + 1).padStart(2, "0")}</span>

      <span class="ri-body">

        <span class="ri-line">

          <i class="tag tag-tbl">表格</i>

          <span class="ri-text">${esc(grid)} · ${cells.length} 单元格</span>

          <i class="rt-badge${low ? " rt-badge-low" : ""}">${esc(badge)}</i>

        </span>

        <span class="ri-sub">空洞 ${t.holes != null ? t.holes : "—"} · 匹配到文本 ${matched} 格 · 归入本表 ${consumed} 行 · ${esc(degen)} · ${bb}</span>

        <div class="rt-actions">

          <button class="rt-btn" type="button" data-table-render="1" data-rendered="0" aria-expanded="false" data-table-html="${esc(html)}">渲染表格</button>

          <span class="rt-hint">渲染前先过白名单净化</span>

        </div>

        <div class="rt-wrap" hidden></div>

        <pre class="rt-raw" aria-label="表格 HTML 原文"><code></code></pre>

      </span>

    </div>`;
        }

        /* 表格渲染按钮(E24)。渲染是**惰性**的:点击才把净化后的表格放进 .rt-wrap,
   再点一次收回(并清空 DOM,让大表不常驻)。净化仍是唯一入口 —— 这里只能用
   sanitizeTableHtml(),绝不把 data-table-html 直接赋给 innerHTML。 */
        function toggleTableRender(btn) {
          const card = btn.closest(".region-table");
          if (!card) return;
          const wrap = card.querySelector(".rt-wrap");
          if (!wrap) return;
          const raw = card.querySelector(".rt-raw");
          const rendered = btn.getAttribute("data-rendered") === "1";
          if (rendered) {
            wrap.innerHTML = "";
            wrap.hidden = true;
            if (raw) raw.hidden = false;
            btn.setAttribute("data-rendered", "0");
            btn.setAttribute("aria-expanded", "false");
            btn.textContent = "渲染表格";
            return;
          }
          wrap.innerHTML = sanitizeTableHtml(btn.getAttribute("data-table-html") || "");
          wrap.hidden = false;
          if (raw) raw.hidden = true;
          btn.setAttribute("data-rendered", "1");
          btn.setAttribute("aria-expanded", "true");
          btn.textContent = "收起表格";
        }

        /* ================= 复制到剪贴板(§9.6:稳健 + 失败可见) =================
   在真实点击手势的同步上下文里,先用 textarea + execCommand(无焦点的内嵌 webview
   也能成功,且此刻瞬时用户激活尚未被 await 消耗);再退回异步 Clipboard API(前台有焦点
   时更规范)。两条都不成才报“复制失败”,绝不静默失败。逐元素 style 走 CSSOM,不受
   style-src 约束;创建的 textarea 不是 style/link,nonce 垫片不会碰它。 */
        async function copyTextToClipboard(text) {
          if (!text) return false;
          const syncCopy = () => {
            let ta;
            try {
              ta = document.createElement("textarea");
              ta.value = text;
              ta.setAttribute("readonly", "");
              ta.style.position = "fixed";
              ta.style.top = "-1000px";
              ta.style.opacity = "0";
              document.body.appendChild(ta);
              ta.focus();
              ta.select();
              ta.setSelectionRange(0, ta.value.length);
              return document.execCommand("copy");
            } catch (_) {
              return false;
            } finally {
              if (ta) ta.remove();
            }
          };
          if (syncCopy()) return true;
          try {
            if (navigator.clipboard && navigator.clipboard.writeText) {
              await navigator.clipboard.writeText(text);
              return true;
            }
          } catch (_) {}
          return false;
        }
        /* “复制全文”的正文:按阅读顺序拼接每个区域的文本。公式区域的 .text 就是它的
           LaTeX(normalizeResult 已将 formula.latex 存入 .text),因此全文天然含公式;
           纯文本结果时与旧的 plain_text 等价。服务端 plain_text 只含文本通道(公式被抹白),
           直接用它会丢公式,所以这里从 regions 重建。
           表格区域(E16.3.7)插入 TableOutcome.markdown(纯文本出口里它比 HTML 合适);
           被表格消费的页级文本行**跳过**,否则同一段文字会出现两次、第二次还脱离表格上下文。 */
        function fullTextForCopy() {
          const res = state.result;
          if (!res) return "";
          if (Array.isArray(res.regions) && res.regions.length) {
            const regions = res.regions;
            const consumed = new Set();
            regions.forEach((r) => {
              if (r && r.kind === "table" && r.table)
                r.table.sourceLineIndices.forEach((n) => consumed.add(n));
            });
            const parts = [];
            regions.forEach((r, i) => {
              if (!r) return;
              if (r.kind === "table") {
                const md = (r.table && r.table.markdown) || "";
                if (md.trim() !== "") parts.push(md.trim());
                return;
              }
              if (consumed.has(i)) return;
              if (r.text) parts.push(r.text);
            });
            if (parts.length) return parts.join("\n");
          }
          return res.plain || "";
        }

        $("copyAllBtn").addEventListener("click", async () => {
          if (!state.result) return;
          const ok = await copyTextToClipboard(fullTextForCopy());
          toast(
            ok ? "全文已复制到剪贴板" : "复制失败,请手动选择文本",
            ok ? "ok" : "err",
            ok ? "copy" : "alert",
          );
        });

        /* 列表项 → 图像高亮的**反向**定位(§9.2)。这个方向必须自己接:canvas 的单击只处理
           "图上点中区域",而列表项的按钮除双击复制 LaTeX 外没有处理器 —— 于是
           data-i 从来没被读过,"点击列表项定位高亮"实际不工作(本轮补上)。
           用事件委托:regionList 的内容每次渲染都被整体替换,逐项绑定会漏。
           点进渲染出的表格里时不切换选中态 —— 用户多半在选单元格文字。
           表格区域的「渲染表格」按钮在更早处拦掉:它是卡片内的交互,不能被当成选中区域。 */
        $("regionList").addEventListener("click", (e) => {
          const tbtn = e.target.closest("[data-table-render]");
          if (tbtn) {
            toggleTableRender(tbtn);
            return;
          }
          const item = e.target.closest(".region-item");
          if (!item) return;
          if (e.target.closest(".rt-wrap")) return;
          const i = Number(item.getAttribute("data-i"));
          if (!Number.isInteger(i) || i < 0) return;
          selectRegion(state.selected === i ? -1 : i);
        });
        /* 双击公式行 → 复制该条 LaTeX。渲染后 fx-slot 的 textContent 为空(SVG/KaTeX 标记),
           原文只在 data-latex 里,因此直接读属性;文本行没有 fx-slot,不响应双击(交回原有单击定位)。 */
        $("regionList").addEventListener("dblclick", async (e) => {
          const item = e.target.closest(".region-item");
          if (!item) return;
          const slot = item.querySelector(".fx-slot");
          if (!slot) return;
          const latex =
            slot.getAttribute("data-latex") || slot.textContent || "";
          if (!latex.trim()) return;
          const ok = await copyTextToClipboard(latex);
          toast(
            ok ? "公式 LaTeX 已复制" : "复制失败,请手动选择文本",
            ok ? "ok" : "err",
            ok ? "copy" : "alert",
          );
        });

        /* ================= 下载标注图 / 导出(blob 附件,§4.2) ================= */
        $("annotatedBtn").addEventListener("click", async () => {
          const j = state.job;
          if (!state.result || !j) return;
          if (DEMO) {
            demoAnnotated();
            return;
          }
          try {
            const b = await apiBlob("/api/jobs/" + j.id + "/annotated.png");
            saveBlob(b, "ocr-" + j.id + "-annotated.png");
            toast("标注图已保存", "ok", "download");
          } catch (e) {
            toastErr(e);
          }
        });
        const EXPORTS = { expJson: "json", expMd: "md", expHtml: "html" };
        Object.keys(EXPORTS).forEach((id) => {
          $(id).addEventListener("click", () => exportAs(EXPORTS[id]));
        });
        async function exportAs(fmt) {
          const j = state.job;
          if (!state.result || !j) return;
          if (DEMO) {
            demoExport(fmt);
            return;
          }
          try {
            const b = await apiBlob(`/api/jobs/${j.id}/export?format=${fmt}`);
            saveBlob(b, `ocr-${j.id}.${fmt}`);
            toast(fmt.toUpperCase() + " 导出已保存", "ok", "download");
          } catch (e) {
            toastErr(e);
          }
        }

        /* ================= 评估(M4:POST /api/evaluate,复用库的 evaluation) =================
   服务端返回的就是 `rapidstruct evaluate` 的那份报告(库的 EvaluationSummary + 运行时四字段),
   因此这里的字段名与 CLI 报告逐字段相同:cases[].{image,cer,exact_text,...}、
   mean_cer、exact_match_rate、iou_threshold、ort_runtime…。前端只排版、不重算指标。 */
        function fmtPct(v) {
          return typeof v === "number" ? (v * 100).toFixed(1) + "%" : "—";
        }
        function fmtNum(v, d) {
          return typeof v === "number" ? v.toFixed(d == null ? 4 : d) : "—";
        }
        function renderEvaluation(rep) {
          const out = $("evalOut");
          out.hidden = false;
          const cases = Array.isArray(rep.cases) ? rep.cases : [];
          out.innerHTML =
            `<p class="eval-sum"><b>均值 CER</b> ${fmtNum(rep.mean_cer)} · ` +
            `<b>精确匹配</b> ${fmtPct(rep.exact_match_rate)} · ` +
            `<b>用例</b> ${cases.length} · <b>IoU 阈值</b> ${fmtNum(rep.iou_threshold, 2)} · ` +
            `清单 <code>${esc(rep.manifest_file || "—")}</code></p>` +
            `<table class="diag-table">

       <tr><td>#</td><td>图像</td><td>CER</td><td>精确</td></tr>` +
            cases
              .map(
                (c, i) =>
                  `<tr><td>${i + 1}</td><td title="${esc(c.image || "")}">${esc((c.image || "").split(/[\\/]/).pop())}</td>` +
                  `<td>${fmtNum(c.cer)}</td><td>${c.exact_text === true ? "是" : "否"}</td></tr>`,
              )
              .join("") +
            `</table>

     <p class="diag-note">指标由服务端复用库的 <code>evaluation</code> 计算(字符错误率 = 编辑距离 ÷ 参考长度;

     精确匹配按空白归一化后比较),与 <code>rapidstruct evaluate --manifest</code> 的报告同源同字段。

     一次请求最多评估 <code>--max-eval-cases</code> 张图(默认 32,见 /api/status 的 limits)。</p>`;
        }
        async function runEvaluation() {
          if (DEMO) {
            toast(
              "离线预览模式不执行评估:请用 rapidstruct serve 打开本页,并在输入框填入清单路径",
              "err",
              "info",
            );
            return;
          }
          const path = ($("evalPath").value || "").trim();
          const btn = $("evalBtn");
          const out = $("evalOut");
          if (!path) {
            toast(
              "请先填入已标注清单的绝对路径(rapidstruct evaluate --manifest 的格式)",
              "err",
              "info",
            );
            return;
          }
          btn.disabled = true;
          out.hidden = false;
          out.innerHTML = `<p class="eval-sum">${ic("loader", "spin")} 评估中…(每张图一次完整推理,最多 --max-eval-cases 张)</p>`;
          try {
            const rep = await apiSendJson("POST", "/api/evaluate", {
              manifest: path,
            });
            renderEvaluation(rep);
            toast(`评估完成 · 均值 CER ${fmtNum(rep.mean_cer)}`, "ok");
          } catch (e) {
            out.hidden = true;
            out.innerHTML = "";
            /* detail.reason 是可定位的原因(清单读不出来 / 用例超限 / 图读不出来),原样显示。 */
            const reason = e && e.body && e.body.detail && e.body.detail.reason;
            if (reason) toast(reason, "err", "alert");
            else toastErr(e);
          } finally {
            btn.disabled = false;
          }
        }
        $("evalBtn").addEventListener("click", runEvaluation);
        $("evalPath").addEventListener("keydown", (e) => {
          if (e.key === "Enter") runEvaluation();
        });

        /* 详细模式开关(诊断面板里的复选框)。`renderDiag` 每次重写 innerHTML,
   因此用事件委托而不是逐个绑定(页面其余列表用的是同一手法)。 */
        $("diagBody").addEventListener("change", (e) => {
          if (e.target && e.target.id === "flowToggle")
            setFlowVerbose(!!e.target.checked, true);
        });
        $("diagBody").addEventListener("click", (e) => {
          if (e.target && e.target.id === "flowToggle")
            e.stopPropagation(); /* 不要把 <details> 收起 */
        });

        /* ================= 渲染:诊断面板(复用 timings / 指纹,不重新测量,§7.5/§10.6) ================= */
        /* 诊断面板顶部永远先渲染契约错误:字段缺失/改名在这里留痕,
   与 toast 一起构成"可见 + 可查"的两条路径(P2-2)。
   注意即使 state.result 为 null(解析失败)也必须显示这些错误,否则用户只剩一个 toast。 */
        function diagContractHtml() {
          if (!state.diag.length) return "";
          return `<div class="diag-sec">契约错误 · 响应字段</div>

    <p class="diag-line">${state.diag.map((x) => esc(x)).join("<br>")}</p>

    <p class="diag-note">前端按 src/api.rs 的冻结契约解析响应,不做别名兼容:字段被改名或缺失时

    一律在此点名路径并拒绝渲染,避免把后端改名悄悄吞掉。</p>`;
        }
        function renderDiag() {
          const d = $("diagBody");
          const head = diagContractHtml();
          /* "最近请求"永远排在最前:报告者要的是"什么都没渲染时不用打开 devtools",
     而诊断面板本来就是唯一常驻的可查处(§9.2)。 */
          const flow = flowHtml();
          if (!state.result) {
            d.innerHTML =
              head +
              flow +
              '<p class="diag-line">识别完成后,此处展示逐阶段耗时(时间账本)与运行时指纹。</p>';
            return;
          }
          const t = state.result.timings;
          const rows = Object.entries(t).filter(
            ([k, v]) =>
              typeof v === "number" && k !== "total_ms" && k !== "total",
          );
          const total =
            t.total_ms != null
              ? t.total_ms
              : t.total != null
                ? t.total
                : rows.reduce((a, [, v]) => a + v, 0);
          const s = state.status || emptyStatus();
          const fp = s.fingerprint;
          d.innerHTML =
            head +
            flow +
            `<div class="diag-sec">逐阶段耗时(MS)</div>

     <table class="diag-table">${rows
       .map(([k, v]) => `<tr><td>${esc(k)}</td><td>${v.toFixed(1)}</td></tr>`)
       .join("")}

       <tr class="total"><td>total</td><td>${total.toFixed(1)}</td></tr>

     </table>` +
            ledgerHtml() +
            `<div class="diag-sec">PROVIDER 实测</div>

     <p class="diag-line">requested ${esc(s.requested || "未知")} · selected_ep ${esc(s.selected_ep || "未知")}` +
            (s.fallback === true
              ? " · 已回退 CPU"
              : s.fallback === false
                ? " · 未回退"
                : " · 回退状态未知") +
            ` — 本页任务的实测耗时见上表。</p>` +
            (fp
              ? `<div class="diag-sec">ORT 指纹</div>

       <p class="diag-line">${esc(fp.file || "")}${fp.size_bytes ? " · " + fmtBytes(fp.size_bytes) : ""}` +
                (fp.sha256
                  ? " · sha256 " + esc(String(fp.sha256).slice(0, 16)) + "…"
                  : "") +
                "</p>"
              : "") +
            `<div class="diag-sec">运行时与内存</div>

      <p class="diag-line">ORT ${esc(s.ort || "—")} · 峰值工作集 ${s.memory != null ? fmtBytes(s.memory) : "—"}` +
            (s.memorySource ? `(来源:${esc(s.memorySource)})` : "") +
            "</p>" +
            `<p class="diag-note">口径说明:以上数据来自引擎内建 timings / stages、库的时间账本与 ORT 指纹,前端不重新测量;

      provider 名称不构成性能结论,请以实测耗时为准。账本的占比只在<b>口径残差</b>的量级内成立,

      残差的含义以下方库原文为准。</p>`;
        }

        /* 时间账本(库的 TimingLedger):命名分量 + 口径残差 + **库自己写的**解释文案。
   刻意把 interpretation 原文展示出来——"两个窗口串行、不是重复计时""账本不是严格划分"
   这些话只有库写得准确,前端自己拼一句"仅供参考"会丢掉可核对的口径(§10.6、M3)。 */
        function ledgerHtml() {
          const l = state.result && state.result.ledger;
          if (!l) return "";
          const c = l.conservation || {};
          const named = [
            "total_ms",
            "attributed_ms",
            "input_ms",
            "inference_ms",
            "rust_ms",
            "unattributed_ms",
          ]
            .filter((k) => typeof l[k] === "number")
            .map(
              (k) => `<tr><td>${esc(k)}</td><td>${l[k].toFixed(1)}</td></tr>`,
            )
            .join("");
          const residual =
            typeof c.residual_ms === "number" ? c.residual_ms.toFixed(6) : "—";
          const excess =
            typeof c.excess_ms === "number" ? c.excess_ms.toFixed(6) : "—";
          const tol =
            typeof c.tolerance_ms === "number"
              ? c.tolerance_ms.toFixed(6)
              : "—";
          const verdict =
            c.conserved === true
              ? "守恒(在容差内)"
              : "不守恒(口径差异,不是总量算错)";
          return `<div class="diag-sec">时间账本 · 口径残差(MS,库数据)</div>

    <table class="diag-table">${named}

      <tr><td>residual_ms = attributed − total</td><td>${residual}</td></tr>

      <tr><td>excess_ms = max(0, −residual)</td><td>${excess}</td></tr>

      <tr><td>tolerance_ms</td><td>${tol}</td></tr>

    </table>

    <p class="diag-line">${esc(verdict)}</p>

    <p class="diag-note">${esc(typeof c.interpretation === "string" ? c.interpretation : "(服务端未提供账本解释文案)")}</p>`;
        }

        /* ================= 真实模式:status / models 轮询 ================= */
        function statusOnce() {
          return apiJson("GET", "/api/status")
            .then((s) => {
              state.netFail = false;
              state.status = normalizeStatus(s);
              renderEngine();
              renderPill();
            })
            .catch((e) => {
              state.netFail = true;
              state.status = emptyStatus("failed");
              renderEngine();
              renderPill();
            });
        }
        function statusLoop() {
          statusOnce()
            .then(() => {
              setTimeout(
                statusLoop,
                state.status.state === "ready" ? 8000 : 2000,
              );
            })
            .catch(() => setTimeout(statusLoop, 5000));
        }
        function refreshModels() {
          if (DEMO) {
            renderBanner();
            renderButton();
            renderModeRow();
            renderEngine();
            return Promise.resolve();
          }
          return apiJson("GET", "/api/models")
            .then((m) => {
              state.models = normalizeModels(m);
              /* 模型集状态一变,三处结论都要跟着重算:横幅(按集合下载)、提交门禁(文本队列)、
       公式开关(公式队列)——公式缺失不得阻塞文本队列,反之亦然。 */
              renderBanner();
              renderButton();
              renderModeRow();
              renderEngine();
            })
            .catch((e) => {
              state.models = { error: e };
              renderBanner();
              renderButton();
              renderModeRow();
              renderEngine();
            });
        }

        /* ================================================================
   离线预览模式(占位符未被 serve 替换时启用,页面顶部有常驻标识)
   ================================================================ */
        function demoStatusData() {
          const ready = demo.phase === "ready";
          const ph = demoPhaseFromModels();
          return {
            engine: {
              state:
                ph === "waitmodels"
                  ? "waiting_models"
                  : ph === "building"
                    ? "loading"
                    : ph === "ready"
                      ? "ready"
                      : "loading",
            },
            /* §7.5 三字段必须齐全。离线预览刻意给一个真实场景:请求 directml 但会话回退到 CPU,
       以便直接看到回退高亮、警示文案与"已回退 CPU"标签(缺失字段则渲染为「未知」)。 */
            provider: {
              requested: "directml",
              selected_ep: "CPUExecutionProvider",
              fallback_to_cpu: true,
            },
            ort: { version: "1.20.1", fingerprint: null },
            memory: { peak_working_set_bytes: ready ? 537395200 : 81234567 },
            queues: {
              text: {
                used: state.job && state.job.state === "queued" ? 1 : 0,
                capacity: 4,
              },
              formula: { used: 0, capacity: 2 },
            },
          };
        }
        function demoSetStatus() {
          state.status = normalizeStatus(demoStatusData());
          renderEngine();
          renderPill();
        }
        /* 演示数据里的计划行(与 /api/models 的 `pipelines.*.plan[]` 同形,E16.1.3/E22)。 */
        function planRow(name, role, state, pipeline) {
          return {
            name: name,
            role: role,
            state: state,
            pipeline: pipeline,
            declared_sha256: null,
            has_declared_digest: false,
          };
        }
        function demoInitialModels() {
          /* 离线预览必须能看出"文本就绪 / 公式缺失"这个区分,因此刻意给两个集合:
       · PP-OCRv5(演示)        → **齐备**(detector + recognizer + dictionary 全 present)
       · PP-FormulaNet(演示)   → **不齐备**(约 566 MiB 公式模型 missing,且带 source_url)
     与 docs/05 一致:公式模型默认不下载(§10.8),普通 OCR 不依赖它(M4 公式独立)。 */
          return normalizeModels({
            model_dir: "<redacted>",
            source: "default_table",
            downloads_allowed: true,
            /* M4:顶层字段是**文本管线**作用域;公式管线单独一块。 */
            complete: true,
            missing: [],
            corrupt: [],
            blocked: [],
            formula: {
              complete: false,
              missing: ["pp_formulanet_plus_m.onnx"],
              corrupt: [],
              blocked: [],
              routing: true,
              disabled_reason: null,
              required_roles: ["formula_recognizer"],
              detector: { configured: true, file: "pix2text-mfd-1.5.onnx" },
            },
            /* 表格管线(E16.2/E22):**结构模型不在任何集合里** —— 真实服务里它由
      `--table-model` 从模型目录之外指定,所以演示数据也必须长这样,否则离线预览
      恰好演示不出"集合里没有这个角色但路由可用"这条(E22 的缺陷就是被它掩盖的)。 */
            table: {
              complete: true,
              missing: [],
              corrupt: [],
              blocked: [],
              routing: true,
              disabled_reason: null,
              in_plan: true,
              required_roles: ["table_structure"],
              structure: {
                configured: true,
                file: "slanet-plus.onnx",
                sha256: null,
                state: "present",
              },
            },
            /* 模型计划(E16.1.3):三条管线各自"哪个文件被哪条管线用",页面只呈现。
      表格那行没有归属集合 → 计划表里显示"命令行指定"(与真实服务同一口径)。 */
            pipelines: {
              text: {
                pipeline: "text",
                complete: true,
                in_plan: true,
                routing: true,
                plan: [
                  planRow("PP-OCRv5_server_det.onnx", "detector", "present", "text"),
                  planRow("PP-OCRv5_server_rec.onnx", "recognizer", "present", "text"),
                  planRow("ppocrv5_dict.txt", "dictionary", "present", "text"),
                ],
              },
              formula: {
                pipeline: "formula",
                complete: false,
                in_plan: true,
                routing: true,
                plan: [
                  planRow(
                    "pp_formulanet_plus_m.onnx",
                    "formula_recognizer",
                    "missing",
                    "formula",
                  ),
                  planRow(
                    "pix2text-mfd-1.5.onnx",
                    "formula_detector",
                    "present",
                    "formula",
                  ),
                ],
              },
              table: {
                pipeline: "table",
                complete: true,
                in_plan: true,
                routing: true,
                plan: [
                  planRow(
                    "slanet-plus.onnx",
                    "table_structure",
                    "present",
                    "table",
                  ),
                ],
              },
            },
            sets: [
              {
                id: "PP-OCRv5(演示)",
                complete: true,
                download_bytes_total: 0,
                files: [
                  {
                    name: "PP-OCRv5_server_det.onnx",
                    role: "detector",
                    state: "present",
                    size_bytes: 4940000,
                    sha256: "8f3ac21d90e…",
                    source_url:
                      "https://paddleocr.bj.bcebos.com/PP-OCRv5/server/det.onnx",
                  },
                  {
                    name: "PP-OCRv5_server_rec.onnx",
                    role: "recognizer",
                    state: "present",
                    size_bytes: 8010000,
                    sha256: "c71b0f4a22e…",
                    source_url:
                      "https://paddleocr.bj.bcebos.com/PP-OCRv5/server/rec.onnx",
                  },
                  {
                    name: "ppocrv5_dict.txt",
                    role: "dictionary",
                    state: "present",
                    size_bytes: 126469,
                    sha256: "a2d9c8e710b…",
                    source_url:
                      "https://paddleocr.bj.bcebos.com/PP-OCRv5/server/dict.txt",
                  },
                ],
              },
              {
                id: "PP-FormulaNet(演示)",
                complete: false,
                download_bytes_total: 593916167,
                files: [
                  {
                    name: "pp_formulanet_plus_m.onnx",
                    role: "formula_recognizer",
                    state: "missing",
                    size_bytes: 593916167,
                    sha256: "6e509ec4b7cda604dc9bf80a876ae6494693deea4c7f4157a4dc0eba0ebda745",
                    source_url:
                      "https://www.modelscope.cn/seeyuer/pp-formulanet-plus-m-optimized/resolve/0bb8154e3583d24613eaa74448de43ecf4ae73ec/pp_formulanet_plus_m.onnx",
                  },
                ],
              },
            ],
          });
        }
        /* 演示模式的引擎相位由**文本集合是否齐备**决定(与真实模式同一判据),
   因此公式集合缺失不会把引擎状态压成 waiting_models。 */
        function demoPhaseFromModels() {
          if (demo.phase === "boot") return "boot";
          if (demo.phase === "building") return "building";
          const t = modelsReadyFor("text");
          if (t.fatal || !t.ready) return "waitmodels";
          return demo.phase === "ready" ? "ready" : "waitmodels";
        }
        async function enterDemo() {
          $("demoStrip").hidden = false;
          demo.phase = "boot";
          demoSetStatus();
          await sleep(1100);
          demo.phase = "waitmodels";
          state.models = demoInitialModels();
          demo.textReady = modelsReadyFor("text").ready;
          demoSetStatus();
          renderBanner();
          renderButton();
          renderModeRow();
          /* 离线预览没有服务端:重新校验按钮仍可点(点击后如实解释),但结论区保持为空。 */
          renderVerify();
        }
        /* 离线预览的下载:与真实模式**共用同一套 job 生命周期**——
   先建 job(拿到 job_id),进度来自 job 的 state/elapsed,取消走同一 cancelDownload()。
   下载只作用于被点击的那个集合(setId),绝不落到 sets[0]。 */
        async function demoDownload(setId) {
          const set = state.models.sets.find((s) => s.id === setId);
          if (!set) return toast(`模型集 ${setId} 不存在`, "err", "cloud-off");
          demo.dlActive = true;
          demo.dlSetId = setId;
          const jobId = "demo-dl-" + Math.random().toString(36).slice(2, 8);
          state.dlSetId = setId;
          state.dlJob = {
            id: jobId,
            set_id: setId,
            state: "queued",
            elapsed_ms: 0,
          };
          renderBanner();
          await sleep(300);
          state.dlJob.state = "running";
          const t0 = performance.now();
          for (const f of set.files) {
            if (!state.dlJob) return; /* 已被取消 */
            if (f.state === "present") continue;
            demo.dlFile = f.name;
            let p = 0;
            while (p < 100) {
              if (!state.dlJob) return; /* 文件边界取消(§6.6) */
              p = Math.min(100, p + 2 + Math.random() * 7);
              demo.dlPct = p;
              state.dlJob.elapsed_ms = performance.now() - t0;
              renderBanner();
              await sleep(65);
            }
            f.state = "present";
          }
          demo.dlActive = false;
          demo.dlSetId = null;
          set.complete = set.files.every((f) => f.state === "present");
          set.bytes = set.files
            .filter((f) => f.state !== "present")
            .reduce((a, f) => a + (f.size || 0), 0);
          const finishedId = state.dlJob.id;
          state.dlJob = null;
          state.dlSetId = null;
          demo.textReady = modelsReadyFor("text").ready;
          renderBanner();
          renderButton();
          renderModeRow();
          toast(
            `模型集「${setId}」下载完成(job ${finishedId}),引擎将在下次识别时惰性创建`,
            "ok",
            "package",
          );
          if (modelsReadyFor("text").ready) {
            demo.phase = "building";
            demoSetStatus();
            await sleep(demo.buildMs);
            demo.phase = "ready";
            demoSetStatus();
            renderButton();
            toast(
              `引擎创建完成 · 耗时 ${(demo.buildMs / 1000).toFixed(1)} s`,
              "ok",
            );
          }
        }
        async function demoUpload() {
          state.uploading = true;
          showUp(true);
          setUpProgress(0);
          renderButton();
          drop.classList.add("no-click");
          demo.upAbort = false;
          let p = 0;
          while (p < 100) {
            if (demo.upAbort) break;
            p = Math.min(100, p + 4 + Math.random() * 11);
            setUpProgress(p / 100);
            await sleep(70 + Math.random() * 70);
          }
          state.uploading = false;
          showUp(false);
          drop.classList.remove("no-click");
          renderButton();
          if (demo.upAbort) {
            toast("已取消上传", "err", "info");
            return;
          }
          await sleep(240); /* 模拟 202 往返 */
          clearResult(false);
          /* 离线预览走**同一条**任务生命周期(beginJob / 取消 → endJob),
     因此"动画归谁清"在演示模式与真实模式里是同一个答案。 */
          toast("任务已提交(202)· 文本队列", "ok");
          beginJob(
            {
              job_id: "demo-" + Math.random().toString(36).slice(2, 8),
              kind: "text",
              queue: "text",
              state: "queued",
              position: 1,
            },
            "text",
            false,
          );
          await sleep(850);
          if (!state.job || state.job.state !== "queued")
            return; /* 排队阶段被取消 */
          state.job.state = "running";
          renderJob();
          const t0 = performance.now();
          while (performance.now() - t0 < 2500) {
            if (!state.job || state.job.state !== "running") return;
            state.job.elapsed_ms = performance.now() - t0;
            renderJob();
            await sleep(180);
          }
          state.job.state = "succeeded";
          state.result = demoResult(state.image.w, state.image.h);
          scanOff();
          finishJob();
        }
        /* 区域类型的中文标签。表格区域必须走这里:它的 .text 是空串,用"有公式吗"
           的二分法会把它显示成"文本"(离线预览导出曾经就是这样)。 */
        function regionKindLabel(kind) {
          return kind === "formula" ? "公式" : kind === "table" ? "表格" : "文本";
        }

        /* 演示区域:按上传图实际尺寸的相对布局生成,保证叠框在任何图上都成立。
           表格样例(E16.3.8)覆盖三件事:净化后的真表格渲染、被消费行的折叠标注、
           Markdown 进入"复制全文"。这里刻意给 confidence:"low" + 一个网格空洞,
           好让"低置信必须看得见"在离线预览里也能被眼睛验收。 */
        function demoResult(w, h) {
          const tableLines = [
            ["项目", 0.955],
            ["服务费 1,200.00", 0.948],
            ["税费 80.00", 0.941],
          ];
          const rows = [
            ["发票代码:144032257110", 0.982],
            ["开票日期:2024-06-18", 0.976],
            ["购方名称:本地评估科技有限公司", 0.964],
            ["合计金额(大写)壹仟贰佰捌拾元整", 0.971],
            ["E = mc^{2}", 0.913, "formula"],
            ["备注:本行由离线预览数据填充", 0.887],
            ...tableLines,
          ];
          const box = (i) => {
            const x0 = Math.round(w * 0.1);
            const x1 = Math.round(w * (0.58 + 0.05 * (i % 3)));
            const y0 = Math.round(h * (0.11 + 0.075 * i));
            const y1 = y0 + Math.max(14, Math.round(h * 0.05));
            return [
              [x0, y0],
              [x1, y0],
              [x1, y1],
              [x0, y1],
            ];
          };
          /* 离线预览也要覆盖文本层(Step 2)。这里的字级框**刻意复刻真实管线的一个特征**:
           切词丢弃空白(`decode.rs` 的 `get_word_info` 不把空白放进 word_content),所以
           “服务费 1,200.00” 里那个空格**没有**对应 span,拖选跨过去不会带出空格。
           几何上则**不复刻**:真实管线从 Step 3 起用 CTC forced alignment 给每个字符一段
           自己的帧区间(`align.rs` + `word_boxes.rs` 的铺格),比例字体下宽度不等;而离线
           预览手里只有文本与区域四边形,没有任何逐步概率,因此只能按等宽铺。
           演示数据只证明“层能建起来、能拖选”,**不是**字符定位精度的证据(那属于 Step 4 的基准)。 */
          const wordsOf = (text, quad, score) => {
            const xs = quad.map((p) => p[0]);
            const ys = quad.map((p) => p[1]);
            const x0 = Math.min(...xs),
              x1 = Math.max(...xs);
            const y0 = Math.min(...ys),
              y1 = Math.max(...ys);
            const chars = [...text];
            const col = (x1 - x0) / Math.max(1, chars.length);
            const out = [];
            chars.forEach((ch, k) => {
              if (ch.trim() === "") return; /* 与真实切词一致:空白不产出 span,位置留成空隙 */
              const left = x0 + k * col;
              out.push({
                text: ch,
                score,
                kind: "char",
                polygon: [
                  [left, y0],
                  [left + col, y0],
                  [left + col, y1],
                  [left, y1],
                ],
              });
            });
            return out;
          };
          const regions = rows.map((r, i) => {
            const quad = box(i);
            const kind = r[2] || "text";
            return {
              text: r[0],
              conf: r[1],
              /* 公式区域**不携带** CTC 结果,因此也没有词框(与线上同一语义) */
              words: kind === "text" ? wordsOf(r[0], quad, r[1]) : null,
              kind,
              order: i + 1,
              polygon: quad,
            };
          });
          const firstTableLine = rows.length - tableLines.length;
          const lastTableLine = rows.length - 1;
          const tableHtml =
            '<table><thead><tr><td colspan="2">离线预览表格</td></tr></thead>' +
            "<tbody><tr><td>项目</td><td>服务费 1,200.00</td></tr>" +
            "<tr><td>税费</td><td>80.00</td></tr></tbody></table>";
          regions.push({
            text: "",
            conf: null,
            kind: "table",
            order: regions.length + 1,
            polygon: [
              [Math.round(w * 0.08), Math.round(h * (0.11 + 0.075 * firstTableLine) - h * 0.012)],
              [Math.round(w * 0.66), Math.round(h * (0.11 + 0.075 * firstTableLine) - h * 0.012)],
              [Math.round(w * 0.66), Math.round(h * (0.11 + 0.075 * lastTableLine) + h * 0.05)],
              [Math.round(w * 0.08), Math.round(h * (0.11 + 0.075 * lastTableLine) + h * 0.05)],
            ],
            table: {
              html: tableHtml,
              table_html: tableHtml,
              markdown: "| 项目 | 服务费 1,200.00 |\n| --- | --- |\n| 税费 | 80.00 |",
              rows: 3,
              cols: 2,
              confidence: "low",
              degradations: [{ kind: "grid_holes", holes: 1 }],
              holes: 1,
              cells: tableLines.map((r, i) => ({
                row: i,
                col: 0,
                rowspan: 1,
                colspan: 1,
                text: r[0],
                score: r[1],
                match_kind: "single",
                polygon: box(firstTableLine + i),
              })),
              source_line_indices: tableLines.map((_, i) => firstTableLine + i),
              model_id: "demo/slanet-plus.onnx",
            },
          });
          return {
            regions,
            plain: rows.map((r) => r[0]).join("\n"),
            timings: {
              preprocess_ms: 14.2,
              det_ms: 412.8,
              cls_ms: 8.4,
              rec_ms: 236.5,
              postprocess_ms: 3.1,
              total_ms: 675.0,
            },
          };
        }
        /* 演示模式:标注图 = 原图 + 当前叠框,本地合成 PNG */
        function demoAnnotated() {
          const i = state.image;
          if (!i || !state.result) return;
          const c = document.createElement("canvas");
          c.width = i.w;
          c.height = i.h;
          const g = c.getContext("2d");
          g.drawImage(imgEl, 0, 0);
          state.result.regions.forEach((r) => {
            if (!r.polygon) return;
            g.beginPath();
            g.moveTo(r.polygon[0][0], r.polygon[0][1]);
            for (let k = 1; k < r.polygon.length; k++)
              g.lineTo(r.polygon[k][0], r.polygon[k][1]);
            g.closePath();
            g.setLineDash(r.kind === "formula" ? [8, 6] : []);
            g.lineWidth = Math.max(2, i.w / 500);
            g.strokeStyle = "#111";
            g.stroke();
          });
          c.toBlob((b) => {
            saveBlob(b, "ocr-" + state.job.id + "-annotated.png");
            toast("标注图已保存", "ok", "download");
          });
        }
        /* 演示模式导出:JSON / Markdown / 静态 HTML(无脚本,呼应 ReportMode::Static 口径) */
        function demoExport(fmt) {
          const r = state.result,
            id = state.job.id;
          let blob, name;
          if (fmt === "json") {
            blob = new Blob(
              [
                JSON.stringify(
                  r.raw && Object.keys(r.raw).length
                    ? r.raw
                    : {
                        job_id: id,
                        plain_text: r.plain,
                        regions: r.regions,
                        timings: r.timings,
                      },
                  null,
                  2,
                ),
              ],
              { type: "application/json" },
            );
          } else if (fmt === "md") {
            const md = [
              "# OCR 识别结果",
              "",
              "- 任务:`" + id + "`",
              "- 区域数:" + r.regions.length,
              "",
              "| # | 类型 | 置信度 | 文本 |",
              "|---|---|---|---|",
              ...r.regions.map(
                (g, i) =>
                  `| ${i + 1} | ${regionKindLabel(g.kind)} | ` +
                  `${g.conf != null ? (g.conf > 1 ? g.conf : g.conf * 100).toFixed(1) + "%" : "—"} | ${g.text.replace(/\|/g, "\\|")} |`,
              ),
            ].join("\n");
            blob = new Blob([md], { type: "text/markdown" });
          } else {
            const html =
              '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"><title>OCR ' +
              esc(id) +
              "</title>" +
              '<style>body{font-family:"Noto Sans SC","Microsoft YaHei",sans-serif;max-width:760px;margin:40px auto;' +
              "padding:0 20px;color:#111;background:#fafafa}h1{font-size:20px}table{border-collapse:collapse;width:100%;" +
              "font-size:14px}td,th{border-bottom:1px solid #ddd;padding:8px 6px;text-align:left}th{font-size:12px;" +
              "color:#666;letter-spacing:.1em}small{color:#888}</style></head><body><h1>OCR 识别结果</h1><p><small>" +
              esc(id) +
              " · " +
              r.regions.length +
              " 个区域 · 由 RapidStructure 本地评估台导出</small></p><table><tr><th>#</th><th>类型</th><th>置信度</th><th>文本</th></tr>" +
              r.regions
                .map(
                  (g, i) =>
                    "<tr><td>" +
                    (i + 1) +
                    "</td><td>" +
                    regionKindLabel(g.kind) +
                    "</td><td>" +
                    (g.conf != null
                      ? (g.conf > 1 ? g.conf : g.conf * 100).toFixed(1) + "%"
                      : "—") +
                    "</td><td>" +
                    esc(g.text) +
                    "</td></tr>",
                )
                .join("") +
              "</table></body></html>";
            blob = new Blob([html], { type: "text/html" });
          }
          saveBlob(blob, "ocr-" + id + "." + fmt);
          toast(fmt.toUpperCase() + " 导出已保存", "ok", "download");
        }

        /* ================= 启动 ================= */
        /* 队列就绪 / 公式开关都依赖 /api/models,因此在取到模型集之前先按"未知"渲染一遍,
   取到之后由 refreshModels() 重算(离线预览则由 enterDemo() 负责)。 */
        renderPill();
        renderEngine();
        renderRegions();
        renderDiag();
        renderButton();
        renderModeRow();
        renderVerify();
        if (DEMO) {
          enterDemo();
        } else {
          statusLoop(); /* 引擎状态:loading 期 2s,ready 后 8s */
          refreshModels(); /* 模型集状态;下载任务的进度由 GET /api/jobs/{id} 轮询 */
        }
      })();
    </script>
  </body>
</html>