File size: 302,335 Bytes
8d52e72
 
 
9ae8ec6
4fbb2dd
 
8d52e72
9efc933
e6e90f2
436e72c
8d52e72
 
8268665
8d52e72
c7eced2
 
8d52e72
 
abb4b1a
 
 
 
 
 
 
 
 
 
 
 
 
 
49a03ba
abb4b1a
 
8d52e72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9efc933
8d52e72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08bd7b1
 
 
 
 
d3f4b21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ef86c5
 
 
d3f4b21
 
 
 
 
 
08bd7b1
486ad7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1dc63a4
 
 
 
 
 
486ad7a
 
 
 
6c8fd46
 
 
486ad7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b97f1d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee872c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
486ad7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84879e3
 
 
 
 
49a03ba
84879e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a03ba
84879e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13e955d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4ddaa3
9eda756
 
 
 
 
 
 
 
 
 
 
975d991
 
 
 
 
 
 
 
 
 
 
c6e337d
e6e90f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1778128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6e90f2
22266af
 
 
 
 
e6e90f2
22266af
 
 
e6e90f2
22266af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6e90f2
 
 
22266af
 
 
 
 
 
 
 
e6e90f2
22266af
 
 
 
 
 
 
e6e90f2
22266af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6e90f2
 
 
 
 
 
22266af
e6e90f2
22266af
 
 
e6e90f2
22266af
e6e90f2
 
22266af
ee872c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16517c2
ee872c7
16517c2
ee872c7
 
16517c2
ee872c7
e6e90f2
ac379b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee872c7
 
 
 
ac379b4
ee872c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50e6523
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
490e866
 
5a321ab
 
 
490e866
 
 
5a321ab
 
 
 
 
 
490e866
 
 
ac379b4
490e866
 
 
ac379b4
 
 
 
 
 
 
 
 
5a321ab
 
 
 
 
 
 
 
ac379b4
 
490e866
 
 
 
 
 
 
 
5a321ab
ac379b4
490e866
c6e337d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f663c
c6e337d
 
 
 
 
ee872c7
 
 
 
 
 
 
 
 
 
 
afb04b0
ee872c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ae8ec6
 
 
 
 
 
9efc933
 
 
 
9ae8ec6
 
 
9efc933
9ae8ec6
 
 
 
 
 
 
 
 
 
8c39e75
 
 
 
 
 
 
 
 
49a03ba
8c39e75
 
 
 
 
 
 
13e955d
8c39e75
 
 
 
13e955d
 
 
 
768e153
13e955d
 
 
49a03ba
13e955d
 
 
 
 
 
8c39e75
 
a50e440
8c39e75
 
 
 
 
 
 
25f663c
8c39e75
 
 
 
 
 
 
 
 
 
 
 
 
2f1b004
8c39e75
2f1b004
8c39e75
 
49a03ba
8c39e75
2f1b004
 
 
8c39e75
 
 
 
2f1b004
8c39e75
 
 
 
4468c93
8c39e75
 
 
 
 
 
 
13e955d
 
 
 
 
 
9eda756
 
13e955d
9eda756
13e955d
 
 
 
 
 
a4ddaa3
13e955d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d57b59a
13e955d
 
 
 
 
 
 
 
 
 
 
 
 
 
8268665
19146fe
436e72c
c3ae63a
 
436e72c
 
c3ae63a
 
 
 
 
 
 
 
 
 
436e72c
c3ae63a
 
436e72c
c3ae63a
 
436e72c
19146fe
 
c3ae63a
 
 
 
 
 
 
 
436e72c
 
 
19146fe
c3ae63a
 
19146fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
436e72c
50ee257
cedec4d
50ee257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ccdee8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2d1258
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
675cc12
c2d1258
 
 
 
 
8a22438
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f663c
8a22438
 
 
 
 
 
 
 
 
 
 
 
 
 
675cc12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a22438
 
 
 
 
 
 
 
 
 
 
 
 
 
3bc5071
 
 
 
 
8a22438
 
 
 
 
 
 
 
 
25f663c
8a22438
 
 
 
 
 
ee32dd3
 
 
 
25f663c
ee32dd3
 
 
 
 
425ad8c
 
8a22438
25f663c
425ad8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee32dd3
425ad8c
 
 
 
 
 
 
 
 
ee32dd3
425ad8c
 
 
56c51f4
425ad8c
 
 
 
 
ee32dd3
 
 
 
 
b0af0d8
ee32dd3
425ad8c
b0af0d8
 
 
 
 
 
 
 
 
 
 
 
49a03ba
b0af0d8
 
 
 
 
 
 
 
 
 
 
56c51f4
b0af0d8
 
 
 
 
 
0ababbd
 
 
 
 
 
 
 
 
 
 
49a03ba
0ababbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2315c7d
9ccdee8
 
 
 
 
 
 
 
2315c7d
 
9ccdee8
 
 
1859749
 
9ccdee8
 
 
 
 
 
 
 
 
 
 
 
 
cedec4d
9ccdee8
 
 
 
 
 
 
 
 
 
 
 
4de02b9
1859749
 
 
 
9ccdee8
 
 
 
 
1859749
 
 
ac379b4
 
9ccdee8
d117afd
 
 
 
3be5e02
cedec4d
 
 
 
 
 
 
3be5e02
 
 
 
 
 
 
 
 
 
 
 
d117afd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d6c316
 
d117afd
 
 
cedec4d
e31cc58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cedec4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e31cc58
 
 
 
 
 
cedec4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e2d0dd
 
 
 
 
 
 
 
 
 
f48da1a
 
 
 
 
 
 
 
 
 
 
 
1085359
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f48da1a
 
 
ca7083d
8e2d0dd
 
ca7083d
8e2d0dd
 
ca7083d
 
 
 
8e2d0dd
 
 
 
 
 
 
 
 
 
ca7083d
 
 
 
 
 
 
8e2d0dd
 
 
 
 
 
 
 
 
dead914
 
8e2d0dd
 
 
 
dead914
ca7083d
8e2d0dd
 
 
 
 
 
 
 
 
ca7083d
 
 
 
 
 
 
 
 
 
 
 
 
 
8e2d0dd
 
 
 
 
 
ca7083d
dead914
ca7083d
dead914
 
 
8e2d0dd
 
 
 
 
 
f48da1a
 
 
 
 
ca7083d
 
 
 
f48da1a
18e3831
 
 
 
f48da1a
 
dead914
 
 
 
 
ca7083d
18e3831
f48da1a
 
dead914
f48da1a
 
 
 
 
 
 
ca7083d
 
 
 
dead914
f48da1a
 
 
ca7083d
 
 
 
 
 
f48da1a
 
 
ca7083d
f48da1a
 
 
dead914
 
 
ca7083d
f48da1a
 
 
 
 
 
dead914
 
 
 
 
7bd7f90
ca7083d
dead914
7bd7f90
dead914
8268665
 
 
 
dead914
 
 
ca7083d
dead914
 
 
 
 
ca7083d
 
8268665
 
 
dead914
ca7083d
 
 
dead914
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca7083d
dead914
 
 
 
ca7083d
 
 
dead914
 
 
18e3831
ca7083d
dead914
 
ca7083d
 
dead914
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca7083d
8268665
7bd7f90
ca7083d
dead914
 
 
 
 
 
 
ca7083d
dead914
ca7083d
8268665
 
456b371
8268665
01a7b0c
 
8268665
 
456b371
 
 
 
 
 
 
8268665
 
 
 
 
 
01a7b0c
 
 
 
 
 
 
 
 
 
456b371
01a7b0c
49a03ba
01a7b0c
 
 
 
 
456b371
9dab77d
 
 
 
 
 
 
be892c3
 
9dab77d
be892c3
 
9dab77d
 
 
 
 
 
8268665
8c62083
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54bcbbc
 
 
 
 
 
490e866
 
54bcbbc
 
 
 
490e866
 
54bcbbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4468c93
54bcbbc
 
 
 
 
 
 
 
 
 
 
 
 
 
490e866
4468c93
490e866
 
 
 
 
4468c93
490e866
 
 
 
 
 
54bcbbc
45ae844
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b26f72b
456b371
b26f72b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e93c04
456b371
0e93c04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d52e72
4468c93
8d52e72
 
675cc12
8d52e72
 
 
 
 
 
 
 
 
 
 
 
8268665
 
2f1b004
8268665
 
 
 
 
 
2f1b004
 
8268665
 
 
 
 
 
 
2f1b004
8268665
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6853944
ffc49fd
 
 
 
 
 
 
 
722c78c
ffc49fd
 
 
 
 
722c78c
 
 
ffc49fd
 
 
 
 
 
 
 
 
 
 
 
 
 
6853944
722c78c
6853944
ffc49fd
6853944
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffc49fd
8d52e72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a03ba
8d52e72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
015727d
 
 
8d52e72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86f0df6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
675cc12
8d52e72
 
 
 
675cc12
8d52e72
 
 
 
 
675cc12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
061d92e
 
 
675cc12
 
061d92e
 
 
 
 
 
675cc12
061d92e
 
 
675cc12
c69d379
 
 
 
 
 
 
 
49a03ba
c69d379
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
675cc12
 
 
 
 
 
 
 
 
 
 
 
b0af0d8
 
 
 
 
 
 
 
 
 
 
 
7bd7f90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e970b77
 
 
8b90a8a
 
e970b77
 
 
 
 
49a03ba
e970b77
 
 
 
 
 
 
 
 
 
 
15d6155
3d91c94
15d6155
 
 
 
 
 
 
 
 
 
 
 
 
 
25f663c
975d991
15d6155
975d991
 
 
15d6155
 
 
 
 
 
 
 
 
 
 
 
 
3d91c94
 
 
 
 
 
 
 
abb4b1a
3d91c94
 
 
abb4b1a
3d91c94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b90a8a
 
 
 
abb4b1a
3d91c94
 
 
 
 
 
 
551ecc9
3d91c94
 
 
 
 
 
25f663c
3d91c94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15d6155
8d52e72
 
 
 
 
 
 
 
 
 
 
 
675cc12
8d52e72
 
 
 
 
 
675cc12
8d52e72
675cc12
 
 
 
 
8d52e72
e61d244
 
 
d3655e4
 
 
 
 
 
e61d244
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2d9f99
 
 
 
 
 
 
 
 
 
 
 
 
86f0df6
a2d9f99
86f0df6
a2d9f99
 
 
86f0df6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a367e7
 
 
 
 
d3655e4
7a367e7
 
 
 
 
 
 
 
d3655e4
7a367e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc8aaf1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3655e4
260c008
 
d3655e4
 
 
7a367e7
 
 
 
d3655e4
 
 
 
 
7a367e7
d6f7739
 
7a367e7
d6f7739
 
 
7a367e7
 
 
d6f7739
 
7a367e7
d6f7739
 
 
 
 
 
 
5fc4750
d6f7739
5fc4750
 
 
d6f7739
 
 
 
 
 
 
 
 
 
 
 
 
 
3e70b04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6f7739
 
 
 
 
 
 
7a367e7
ec3e7e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58d59b4
02a27d4
 
 
 
 
 
 
 
 
 
 
58d59b4
 
 
 
 
 
02a27d4
 
58d59b4
 
02a27d4
58d59b4
 
02a27d4
 
 
 
 
58d59b4
 
02a27d4
58d59b4
 
 
 
 
 
 
 
 
 
 
 
a2d9f99
 
 
 
 
 
 
082debe
a2d9f99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1dc63a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2d9f99
 
 
 
 
 
 
 
 
 
 
 
 
1dc63a4
 
 
 
 
 
 
a2d9f99
61141ec
7a367e7
61141ec
 
 
49a03ba
 
 
 
 
 
61141ec
 
49a03ba
61141ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a367e7
61141ec
 
 
8d52e72
 
 
 
 
 
 
 
 
4468c93
8d52e72
 
 
 
 
ee872c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7f9999
ee872c7
ab9f351
 
 
 
 
 
 
 
 
 
 
 
 
 
596220b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ffc398
 
 
 
 
 
596220b
7ffc398
596220b
 
7ffc398
 
 
596220b
 
 
 
 
 
7ffc398
 
596220b
 
 
ab9f351
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afb04b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c9b4f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab9f351
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c9b4f9
 
 
 
 
 
 
 
 
 
ab9f351
 
 
 
 
 
 
 
 
 
 
 
f7f9999
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee872c7
 
 
 
 
 
 
 
 
 
 
 
f7f9999
ee872c7
 
f7f9999
89a0db3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7f9999
ab9f351
 
 
 
 
 
 
 
 
 
 
 
89a0db3
8d52e72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
082debe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec782cb
082debe
 
 
 
479bcbd
082debe
 
 
 
8c2c7af
81f2c79
ec782cb
082debe
ec782cb
479bcbd
 
81f2c79
082debe
 
 
 
 
81f2c79
082debe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d52e72
 
 
2f1b004
8d52e72
2f1b004
8d52e72
 
2f1b004
 
8d52e72
 
2f1b004
8d52e72
2f1b004
8d52e72
 
4468c93
8d52e72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fbb2dd
2f1b004
 
4fbb2dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f1b004
 
 
29d435f
 
2f1b004
4fbb2dd
 
 
29d435f
 
4fbb2dd
2f1b004
29d435f
2f1b004
 
4fbb2dd
 
 
 
 
 
 
 
 
9c3b322
 
 
 
 
 
 
 
 
 
4fbb2dd
 
 
 
 
 
9c3b322
 
4fbb2dd
 
 
 
 
675cc12
4468c93
675cc12
4fbb2dd
675cc12
4fbb2dd
 
 
675cc12
 
4fbb2dd
 
0ababbd
 
 
 
 
 
 
 
49a03ba
0ababbd
 
 
 
 
 
 
 
 
 
 
675cc12
 
4468c93
675cc12
 
 
 
 
 
 
 
 
 
 
4fbb2dd
 
 
 
 
 
 
4468c93
675cc12
4fbb2dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4468c93
4fbb2dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4468c93
4fbb2dd
 
 
 
 
 
 
 
 
 
 
 
 
8d52e72
2f1b004
 
 
 
8d52e72
2f1b004
8d52e72
2f1b004
 
 
 
 
 
 
 
 
 
 
 
 
8d52e72
2f1b004
 
8d52e72
 
2f1b004
8d52e72
ee10dd3
 
 
 
 
 
 
 
 
 
 
 
 
 
25f663c
ee10dd3
 
 
 
 
 
 
 
 
 
 
 
 
2f1b004
ee10dd3
 
 
 
 
2f1b004
ee10dd3
 
 
2f1b004
 
ee10dd3
 
2f1b004
ee10dd3
 
 
 
 
2f1b004
ee10dd3
 
 
 
 
 
 
 
 
 
 
 
 
 
2f1b004
ee10dd3
 
2f1b004
ee10dd3
2f1b004
ee10dd3
 
2f1b004
 
ee10dd3
 
2f1b004
ee10dd3
 
 
 
 
 
 
2f1b004
25f663c
ee10dd3
 
 
 
 
 
 
 
 
 
9906d8a
2f1b004
9906d8a
2f1b004
9906d8a
 
 
 
2f1b004
 
9906d8a
 
2f1b004
9906d8a
 
 
 
2f1b004
9906d8a
 
 
 
 
 
 
 
 
 
 
 
8d52e72
 
 
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
"""Local Reader behavior regressions; all document/network fixtures stay offline."""

import io
import base64
import gzip
import hashlib
import json
import os
import struct
import time
import unittest
import urllib.parse
import wave

from tests.performance import test_reader_performance as support
from tests.support.reader_native_fixture import install as install_native_djvu


def expose_dom_search_tools(page):
    def instrument(route):
        response = route.fetch()
        script = response.text()
        marker = "  function pruneMarks() {"
        if marker not in script:
            raise AssertionError("DOM search instrumentation boundary missing")
        route.fulfill(response=response, body=script.replace(marker, '''
          window.__domSearchTools = {
            locator: () => fullSearchDomLocator, snapshot: () => fullSearchDomSnapshot,
            textNodes: fullSearchTextNodes, headingLookup: createFullSearchHeadingLookup,
            location: fullSearchLocation
          };
        ''' + marker))
    page.route("**/static/reader/search/reader-dom-search.mjs*", instrument)


@unittest.skipIf(support.sync_playwright is None, "Playwright is unavailable")
class ReaderRefactorTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.server = support.static_server()
        cls.origin = cls.server.__enter__()
        cls.playwright = support.sync_playwright().start()
        try:
            cls.browser = cls.playwright.chromium.launch(headless=True, args=["--no-sandbox"])
        except support.PlaywrightError as error:
            cls.playwright.stop()
            cls.server.__exit__(None, None, None)
            raise unittest.SkipTest(str(error))

    @classmethod
    def tearDownClass(cls):
        cls.browser.close()
        cls.playwright.stop()
        cls.server.__exit__(None, None, None)

    def setUp(self):
        self.context = self.browser.new_context(viewport={"width": 1100, "height": 800})
        self.context.route("**/*", lambda route: route.continue_()
                           if route.request.url.startswith(self.origin + "/")
                           else route.abort())
        self.page = self.context.new_page()
        self.errors = []
        self.page.on("pageerror", lambda error: self.errors.append(str(error)))
        self.page.set_default_timeout(int(os.environ.get("READER_TEST_TIMEOUT_MS", "6000")))

    def tearDown(self):
        self.context.close()
        self.assertEqual(self.errors, [])

    def reader_url(self, extension="txt", name="refactor", **params):
        source = f"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/{name}.{extension}"
        values = {"url": source, "ext": extension, "title": name, **params}
        return self.origin + "/static/reader.html?" + urllib.parse.urlencode(values)

    def serve(self, body, mime="text/plain"):
        self.page.route("**/api/reader-content**", lambda route: route.fulfill(
            status=200, content_type=mime, body=body))

    def open(self, url):
        self.page.goto(url)
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")

    def test_retired_ocr_parameter_does_not_create_a_button_or_break_text(self):
        self.serve("Original text remains readable")
        self.open(self.reader_url("txt", ocr=self.origin + "/txt/old-book.txt"))
        self.assertEqual(self.page.locator("#ocr").count(), 0)
        self.assertIn("Original text remains readable", self.page.locator(".reader-text").inner_text())

    def test_fetch_proxy_failure_and_manual_retry_for_txt_and_markdown(self):
        support.route_local_vendor_fallback(self.page)
        direct, requests = [], []
        self.page.on("request", lambda request: direct.append(request.url)
                     if request.url.startswith("https://huggingface.co/") else None)
        available = False

        def proxy(route):
            requests.append(route.request.url)
            route.fulfill(status=200 if available else status,
                          content_type="text/plain" if extension == "txt" else "text/markdown",
                          body="# Proxy readable" if available else "unavailable",
                          headers={"Access-Control-Allow-Origin": "*"})

        self.page.route("**/api/reader-content**", proxy)
        for extension, selector in (("txt", ".reader-text"), ("md", ".reader-markdown")):
            for status in (403, 404):
                with self.subTest(extension=extension, status=status):
                    requests.clear()
                    available = False
                    self.page.goto(self.reader_url(extension), wait_until="domcontentloaded")
                    self.page.locator('html[data-reader-phase="failed"]').wait_for()
                    alert = self.page.get_by_role("alert")
                    self.assertTrue(alert.is_visible())
                    self.assertIn(f"HTTP {status}", alert.text_content())
                    self.assertEqual(self.page.locator("#status").text_content(), "无法打开")
                    self.assertEqual(self.page.locator("#content").get_attribute("data-error-code"), "READER_NETWORK")
                    self.assertEqual(self.page.locator(selector).count(), 0)
                    self.assertEqual(self.page.locator(".reader-loading-indicator").count(), 0)
                    self.assertEqual(len(requests), 1)
                    source = urllib.parse.parse_qs(urllib.parse.urlsplit(self.page.url).query)["url"]
                    self.assertEqual(urllib.parse.parse_qs(urllib.parse.urlsplit(requests[0]).query)["url"], source)
                    self.assertEqual(direct, [])
                    # Network errors use a manual browser reload for retry.
                    self.assertEqual(self.page.locator("#reader-engine-retry").count(), 0)
                    failed_url = self.page.url
                    available = True
                    self.page.reload(wait_until="domcontentloaded")
                    self.page.locator('html[data-reader-phase="ready"]').wait_for()
                    # Plain text blocks use content-visibility; innerText can
                    # omit their content until the next layout/paint.
                    self.page.locator(selector, has_text="Proxy readable").wait_for(state="attached")
                    if extension == "md":
                        self.assertEqual(self.page.locator(selector + " h1").inner_text(), "Proxy readable")
                    self.assertEqual(self.page.locator(".reader-error, .reader-loading-indicator").count(), 0)
                    self.assertEqual(self.page.url, failed_url)
                    self.assertEqual(requests, [requests[0]] * 2)
                    self.assertEqual(direct, [])

    def markdown_link_fixture(self):
        support.route_local_vendor_fallback(self.page)
        # The checked-in Reader source loads these locally in production builds;
        # use the same real Marked and DOMPurify in browser regression tests.
        base = 'https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/books/'
        index = '''# Index

[chapter](chapter%20one.md)

[fragment](chapter%20one.md#section)

[self](index.md#local)

[local](#local)

[outside](https://example.org/article.md)

[foreign](https://huggingface.co/datasets/Other/Test/resolve/main/book.md)

[unsupported](archive.chm)

[query](chapter%20one.md?download=true)

[pdf-fragment](book.pdf#page=4)

[mirror](https://hf-mirror.com/datasets/VoiceOfML/Test/resolve/main/mirror.md)

[malicious](https://huggingface.co.evil.test/datasets/VoiceOfML/Test/resolve/main/book.md)

<a download href="https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/books/chapter%20one.md">download</a>

[unsafe](javascript:alert(1))

<a id="local"></a> Local anchor
'''
        chapter = ('# Chapter one\n\n' + ('A paragraph.\n\n' * 90) +
                   '<a id="section"></a>\n\n## Section target\n\n' + ('More text.\n\n' * 60))
        def serve(route):
            source = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query).get('url', [''])[0]
            path = urllib.parse.unquote(urllib.parse.urlsplit(source).path)
            if path.endswith('/books/index.md'):
                route.fulfill(content_type='text/markdown', body=index)
            elif path.endswith('/books/chapter one.md'):
                route.fulfill(content_type='text/markdown', body=chapter)
            else:
                route.fulfill(status=404, body='missing')
        self.page.route('**/api/reader-content**', serve)
        self.page.route('**/api/reader-bucket-resource**', lambda route: route.fulfill(
            content_type='text/markdown', body=index))
        return base

    def test_markdown_dataset_links_open_in_reader_and_keep_navigation(self):
        base = self.markdown_link_fixture()
        self.open(self.reader_url('md', name='books/index'))
        article = self.page.locator('.reader-markdown')
        href = article.get_by_role('link', name='chapter', exact=True).get_attribute('href')
        target = urllib.parse.urlsplit(href)
        args = urllib.parse.parse_qs(target.query)
        self.assertTrue(target.path.endswith('/static/reader.html'))
        self.assertEqual(urllib.parse.unquote(args['url'][0]), base + 'chapter one.md')
        self.assertEqual(args['ext'][0], 'md')
        self.assertEqual(article.get_by_role('link', name='local', exact=True).get_attribute('href'), '#local')
        self.assertEqual(article.get_by_role('link', name='self', exact=True).get_attribute('href'), '#local')
        self.assertEqual(article.get_by_role('link', name='outside').get_attribute('href'), 'https://example.org/article.md')
        self.assertTrue(article.get_by_role('link', name='foreign').get_attribute('href').startswith('https://huggingface.co/datasets/Other/'))
        self.assertEqual(article.get_by_role('link', name='unsupported').get_attribute('href'), base + 'archive.chm')
        self.assertEqual(article.get_by_role('link', name='query').get_attribute('href'), base + 'chapter%20one.md?download=true')
        self.assertEqual(article.get_by_role('link', name='pdf-fragment').get_attribute('href'), base + 'book.pdf#page=4')
        self.assertIn('ext=md', article.get_by_role('link', name='mirror').get_attribute('href'))
        self.assertTrue(article.get_by_role('link', name='malicious').get_attribute('href').startswith('https://huggingface.co.evil.test/'))
        self.assertTrue(article.get_by_role('link', name='download').get_attribute('href').startswith(base))
        self.assertEqual(article.get_by_text('unsafe').evaluate('node => node.closest("a")?.getAttribute("href") || null'), None)
        article.get_by_role('link', name='chapter', exact=True).click()
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready' && document.querySelector('.reader-markdown')?.textContent.includes('Chapter one')")
        self.assertEqual(urllib.parse.unquote(urllib.parse.parse_qs(urllib.parse.urlsplit(self.page.url).query)['url'][0]), base + 'chapter one.md')
        self.page.evaluate("() => VoiceOfMLReaderStore.put({url: new URL(location.href).searchParams.get('url'), title:'Chapter', extension:'md', lastReadAt:Date.now(), scrollTop:0})")
        self.page.go_back()
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready' && document.querySelector('.reader-markdown')?.textContent.includes('Index')")
        self.page.locator('.reader-markdown').get_by_role('link', name='fragment', exact=True).click()
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready' && !!document.querySelector('.reader-markdown #section')")
        self.assertEqual(urllib.parse.urlsplit(self.page.url).fragment, 'section')
        self.page.wait_for_function("() => { const n=document.querySelector('#section'), v=document.querySelector('#viewport'); return n && Math.abs(n.getBoundingClientRect().top-v.getBoundingClientRect().top)<40; }")

    def test_markdown_reflows_prose_and_keeps_code_and_tables_in_reading_column(self):
        self.page.set_viewport_size({'width': 320, 'height': 780})
        self.page.emulate_media(reduced_motion='reduce')
        self.page.route('**/static/reader/core/reader-store.js*', lambda route: route.fulfill(
            content_type='text/javascript', body='window.VoiceOfMLReaderStore={get:async()=>null,put:async()=>{},list:async()=>[]};'))
        prose = '  ' + '长段落应该在阅读栏内折行。' * 40
        code = '  const row = "' + 'X' * 90 + '";'
        aligned = '合计' + '\u3000' * 22 + '133.9'
        long_link = 'https://example.invalid/' + 'part' * 95
        dot = ('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8'
               '/x8AAwMB/6XWbqkAAAAASUVORK5CYII=')
        self.serve(f'''# 小说标题

## 第一节

```
{prose}

    行首空格保留。
```

[{long_link}](#later)

{aligned}

## 第二节

```js
{code}
```

<table id="data" style="min-width:680px"><caption>数据表</caption><tr><th>栏目</th><td>42</td></tr></table>

<table id="illustration"><tr><td><img src="{dot}" width="900" height="900" alt="插图"></td></tr></table>

<h2 id="later">末节</h2>

结尾正文。
''', 'text/markdown')
        url = self.reader_url('md', 'responsive-markdown')
        self.open(url)
        panel_button = self.page.locator('#history')
        self.page.wait_for_function("() => document.querySelector('#history').getAttribute('aria-expanded') === 'true'")
        self.page.get_by_role('link', name='第二节', exact=True).click()
        self.page.locator('#history-panel').wait_for(state='hidden')
        self.assertEqual(panel_button.get_attribute('aria-expanded'), 'false')
        self.open(url)
        self.page.evaluate('()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))')
        self.assertEqual(panel_button.get_attribute('aria-expanded'), 'false')
        article = self.page.locator('.reader-markdown')
        self.assertEqual(article.locator('pre code').first.text_content(), prose + '\n\n    行首空格保留。\n')
        self.assertEqual(article.locator('code.language-js').text_content(), code + '\n')
        self.assertEqual(article.locator('p', has_text='133.9').text_content(), aligned)
        for width, zoom in ((320, 100), (390, 150), (1200, 100)):
            with self.subTest(width=width, zoom=zoom):
                self.page.set_viewport_size({'width': width, 'height': 780})
                self.page.locator('#zoom').fill(str(zoom))
                self.page.locator('#zoom').dispatch_event('change')
                metrics = article.evaluate('''article => {
                    const v = document.querySelector('#viewport');
                    const [a,b] = article.querySelectorAll('pre');
                    const region = article.querySelector('#data').parentElement;
                    const img = article.querySelector('#illustration img');
                    return [v.scrollWidth - v.clientWidth, a.scrollWidth - a.clientWidth,
                        b.scrollWidth - b.clientWidth, region.scrollWidth - region.clientWidth,
                        region.tabIndex, img.getBoundingClientRect().width <= article.clientWidth + 1,
                        img.getBoundingClientRect().width === img.getBoundingClientRect().height];
                }''')
                self.assertLessEqual(metrics[0], 1, metrics)
                self.assertLessEqual(metrics[1], 1, metrics)
                if width < 600:
                    self.assertGreater(metrics[2], 40, metrics)
                    self.assertGreater(metrics[3], 40, metrics)
                self.assertEqual(metrics[4:], [0, True, True], metrics)

    def test_markdown_mounts_sanitized_nodes_without_reparsing_article(self):
        self.page.add_init_script('''(() => {
          const html = Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML');
          window.__markdownArticleWrites = 0;
          Object.defineProperty(Element.prototype, 'innerHTML', {...html, set(value) {
            if (this.matches('article.reader-markdown')) window.__markdownArticleWrites++;
            return html.set.call(this, value);
          }});
        })()''')
        self.serve('---\ntitle: frontmatter sentinel\n---\n\n# Readable Markdown\n\n'
                   '**Bold** and `code`.\n\n'
                   '| Cell | Value |\n| --- | --- |\n| A | 中文 |\n\n'
                   '<script>/* disallowed in book content */</script>\n'
                   '<a id="filtered-link" href="javascript:void(0)">Unsafe link</a>', 'text/markdown')
        self.open(self.reader_url('md', 'fragment-output'))
        article = self.page.locator('.reader-markdown')
        self.assertEqual(article.locator('h1').inner_text(), 'Readable Markdown')
        self.assertEqual(article.locator('strong').inner_text(), 'Bold')
        self.assertEqual(article.locator('tbody td').all_text_contents(), ['A', '中文'])
        self.assertEqual(article.locator('script').count(), 0)
        self.assertIsNone(article.locator('#filtered-link').get_attribute('href'))
        self.assertNotIn('frontmatter sentinel', article.inner_text())
        self.assertEqual(self.page.evaluate('window.__markdownArticleWrites'), 0)

    def test_markdown_cached_source_relative_links_use_original_download(self):
        base = self.markdown_link_fixture()
        cache = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=documents/text/md/' + 'a'*64 + '/document.md'
        self.open(self.reader_url('md', name='cache', url=cache, download=base + 'index.md'))
        href = self.page.locator('.reader-markdown').get_by_role('link', name='chapter', exact=True).get_attribute('href')
        self.assertEqual(urllib.parse.unquote(urllib.parse.parse_qs(urllib.parse.urlsplit(href).query)['url'][0]), base + 'chapter one.md')

    def test_markdown_dataset_link_in_search_overlay_uses_parent_navigation(self):
        self.markdown_link_fixture()
        reader = self.reader_url('md', name='books/index')
        shell = ('<!doctype html><body><script>window.__messages=[];'
                 'addEventListener("message", e => __messages.push(e.data));</script>'
                 '<iframe class="reader-overlay" style="width:1000px;height:700px" src=' + json.dumps(reader) + '></iframe></body>')
        self.page.route(self.origin + '/markdown-host', lambda route: route.fulfill(content_type='text/html', body=shell))
        self.page.goto(self.origin + '/markdown-host')
        frame = next(item for item in self.page.frames if '/static/reader.html?' in item.url)
        frame.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        frame.locator('.reader-markdown').get_by_role('link', name='chapter', exact=True).click()
        self.page.wait_for_function("() => __messages.some(m => m.type === 'voice-reader-open')")
        message = self.page.evaluate("() => __messages.find(m => m.type === 'voice-reader-open')")
        self.assertIn('/static/reader.html?', message['url'])
        self.assertIn('chapter%2520one.md', message['url'])

    def test_zoom_changed_during_preparation_survives_late_restoration(self):
        store = support.STORE_SCRIPT.replace(
            "get: () => new Promise((resolve) => setTimeout(() => resolve(null), 300)),",
            "get: () => new Promise(resolve => { window.__releaseRestore = () => resolve({url: location.href, page: 1, zoom: 220}); }),",
        )
        self.page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(
            content_type="text/javascript", body=store))
        self.serve(support.minimal_pdf(), "application/pdf")
        self.page.goto(self.reader_url("pdf"), wait_until="domcontentloaded")
        self.page.wait_for_function("() => !!window.__releaseRestore && !!document.querySelector('.reader-page canvas.ready')")
        self.page.locator("#zoom-in").click(click_count=3)
        self.assertEqual(self.page.locator("#zoom").input_value(), "130")
        self.page.evaluate("window.__releaseRestore()")
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        self.assertEqual(self.page.locator("#zoom").input_value(), "130")
        self.assertEqual(self.page.locator("#content").evaluate(
            "node => node.style.getPropertyValue('--reader-zoom')"), "1.3")
        self.assertEqual(self.page.evaluate("localStorage.getItem('reader-zoom')"), "130")
        self.page.wait_for_function("() => window.__savedReaderProgress?.zoom === 130")

    def test_book_restoration_does_not_change_new_books_global_zoom(self):
        store = support.STORE_SCRIPT.replace(
            "get: () => new Promise((resolve) => setTimeout(() => resolve(null), 300)),",
            "get: (url) => Promise.resolve(url.includes('refactor.pdf') ? {url, page: 1, zoom: 175} : null),",
        )
        self.page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(
            content_type="text/javascript", body=store))
        self.serve(support.minimal_pdf(), "application/pdf")
        self.page.goto(self.reader_url("pdf"))
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        self.page.locator("#zoom").fill("125")
        self.page.locator("#zoom").press("Enter")
        self.page.reload()
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        self.assertEqual(self.page.locator("#zoom").input_value(), "175")
        self.assertEqual(self.page.locator("#content").evaluate(
            "node => node.style.getPropertyValue('--reader-zoom')"), "1.75")
        self.assertEqual(self.page.evaluate("localStorage.getItem('reader-zoom')"), "125")
        self.page.goto(self.reader_url("pdf", "another"))
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        self.assertEqual(self.page.locator("#zoom").input_value(), "125")
        self.assertEqual(self.page.locator("#content").evaluate(
            "node => node.style.getPropertyValue('--reader-zoom')"), "1.25")

    def test_djvu_source_is_pinned_and_navigates(self):
        state = install_native_djvu(self.page, self.origin)
        requests = []
        self.page.on("request", lambda request: requests.append(request.url))
        self.open(state["url"])
        self.page.locator('.reader-page[data-page="1"] canvas.ready').wait_for()
        self.page.locator("#page-number").fill("3")
        self.page.locator("#page-number").dispatch_event("change")
        self.page.locator('.reader-page[data-page="3"] canvas.ready').wait_for()
        self.assertTrue(state["source"])
        self.assertTrue(all(row["range"] and "/resolve/main/" not in row["url"] for row in state["source"]))
        self.assertFalse([url for url in requests if "/pages/page-" in url or "/preview/" in url])
        self.assertFalse(self.page.locator('.reader-page img').count())
        self.page.wait_for_function("() => !document.querySelector('#toc-tab').hidden")
        support.open_reader_panel(self.page)
        self.page.locator('#toc-tab').click()
        self.page.get_by_text('Chapter two · 第 2 页', exact=True).click()
        self.page.wait_for_function("() => document.querySelector('#page-number').value === '2'")

    def test_pinned_djvu_skips_revision_lookup_and_keeps_verified_ranges(self):
        state = install_native_djvu(self.page, self.origin)
        revisions = []
        self.page.on('request', lambda request: revisions.append(request.url)
                     if '/api/reader-source-revision?' in request.url else None)
        self.open(state['url'].replace('%2Fmain%2F', '%2F' + 'a'*40 + '%2F'))
        self.page.locator('.reader-page[data-page="1"] canvas.ready').wait_for()
        self.assertEqual(revisions, [])
        self.assertTrue(state['source'] and all(row['range'] for row in state['source']))
        self.assertFalse(self.page.locator('.reader-page img').count())

    def test_unconverted_docx_is_download_only_without_loading_native_engines(self):
        requests = []
        self.page.on("request", lambda request: requests.append(request.url))
        source = 'https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/unconverted.docx'
        self.page.goto(self.reader_url('docx', url=source), wait_until='domcontentloaded')
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'failed'")
        self.assertIn("此文件暂不支持在线阅读", self.page.locator('.reader-error').text_content())
        download = self.page.locator('#download').get_attribute('href')
        self.assertTrue(download.startswith('/api/download?'))
        self.assertEqual(urllib.parse.parse_qs(urllib.parse.urlsplit(download).query).get('link'), [source])
        self.assertFalse(any('docx-preview' in url or 'jszip' in url.lower() for url in requests))

    # 2x2 AVIF fixture; no encoder or network needed at test time.
    AVIF_IMAGE = base64.b64decode(
        'AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADrbWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAcGljdAAAAAAAAA'
        'AAAAAAAAAAAAAOcGl0bQAAAAAAAQAAAB5pbG9jAAAAAEQAAAEAAQAAAAEAAAETAAAAKgAAAChpaW5mAAAAAAABAAAAGm'
        'luZmUCAAAAAAEAAGF2MDFDb2xvcgAAAABqaXBycAAAAEtpcGNvAAAAFGlzcGUAAAAAAAAAAgAAAAIAAAAQcGl4aQAAAA'
        'ADCAgIAAAADGF2MUOBAAwAAAAAE2NvbHJuY2x4AAEADQAGgAAAABdpcG1hAAAAAAAAAAEAAQQBAoMEAAAAMm1kYXQSAA'
        'oIGAA2iAhoNCAyHBTHh4ZlAgggnlAAAABIWtlc1jIgMQsbXgqRN4A=')

    def test_avif_document_decodes_via_native_image_and_bucket_proxy(self):
        path = f'pages/image/jpg/{"c" * 64}/document.avif'
        source = self.origin + '/api/reader-bucket-resource?' + urllib.parse.urlencode({'path': path})
        self.page.route(source, lambda route: route.fulfill(content_type='image/avif', body=self.AVIF_IMAGE))
        self.open(self.reader_url('image', url=source))
        image = self.page.locator('img.reader-image')
        self.assertEqual(image.get_attribute('src'), source)
        self.assertEqual(image.evaluate('img => img.naturalWidth'), 2)

    def test_avif_image_pages_navigate_with_exact_manifest_pins(self):
        root = f'pages/image/tiff/{"d" * 64}/'
        source = self.origin + '/api/reader-bucket-resource?' + urllib.parse.urlencode({'path': root + 'page-manifest.json'})
        count = 3
        # A trailing free-space box gives each valid AVIF its own size and digest.
        images = {f'pages/page-{i:06}.avif': self.AVIF_IMAGE + struct.pack('>I4s', 8 + i, b'free') + b'\x00' * i
                  for i in range(1, count + 1)}
        entries = [{'path': path, 'sha256': hashlib.sha256(data).hexdigest(), 'bytes': len(data)}
                   for path, data in images.items()]
        manifest = dict(version=1, kind='image-page-stream', image_format='avif', page_count=count, pages=entries)
        expected = [{'path': [root + entry['path']], 'sha256': [entry['sha256']], 'bytes': [str(entry['bytes'])]}
                    for entry in entries]
        manifests, requests = [], []

        def bucket(route):
            params = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)
            if params == {'path': [root + 'page-manifest.json']}:
                manifests.append(route)
                return
            requests.append(params)
            if params not in expected:
                route.fulfill(status=400)
                return
            route.fulfill(content_type='image/avif', body=images[params['path'][0].removeprefix(root)])

        self.page.add_init_script("Object.defineProperty(navigator, 'connection', {value:{saveData:false}})")
        self.page.route('**/static/reader/core/reader-store.js', lambda route: route.fulfill(
            content_type='text/javascript', body=support.STORE_SCRIPT.replace(
                'new Promise((resolve) => setTimeout(() => resolve(null), 300))', 'Promise.resolve(null)')))
        self.page.route('**/api/reader-bucket-resource?**', bucket)
        self.page.goto(self.reader_url('image-pages', url=source), wait_until='domcontentloaded')
        self.page.wait_for_function('() => window.__storeStartedAt !== undefined')
        self.page.evaluate('() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))')
        self.assertEqual(requests, [])
        self.assertEqual(len(manifests), 1)
        manifests.pop().fulfill(json=manifest)
        self.page.locator('html[data-reader-phase="ready"]').wait_for(state='attached')
        self.assertEqual(self.page.locator('#page-total').inner_text(), f'/ {count}')
        self.page.locator('.reader-page[data-page="1"] img.ready').wait_for(state='visible')
        self.page.locator('#page-number').fill(str(count))
        self.page.locator('#page-number').dispatch_event('change')
        self.page.locator(f'.reader-page[data-page="{count}"] img.ready').wait_for(state='visible')
        self.assertEqual(requests[0], expected[0])
        self.assertEqual(requests.count(expected[0]), 1)
        self.assertIn(expected[-1], requests)
        self.assertTrue(all(params in expected for params in requests), requests)

    def test_tiff_image_pages_remain_readable_without_document_page_streams(self):
        prefix = 'pages/image/tiff/' + 'a' * 64 + '/'
        source = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?' + urllib.parse.urlencode({'path': prefix+'page-manifest.json'})
        original = 'https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/original.tiff'
        data = support.IMAGE_FIXTURES['webp'][1]
        manifest = dict(version=1, kind='image-page-stream', page_count=3,
                        pages=[dict(path=f'pages/page-{page:06}.webp', bytes=len(data), sha256='a'*64)
                               for page in range(1, 4)])
        requested = []
        def asset(route):
            path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query).get('path', [''])[0]
            requested.append(path)
            if path == prefix+'page-manifest.json':
                route.fulfill(json=manifest)
            elif path.startswith(prefix+'pages/page-') and path.endswith('.webp'):
                route.fulfill(content_type='image/webp', body=data)
            else:
                route.fulfill(status=404, body='unexpected resource')
        self.page.route('**/api/reader-bucket-resource?**', asset)
        query = urllib.parse.urlencode({'url': source, 'ext': 'image-pages', 'download': original})
        self.open(self.origin+'/static/reader.html?'+query)
        self.page.locator('.reader-page[data-page="1"] img.ready').wait_for(state='visible')
        self.assertEqual(self.page.locator('#content').get_attribute('data-mode'), 'image-pages')
        self.assertEqual(self.page.locator('#page-total').inner_text(), '/ 3')
        self.page.locator('#page-number').fill('3')
        self.page.locator('#page-number').dispatch_event('change')
        self.page.locator('.reader-page[data-page="3"] img.ready').wait_for(state='visible')
        self.page.locator('#zoom-in').click()
        self.assertTrue(self.page.locator('.reader-page[data-page="3"] img.ready').evaluate('image => image.naturalWidth > 0'))
        self.assertTrue(any(path == prefix+'pages/page-000003.webp' for path in requested))
        self.assertFalse(any(path.startswith('objects/') for path in requested))
        self.assertTrue(self.page.locator('#download').get_attribute('href'))

    def test_tiff_first_image_fetch_waits_for_manifest_validation(self):
        for saved, save_data, valid in ((False, False, True), (False, False, False),
                                        (False, True, True), (True, False, True)):
            with self.subTest(saved=saved, save_data=save_data, valid=valid):
                page = self.context.new_page()
                try:
                    self._check_tiff_opening(page, saved, save_data, valid)
                finally:
                    page.close()

    def _check_tiff_opening(self, page, saved, save_data, valid):
        prefix = 'pages/image/tiff/' + hashlib.sha256(str((saved, save_data, valid)).encode()).hexdigest() + '/'
        source = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?' + urllib.parse.urlencode({
            'path': prefix + 'page-manifest.json'})
        data = support.IMAGE_FIXTURES['webp'][1]
        store = support.STORE_SCRIPT.replace('new Promise((resolve) => setTimeout(() => resolve(null), 300))',
            'Promise.resolve({page: 2, pageOffset: 0, zoom: 1})' if saved else 'Promise.resolve(null)')
        page.route('**/static/reader/core/reader-store.js', lambda route: route.fulfill(
            content_type='text/javascript', body=store))
        page.add_init_script(f"Object.defineProperty(navigator, 'connection', {{value:{{saveData:{str(save_data).lower()}}}}})")
        manifests, images = [], []

        def asset(route):
            path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)['path'][0]
            if path.endswith('/page-manifest.json'):
                manifests.append(route)
            else:
                images.append(path)
                route.fulfill(content_type='image/webp', body=data)

        page.route('**/api/reader-bucket-resource?**', asset)
        page.goto(self.reader_url('image-pages', url=source), wait_until='domcontentloaded')
        page.wait_for_function('() => window.__storeStartedAt !== undefined')
        # Flush the settled history lookup while the manifest is still held.
        page.evaluate('() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))')
        self.assertEqual(images, [])
        self.assertEqual(page.locator('.reader-page').count(), 0)
        self.assertEqual(len(manifests), 1)
        count = 2 if saved else 1
        manifests.pop().fulfill(json=dict(version=1, kind='image-page-stream', page_count=count,
                                        pages=[{} for _ in range(count)] if valid else []))
        if not valid:
            page.locator('.reader-error').wait_for()
            self.assertEqual(page.locator('.reader-page').count(), 0)
            self.assertEqual(images, [])
            return
        page.locator(f'.reader-page[data-page="{count}"] img.ready').wait_for(state='visible')
        self.assertEqual(page.locator('#page-number').input_value(), str(count))
        self.assertEqual(images.count(prefix + f'pages/page-{count:06}.webp'), 1)
        if saved:
            self.assertTrue(images[0].endswith('page-000002.webp'))

    def test_disposal_after_tiff_manifest_validation_releases_pending_image(self):
        prefix = 'pages/image/tiff/' + 'c' * 64 + '/'
        source = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?' + urllib.parse.urlencode({
            'path': prefix + 'page-manifest.json'})
        self.page.add_init_script('''(() => {
          Object.defineProperty(navigator, 'connection', {value:{saveData:false}});
          const NativeImage = window.Image;
          window.Image = function (...args) {
            const image = new NativeImage(...args);
            (window.__openingImages ||= []).push(image);
            return image;
          };
        })()''')
        self.page.route('**/static/reader/core/reader-store.js', lambda route: route.fulfill(
            content_type='text/javascript', body=support.STORE_SCRIPT.replace(
                'new Promise((resolve) => setTimeout(() => resolve(null), 300))', 'Promise.resolve(null)')))
        held = []
        def bucket(route):
            if 'page-manifest.json' in route.request.url:
                route.fulfill(json=dict(version=1, kind='image-page-stream', page_count=1, pages=[{}]))
            else:
                held.append(route)
        self.page.route('**/api/reader-bucket-resource?**', bucket)
        self.page.goto(self.reader_url('image-pages', url=source), wait_until='domcontentloaded')
        self.page.locator('.reader-page img[src]').wait_for(state='attached')
        self.assertTrue(self.page.evaluate('''() => {
          const image = window.__openingImages.find(item => item.src.includes('page-000001.webp'));
          window.dispatchEvent(new Event('voice-reader-dispose'));
          return !image.hasAttribute('src');
        }'''))
        self.assertEqual(len(held), 1)
        self.assertIn('page-000001.webp', held[0].request.url)

    def test_tiff_first_page_renders_before_remaining_shell_batches_finish(self):
        prefix = 'pages/image/tiff/' + 'a' * 64 + '/'
        source = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?' + urllib.parse.urlencode({'path': prefix+'page-manifest.json'})
        data = support.IMAGE_FIXTURES['webp'][1]
        count = 253  # Requires a second shell batch but not large-book virtualization.
        manifest = dict(version=1, kind='image-page-stream', page_count=count,
                        pages=[dict(path=f'pages/page-{page:06}.webp', bytes=len(data), sha256='a'*64)
                               for page in range(1, count+1)])
        def asset(route):
            path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query).get('path', [''])[0]
            if path == prefix+'page-manifest.json':
                route.fulfill(json=manifest)
            else:
                route.fulfill(content_type='image/webp', body=data)
        self.page.route('**/api/reader-bucket-resource?**', asset)
        def hold_shells(route):
            script = route.fetch().text()
            anchor = 'await readerContext.waitForReader();\n    }\n  }'
            self.assertEqual(script.count(anchor), 1)
            route.fulfill(content_type='text/javascript', body=script.replace(anchor, '''
              if (readerContext.capability.mode === 'image-pages' && start === 2)
                await new Promise(resolve=>{window.__releaseImageShells=resolve;});
            '''+anchor))
        self.page.route('**/static/reader/pdf/reader-pdf-page-window.mjs', hold_shells)
        # The validated opening page must render early even on Save-Data.
        self.page.add_init_script('''
          Object.defineProperty(navigator,'connection',{value:{saveData:true}});
          const parse = JSON.parse, stringify = JSON.stringify;
          window.imageManifestWork = {wire:0, synthetic:0};
          JSON.parse = function (value, ...args) {
            const result = parse.call(this,value,...args);
            if (result?.kind === 'image-page-stream') imageManifestWork.wire++;
            if (result?.kind === 'pdf-pages') imageManifestWork.synthetic++;
            return result;
          };
          JSON.stringify = function (value,...args) {
            if (value?.kind === 'pdf-pages') imageManifestWork.synthetic++;
            return stringify.call(this,value,...args);
          };
        ''')
        self.page.goto(self.reader_url('image-pages', url=source), wait_until='domcontentloaded')
        self.page.wait_for_function('()=>!!window.__releaseImageShells')
        self.assertEqual(self.page.locator(f'.reader-page[data-page="{count}"]').count(), 0)
        self.page.locator('.reader-page[data-page="1"] img.ready').wait_for(state='visible')
        self.assertEqual(self.page.evaluate('window.imageManifestWork'), {'wire': 1, 'synthetic': 0})
        self.assertNotEqual(self.page.locator('html').get_attribute('data-reader-phase'), 'ready')
        self.page.evaluate('window.__releaseImageShells()')
        self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'")
        self.assertEqual(self.page.locator('.reader-page').count(), count)
        self.page.locator('#page-number').fill(str(count))
        self.page.locator('#page-number').dispatch_event('change')
        self.page.locator(f'.reader-page[data-page="{count}"] img.ready').wait_for(state='visible')

        # With a saved destination in a later batch, don't race a page-one
        # render against restoration or briefly reveal the wrong image.
        self.page.route('**/static/reader/core/reader-store.js', lambda route: route.fulfill(
            content_type='text/javascript', body=support.STORE_SCRIPT.replace(
                'new Promise((resolve) => setTimeout(() => resolve(null), 300))',
                f'Promise.resolve({{page:{count},zoom:100}})')))
        self.page.reload(wait_until='domcontentloaded')
        self.page.wait_for_function('()=>!!window.__releaseImageShells')
        self.assertEqual(self.page.locator('.reader-page img.ready').count(), 0)
        self.page.evaluate('window.__releaseImageShells()')
        self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'")
        self.assertEqual(self.page.locator('#page-number').input_value(), str(count))
        self.page.locator(f'.reader-page[data-page="{count}"] img.ready').wait_for(state='visible')

    def image_pages_fixture(self, count, data, hold_first=False):
        prefix = 'pages/image/tiff/' + 'a' * 64 + '/'
        source = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?' + urllib.parse.urlencode(
            {'path': prefix + 'page-manifest.json'})
        manifest = dict(version=1, kind='image-page-stream', page_count=count,
                        pages=[dict(path=f'pages/page-{i:06}.webp') for i in range(1, count + 1)])
        held = []
        def resource(route):
            path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)['path'][0]
            if path.endswith('page-manifest.json'):
                route.fulfill(json=manifest)
            elif hold_first and path == prefix + 'pages/page-000001.webp' and not held:
                held.append(route)
            else:
                route.fulfill(content_type='image/webp', body=data)
        self.page.route('**/api/reader-bucket-resource**', resource)
        self.page.add_init_script('''Object.defineProperty(navigator,'connection',{value:{saveData:true}})''')
        self.page.route('**/static/reader/core/reader-store.js', lambda route: route.fulfill(
            content_type='text/javascript', body=support.STORE_SCRIPT.replace(
                'new Promise((resolve) => setTimeout(() => resolve(null), 300))', 'Promise.resolve(null)')))
        self.page.goto(self.reader_url('image-pages', url=source), wait_until='domcontentloaded')
        return held

    def test_image_jump_can_finish_open_and_save_while_old_page_is_stalled(self):
        held = self.image_pages_fixture(12, support.IMAGE_FIXTURES['webp'][1], hold_first=True)
        self.page.locator('.reader-page[data-page="1"] img').wait_for(state='attached')
        field = self.page.locator('#page-number')
        field.fill('12')
        field.dispatch_event('change')
        self.page.locator('.reader-page[data-page="12"] img.ready').wait_for(state='visible')
        self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'")
        self.page.wait_for_function("()=>window.__savedReaderProgress?.page===12")
        self.assertEqual(len(held), 1)
        held[0].abort()

    def test_late_first_image_does_not_reset_wheel_position(self):
        data = support.IMAGE_FIXTURES['webp'][1]
        held = self.image_pages_fixture(6, data, hold_first=True)
        second = self.page.locator('.reader-page[data-page="2"]')
        second.wait_for(state='attached')
        self.page.wait_for_function("()=>!!document.querySelector('.reader-page img')")
        offset = self.page.locator('.reader-page[data-page="1"]').evaluate('n => n.getBoundingClientRect().height + 50')
        self.page.mouse.move(400, 400)
        self.page.mouse.wheel(0, offset)
        self.page.wait_for_function('height => document.querySelector("#viewport").scrollTop >= height - 1', arg=offset)
        self.assertEqual(len(held), 1)
        held[0].fulfill(content_type='image/webp', body=data)
        self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'")
        self.assertGreater(self.page.locator('#viewport').evaluate('n => n.scrollTop'), 100)

    def test_image_pages_save_last_landscape_page_at_scroll_end(self):
        self.page.set_viewport_size({'width': 1100, 'height': 900})
        landscape = self.page.evaluate('''() => {
            const canvas = document.createElement('canvas'); canvas.width = 1000; canvas.height = 200;
            return canvas.toDataURL('image/webp').split(',')[1];
        }''')
        self.image_pages_fixture(6, base64.b64decode(landscape))
        self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'")
        field = self.page.locator('#page-number')
        field.fill('6')
        field.dispatch_event('change')
        self.page.locator('.reader-page[data-page="6"] img.ready').wait_for(state='visible')
        viewport = self.page.locator('#viewport')
        viewport.focus()
        self.page.wait_for_function('''()=>{
            const end=document.querySelector('#viewport'), first=document.querySelector('.reader-page[data-page="4"]');
            return end.scrollHeight-end.clientHeight>2 && first?.querySelector('img.ready') &&
                document.querySelectorAll('.reader-page > img.ready').length===6;
        }''')
        viewport.evaluate('n => { n.scrollTop = n.scrollHeight; }')
        self.page.wait_for_function('()=>window.__savedReaderProgress?.page===6')
        # After the page-jump lock expires, a fresh scroll/save must still pick 6.
        self.page.wait_for_timeout(550)
        viewport.evaluate('n => { n.scrollTop -= 30; }')
        self.page.wait_for_function('''()=>{const n=document.querySelector('#viewport');return n.scrollHeight-n.clientHeight-n.scrollTop>=25;}''')
        viewport.evaluate('n => { n.scrollTop = n.scrollHeight; }')
        self.page.wait_for_function('''()=>{
            const n=document.querySelector('#viewport'), saved=window.__savedReaderProgress;
            return saved?.page===6 && saved.scrollTop===n.scrollTop &&
                n.scrollHeight-n.clientHeight-n.scrollTop<=2 &&
                document.querySelector('#page-number').value==='6';
        }''')

    def test_missing_image_manifest_or_page_recovers_original_without_changing_book_identity(self):
        prefix = 'pages/image/bmp/' + 'a' * 64 + '/'
        manifest_path = prefix + 'page-manifest.json'
        page_path = prefix + 'pages/page-000001.webp'
        source = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?' + urllib.parse.urlencode({'path': manifest_path})
        original = 'https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/original.bmp'
        resolved = dict(url=source, download=original, extension='image-pages', original_extension='bmp')
        self.page.route('**/api/reader-resolve?**', lambda route: route.fulfill(json=resolved))
        self.page.add_init_script("Object.defineProperty(navigator, 'connection', {value:{saveData:false}})")
        store = support.STORE_SCRIPT.replace(
            'new Promise((resolve) => setTimeout(() => resolve(null), 300))',
            '(window.__imageRecoveryLookedUp = true, Promise.resolve(null))')
        self.page.route('**/static/reader/core/reader-store.js', lambda route: route.fulfill(
            content_type='text/javascript', body=store))
        originals = []
        self.page.route('**/api/reader-content?**', lambda route: (
            originals.append(route.request.url), route.fulfill(content_type='image/webp', body=support.IMAGE_FIXTURES['webp'][1])))
        for fault in ('manifest', 'page', 'null-entry', 'too-many', 'too-large'):
            with self.subTest(fault=fault):
                manifest = dict(version=1, kind='image-page-stream', page_count=1,
                                pages=[dict(path='pages/page-000001.webp', bytes=10, sha256='a'*64)])
                if fault == 'null-entry':
                    manifest['pages'] = [None]
                if fault == 'too-many':
                    manifest.update(page_count=100001, pages=[{}] * 100001)
                if fault == 'too-large':
                    manifest['padding'] = 'x' * (8 * 1024 * 1024)
                requested = []

                def resource(route):
                    path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)['path'][0]
                    requested.append(path)
                    if path == manifest_path:
                        if fault != 'manifest':
                            return route.fulfill(json=manifest)
                        # Keep the 404 pending until the empty history lookup can trigger a preload.
                        self.page.wait_for_function('() => window.__imageRecoveryLookedUp === true')
                    return route.fulfill(status=404, body='missing')

                self.page.route('**/api/reader-bucket-resource?**', resource)
                self.open(self.origin+'/static/reader.html?id=0ym7e7wbcxau0&ext=image-pages')
                self.assertTrue(self.page.locator('img.reader-image').evaluate('image => image.naturalWidth > 0'))
                self.assertTrue(self.page.locator('#full-search-toggle').evaluate('node => node.hidden'))
                self.assertEqual(self.page.locator('.reader-page').count(), 0)
                self.assertEqual(self.page.url.split('?')[1], 'id=0ym7e7wbcxau0&ext=image-pages')
                self.page.evaluate('window.dispatchEvent(new Event("voice-reader-dispose"))')
                self.assertEqual(self.page.locator('html').get_attribute('data-reader-phase'), 'disposed')
                self.page.unroute('**/api/reader-bucket-resource?**')
                self.assertEqual(set(requested), {manifest_path, page_path} if fault == 'page' else {manifest_path})
        self.assertEqual(len(originals), 5)

    def test_classic_engine_failure_timeout_and_disposal_release_scripts(self):
        self.page.add_init_script('''const timer = window.setTimeout.bind(window);
          window.setTimeout = (fn, ms, ...args) => timer(fn, ms === 20000 ? 400 : ms, ...args);''')
        for extension, fault in (('md', 'http'), ('html', 'timeout'), ('html', 'dispose')):
            with self.subTest(extension=extension, fault=fault):
                held = []
                pattern = '**/static/vendor/' + ('marked' if extension == 'md' else 'purify') + '.min.*.js'
                self.page.route(pattern, lambda route: route.fulfill(status=503, body='unavailable')
                                if fault == 'http' else held.append(route))
                self.serve('Readable document')
                self.page.goto(self.reader_url(extension), wait_until='domcontentloaded')
                if fault == 'dispose':
                    self.page.wait_for_function("() => !!document.querySelector('script[src*=\"purify.min.\"]')")
                    self.page.evaluate("window.__pendingScript = document.querySelector('script[src*=\"purify.min.\"]'); window.dispatchEvent(new Event('pagehide'))")
                    self.assertEqual(self.page.evaluate('[__pendingScript.isConnected, __pendingScript.onload, __pendingScript.onerror]'), [False, None, None])
                    self.assertEqual(self.page.locator('html').get_attribute('data-reader-phase'), 'disposed')
                else:
                    self.page.locator('#reader-engine-retry').wait_for()
                    self.assertEqual(self.page.locator('#content').get_attribute('data-error-code'), 'READER_ENGINE_NETWORK')
                    self.assertEqual(self.page.locator('script[src*="' + ('marked' if extension == 'md' else 'purify') + '.min."]').count(), 0)
                self.page.unroute(pattern)
                for route in held:
                    route.abort()

    def test_image_wait_releases_listeners_on_success_deadline_and_disposal(self):
        def instrument(route):
            response = route.fetch()
            route.fulfill(response=response, body=response.text() + """
              window.__imageWaitProbe = async () => {
                const timers = new Set(), set = window.setTimeout.bind(window), clear = window.clearTimeout.bind(window);
                window.setTimeout = (fn, ms, ...args) => {
                  let handle; handle = set(() => { timers.delete(handle); fn(...args); }, ms);
                  if (ms === 1000 || ms === 10) timers.add(handle);
                  return handle;
                };
                window.clearTimeout = handle => { timers.delete(handle); clear(handle); };
                const make = () => {
                  const image = new EventTarget(), listeners = new Set();
                  image.complete = false;
                  let decodes = 0;
                  image.decode = async () => { decodes++; };
                  const add = image.addEventListener.bind(image), remove = image.removeEventListener.bind(image);
                  image.addEventListener = (type, fn, ...args) => { listeners.add(type); add(type, fn, ...args); };
                  image.removeEventListener = (type, fn, ...args) => { listeners.delete(type); remove(type, fn, ...args); };
                  return {image, root: {querySelectorAll: () => [image]},
                    metrics: () => [listeners.size, decodes, image.loading]};
                };
                const good = make(), first = settleReaderImages(good.root, 1000);
                good.image.complete = true; good.image.dispatchEvent(new Event('load')); await first;
                const expired = make(); await settleReaderImages(expired.root, 10);
                expired.image.dispatchEvent(new Event('load'));
                const cancelled = make(), pending = settleReaderImages(cancelled.root, 1000).catch(e => e.name);
                readerRuntime.dispose(); const outcome = await pending;
                cancelled.image.dispatchEvent(new Event('load')); await Promise.resolve();
                return [good.metrics(), expired.metrics(), cancelled.metrics(), outcome, timers.size];
              };
            """)
        self.page.route('**/static/reader.js*', instrument)
        self.serve('Image waiting')
        self.open(self.reader_url())
        self.assertEqual(self.page.evaluate('window.__imageWaitProbe()'),
                         [[0, 1, 'eager'], [0, 0, 'eager'], [0, 0, 'eager'], 'AbortError', 0])

    def test_spreadsheet_cells_take_first_viewport_while_images_are_pending(self):
        # Delay only the post-frame image settlement. The sanitized HTML has
        # already loaded, so this distinguishes first paint from restore-ready.
        self.page.set_viewport_size({'width': 390, 'height': 240})
        chart = base64.b64encode(support.IMAGE_FIXTURES['webp'][1]).decode()
        self.serve(f'<section class="reader-spreadsheet-sheet"><table><tr>'
                   f'<td id="first-cell">首行单元格</td><td><img src="data:image/webp;base64,{chart}"></td>'
                   '</tr></table><div style="height:1800px">后续行</div></section>', 'text/html')
        def hold_images(route):
            response = route.fetch()
            script = response.text()
            anchor = 'async function waitForSpreadsheetImages(doc) {'
            self.assertEqual(script.count(anchor), 1)
            route.fulfill(response=response, body=script.replace(anchor, anchor+'''
              await new Promise(resolve=>{window.__releaseSheetImages=resolve;});
            '''))
        self.page.route('**/static/reader/formats/reader-html-format.mjs', hold_images)
        store = support.STORE_SCRIPT.replace('new Promise((resolve) => setTimeout(() => resolve(null), 300))',
                                             'Promise.resolve({htmlScrollTop:420,zoom:100})')
        self.page.route('**/static/reader/core/reader-store.js', lambda route: route.fulfill(
            status=200, content_type='text/javascript', body=store))
        self.page.goto(self.reader_url('html', 'sheet-first-view'), wait_until='domcontentloaded')
        self.page.wait_for_function('()=>!!window.__releaseSheetImages')
        self.assertEqual(self.page.locator('.reader-loading-indicator').count(), 0)
        self.assertNotEqual(self.page.locator('html').get_attribute('data-reader-phase'), 'ready')
        self.assertIsNone(self.page.evaluate('window.__savedReaderProgress || null'))
        self.page.wait_for_function('''()=>{
          const frame=document.querySelector('iframe.spreadsheet-html-frame');
          const cell=frame?.contentDocument?.querySelector('#first-cell');
          return !!cell && frame.getBoundingClientRect().top + cell.getBoundingClientRect().bottom <= innerHeight;
        }''')
        self.page.evaluate('window.__releaseSheetImages()')
        self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'")
        self.assertEqual(self.page.locator('iframe.spreadsheet-html-frame').evaluate('frame=>frame.contentWindow.scrollY'),420)

    def test_native_spreadsheet_html_keeps_cells_selectable_and_zoomable(self):
        chart = support.IMAGE_FIXTURES["webp"][1]
        chart_data = "data:image/webp;base64," + base64.b64encode(chart).decode()
        document = (
            '<!doctype html><html><head><meta charset="utf-8"><style>'
            'body{width:max-content;min-width:100%;margin:0;padding:12px}'
            '.reader-spreadsheet-sheet{width:max-content;min-width:100%}'
            '</style></head><body><section class="reader-spreadsheet-sheet">'
            '<h2>Summary</h2><table><tr><td id="cell">完整单元格文字</td>'
            f'<td><img src="{chart_data}"></td></tr></table></section></body></html>'
        )
        self.serve(document, "text/html")
        self.open(self.reader_url("html", "table"))
        frame_element = self.page.locator("iframe.spreadsheet-html-frame")
        frame_element.wait_for()
        frame = frame_element.element_handle().content_frame()
        self.assertEqual(frame.locator("#cell").text_content().strip(), "完整单元格文字")
        self.assertGreater(frame.locator("img").evaluate("image => image.naturalWidth"), 0)
        before = frame.locator("table").evaluate("node => node.getBoundingClientRect().width")
        self.page.locator("#zoom-in").click(click_count=5)
        self.assertGreater(
            frame.locator("table").evaluate("node => node.getBoundingClientRect().width"), before,
        )

    def test_saved_native_pdf_opens_target_page_first(self):
        store = support.STORE_SCRIPT.replace(
            "get: () => new Promise((resolve) => setTimeout(() => resolve(null), 300)),",
            "get: () => Promise.resolve({page: 12, pageOffset: 20, zoom: 1}),",
        )
        module = support.PDF_MODULE.replace(
            "getPage: () => Promise.resolve(page)",
            "getPage: (number) => { (window.__pdfPageRequests ||= []).push(number); return Promise.resolve(page); }",
        )
        self.page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(content_type="text/javascript", body=store))
        self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route: route.fulfill(content_type="text/javascript", body=module))
        self.serve(b"pdf", "application/pdf")
        self.open(self.reader_url("pdf"))
        self.assertEqual(self.page.evaluate("window.__pdfPageRequests[0]"), 12)
        self.assertEqual(self.page.locator("#page-number").input_value(), "12")
        self.page.locator('.reader-page[data-page="12"] canvas.ready').wait_for()

    def test_saved_djvu_decodes_target_page_first(self):
        store = support.STORE_SCRIPT.replace(
            "get: () => new Promise((resolve) => setTimeout(() => resolve(null), 300)),",
            "get: () => Promise.resolve({page: 12, pageOffset: 0, zoom: 1}),",
        )
        store = store.replace("page: 12", "page: 2")
        state = install_native_djvu(self.page, self.origin)
        def record_page(route):
            response = route.fetch()
            marker = 'async function loadPage(number, priority, signal) {'
            body = response.text()
            self.assertIn(marker, body)
            route.fulfill(response=response, body=body.replace(marker, marker + ' (window.__nativePages ||= []).push(number);'))
        self.page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(content_type="text/javascript", body=store))
        self.page.route("**/static/reader/pdf/reader-djvu-adapter.mjs*", record_page)
        self.open(state["url"])
        self.assertEqual(self.page.evaluate("window.__nativePages[0]"), 2)
        self.assertEqual(self.page.locator("#page-number").input_value(), "2")
        self.page.locator('.reader-page[data-page="2"] canvas.ready').wait_for()
        self.assertTrue(all(row["range"] for row in state["source"]))

    def test_native_pdf_reuses_text_after_layer_is_cleared(self):
        module = support.PDF_MODULE.replace("numPages: 30", "numPages: 1").replace(
            "getTextContent() { return Promise.resolve",
            "getTextContent() { window.__pdfTextCalls = (window.__pdfTextCalls || 0) + 1; return Promise.resolve",
        )
        self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route: route.fulfill(content_type="text/javascript", body=module))
        def instrument(route):
            response = route.fetch()
            route.fulfill(response=response, body=response.text() + "\nwindow.__reloadPdfText = async () => { const shell = document.querySelector('.reader-page[data-page=\\\"1\\\"]'); shell.querySelector('.reader-pdf-text').replaceChildren(); shell.dataset.textReady = '0'; await renderPdfText(await pdfDocument.getPage(1), shell); };\n")
        self.page.route("**/static/reader.js*", instrument)
        self.serve(b"pdf", "application/pdf")
        self.open(self.reader_url("pdf"))
        self.page.wait_for_function("() => document.querySelector('.reader-page[data-page=\\\"1\\\"]')?.dataset.textReady === '1'")
        before = self.page.evaluate("window.__pdfTextCalls")
        self.page.evaluate("window.__reloadPdfText()")
        self.assertEqual(self.page.evaluate("window.__pdfTextCalls"), before)
        self.assertIn("Accessible PDF text", self.page.locator('.reader-page[data-page="1"] .reader-pdf-text').text_content())

    def test_saved_chapter_book_fetches_target_first(self):
        store = support.STORE_SCRIPT.replace(
            "get: () => new Promise((resolve) => setTimeout(() => resolve(null), 300)),",
            "get: () => Promise.resolve({chapterIndex: 8, chapterOffset: 0}),",
        )
        root = "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=chapters/ebook/chm/" + "a" * 64 + "/1234567890abcdef"
        manifest = {"version": 1, "kind": "epub-chapters", "chapters": [
            {"index": i, "path": f"chapters/chapter-{i:04d}.xhtml", "bytes": 100} for i in range(1, 13)
        ]}
        requested = []
        self.page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(content_type="text/javascript", body=store))
        def resource(route):
            path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query).get("path", [""])[0]
            if path.endswith(".xhtml"):
                number = int(path.rsplit("chapter-", 1)[1].split(".", 1)[0])
                requested.append(number)
                route.fulfill(content_type="text/html", body=f"<h1>Chapter {number}</h1><p>Content</p>")
            else:
                route.fulfill(json=manifest)
        self.page.route("**/api/reader-bucket-resource**", resource)
        self.open(self.reader_url("epub-chapters", url=root + "/chapter-manifest.json"))
        self.assertEqual(requested[0], 8)
        self.assertNotIn(1, requested)
        self.assertTrue(self.page.locator('.reader-epub-chapter[data-chapter="8"]').is_visible())
        support.open_reader_panel(self.page)
        self.page.locator('#toc-list .panel-item-main').nth(6).click()
        self.page.locator('.reader-epub-chapter[data-chapter="7"]').wait_for(state="attached")
        self.page.wait_for_function("() => document.querySelector('.reader-chapter-sentinel[data-chapter=\\\"6\\\"]') || document.querySelector('.reader-epub-chapter[data-chapter=\\\"6\\\"]')")
        self.page.evaluate("() => document.querySelector('.reader-chapter-sentinel[data-chapter=\\\"6\\\"]')?.click()")
        self.page.locator('.reader-epub-chapter[data-chapter="6"]').wait_for(state="attached")
        self.assertNotIn(1, requested)

    def test_djvu_recovers_ocr_text_and_searches_valid_index(self):
        state = install_native_djvu(self.page, self.origin, ocr=True, fail_page_once=True)
        self.open(state["url"])
        self.page.locator('.reader-page[data-page="1"] canvas.ready').wait_for()
        self.page.wait_for_function("() => !document.querySelector('.reader-page[data-page=\"1\"]')._ocrPromise")
        self.assertEqual(state["page_attempts"].count(1), 1)
        self.page.wait_for_function("() => document.querySelector('.reader-page[data-page=\"1\"]')?.dataset.nativeTextFallback === '1'")
        self.assertIn('Page1text', self.page.locator('.reader-page[data-page="1"] .reader-pdf-text').text_content())
        self.page.locator('#zoom-in').click()
        self.page.wait_for_function("() => document.querySelector('.reader-page[data-page=\"1\"] .reader-pdf-text')?.textContent.includes('OCR first preserved')")
        self.assertEqual(state["page_attempts"].count(1), 2)
        self.assertIn(state["texts"][0], self.page.locator('.reader-page[data-page="1"] .reader-pdf-text').text_content())
        self.assertTrue(state["source"] and all(row["range"] is None for row in state["source"]))
        self.page.locator('#history').click()
        self.page.locator('#full-search-toggle').click()
        self.page.locator('#full-search-input').fill('OCR first')
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")
        self.assertEqual(self.page.locator('.full-search-result').count(), 1)
        self.assertFalse(self.page.locator('.reader-page img').count())

    def test_djvu_ocr_uses_versioned_paths_and_selection(self):
        state = install_native_djvu(self.page, self.origin, ocr=True)
        self.open(state["url"])
        self.page.locator('.reader-page[data-page="1"][data-text-ready="1"] canvas.ready').wait_for()
        self.assertEqual(state["assets"].count(state["ocr_path"]), 1)
        self.assertTrue(state["source"] and all(row["range"] is None for row in state["source"]))
        for number in (1, 2):
            self.page.locator('#page-number').fill(str(number))
            self.page.locator('#page-number').dispatch_event('change')
            shell = self.page.locator(f'.reader-page[data-page="{number}"]')
            shell.locator('canvas.ready').wait_for()
            self.page.wait_for_function("n => document.querySelector(`.reader-page[data-page=\"${n}\"]`)?.dataset.textReady === '1'", arg=number)
            self.assertIn(state["texts"][number - 1], shell.locator('.reader-pdf-text').text_content())
        selected = self.page.locator('.reader-page[data-page="2"] .reader-pdf-text').evaluate("""node => {
          const range=document.createRange();range.selectNodeContents(node);
          const selection=getSelection();selection.removeAllRanges();selection.addRange(range);return selection.toString();
        }""")
        self.assertIn(state["texts"][1], selected)
        self.assertFalse(self.page.locator('.reader-page img').count())
        self.assertFalse([path for path in state["assets"] if '/pages/page-' in path])

    def test_djvu_mismatched_ocr_is_never_attached(self):
        state = install_native_djvu(self.page, self.origin, ocr=True, mismatch=True)
        self.open(state["url"])
        self.page.locator('.reader-page[data-page="1"][data-text-ready="1"] canvas.ready').wait_for()
        text = self.page.locator('.reader-page[data-page="1"] .reader-pdf-text').text_content()
        self.assertIn('Page1text', text)
        self.assertNotIn(state['texts'][0], text)
        self.assertEqual(state['page_attempts'], [])
        self.assertEqual(state['assets'], [state['ocr_path']])
        self.assertTrue(state['source'] and all(row['range'] is None for row in state['source']))

    def test_download_during_prepare_does_not_interrupt_reader(self):
        pending_content = []
        checks = []
        downloads = []
        def slow_content(route):
            pending_content.append(route)
        def check_download(route):
            checks.append(route.request.url)
            if len(checks) == 1:
                route.fulfill(status=503, content_type="application/json", body=json.dumps({"error": "下载检查失败,请重试"}))
            else:
                route.fulfill(content_type="application/json", body=json.dumps({"ok": True}))
        def serve_download(route):
            downloads.append(route.request.url)
            route.fulfill(content_type="application/octet-stream", body=b"download",
                          headers={"Content-Disposition": "attachment; filename*=UTF-8''refactor.txt"})
        self.page.route("**/api/reader-content**", slow_content)
        self.page.route("**/api/download/check**", check_download)
        self.page.route("**/api/download?**", serve_download)
        self.page.goto(self.reader_url("txt"), wait_until="domcontentloaded")
        self.page.wait_for_function("() => document.querySelector('#download').hasAttribute('href')")
        self.assertNotEqual(self.page.locator("html").get_attribute("data-reader-phase"), "ready")
        self.page.locator("#download").click()
        self.page.wait_for_function("() => document.querySelector('#download-feedback').textContent === '下载检查失败,请重试'")
        self.assertEqual(len(checks), 1)
        self.assertEqual(downloads, [])
        self.assertNotIn("原文件", self.page.locator("#status").text_content())
        self.page.set_viewport_size({"width": 390, "height": 844})
        self.assertTrue(self.page.locator("#download-feedback").evaluate("""node => {
            const message = node.getBoundingClientRect();
            const button = document.querySelector('#download').getBoundingClientRect();
            return message.left >= 0 && message.right <= innerWidth && message.top >= button.bottom;
        }"""))
        with self.page.expect_download() as event:
            self.page.locator("#download").click()
        self.assertEqual(event.value.suggested_filename, "refactor.txt")
        self.assertEqual(self.page.locator("html").get_attribute("data-reader-phase"), "prepare")
        self.assertEqual(len(checks), 2)
        self.assertEqual(len(downloads), 1)
        pending_content[0].fulfill(status=200, content_type="text/plain", body="Reader download")
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        self.assertIn("Reader download", self.page.locator("#content").text_content())

    def test_id_only_download_joins_reader_resolution(self):
        resolved = []
        content = []
        checks = []
        source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/shared.txt"
        self.page.route("**/api/reader-resolve?**", lambda route: resolved.append(route))
        self.page.route("**/api/reader-content?**", lambda route: content.append(route))
        self.page.route("**/api/download/check?**", lambda route: (
            checks.append(route.request.url), route.fulfill(json={"ok": True})))
        self.page.route("**/api/download?**", lambda route: route.fulfill(
            body=b"original", headers={"Content-Disposition": "attachment; filename=shared.txt"}))
        self.page.goto(self.origin + "/static/reader.html?id=" + "a" * 13 + "&ext=txt", wait_until="domcontentloaded")
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'resolve'")
        self.page.locator("#download").click()
        self.page.locator("#download").click()
        self.assertEqual(len(resolved), 1)
        self.assertEqual(checks, [])
        with self.page.expect_download() as event:
            resolved[0].fulfill(json={"url": source, "download": source, "title": "shared", "extension": "txt"})
        self.assertEqual(event.value.suggested_filename, "shared.txt")
        self.assertEqual(len(checks), 1)
        self.assertEqual(self.page.locator("html").get_attribute("data-reader-phase"), "prepare")
        content[0].fulfill(body="Resolved text")
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")

    def test_pdf_can_finish_preparing_after_download_starts(self):
        pending_content = []
        self.page.route("**/api/reader-content**", lambda route: pending_content.append(route))
        self.page.route("**/api/download/check**", lambda route: route.fulfill(json={"ok": True}))
        self.page.route("**/api/download?**", lambda route: route.fulfill(
            content_type="application/octet-stream", body=b"original",
            headers={"Content-Disposition": "attachment; filename=book.pdf"}))
        self.page.goto(self.reader_url("pdf"), wait_until="domcontentloaded")
        self.page.wait_for_function("() => document.querySelector('#download').hasAttribute('href')")
        with self.page.expect_download() as event:
            self.page.locator("#download").click()
        self.assertEqual(event.value.suggested_filename, "book.pdf")
        self.assertEqual(self.page.locator("html").get_attribute("data-reader-phase"), "prepare")
        self.page.wait_for_timeout(200)
        self.assertTrue(pending_content)
        pending_content[0].fulfill(content_type="application/pdf", body=support.minimal_pdf())
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        self.page.locator('.reader-page[data-page="1"] canvas.ready').wait_for(state="attached")

    def test_pdf_retries_transient_proxy_failure_while_download_starts(self):
        requests, held = [], []
        direct = []
        def reader_content(route):
            requests.append(route)
            if len(requests) > 1:
                route.fulfill(content_type="application/pdf", body=support.minimal_pdf())
        self.page.route("**/api/reader-content**", reader_content)
        self.page.route("https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/refactor.pdf",
                        lambda route: (direct.append(route.request.url), route.abort()))
        self.page.route("**/api/download/check**", lambda route: route.fulfill(json={"ok": True}))
        self.page.route("**/api/download?**", lambda route: route.fulfill(
            body=b"original", headers={"Content-Disposition": "attachment; filename=refactor.pdf"}))
        for fault in ("http", "transport"):
            with self.subTest(fault=fault):
                requests.clear()
                with self.page.expect_request("**/api/reader-content**"):
                    self.page.goto(self.reader_url("pdf"), wait_until="domcontentloaded")
                self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'prepare'")
                with self.page.expect_download() as event:
                    self.page.locator("#download").click()
                self.assertEqual(event.value.suggested_filename, "refactor.pdf")
                self.page.wait_for_function("() => document.querySelector('#download-feedback').textContent === '已发起下载'")
                self.assertEqual(len(requests), 1)
                if fault == "http":
                    requests[0].fulfill(status=503, body="temporary")
                else:
                    requests[0].abort("failed")
                self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
                self.page.locator('.reader-page[data-page="1"] canvas.ready').wait_for(state="attached")
                self.assertEqual(len(requests), 2)
                self.assertEqual(direct, [])

    def test_failed_reader_still_allows_original_download(self):
        checks = []
        def check(route):
            checks.append(route.request.url)
            if len(checks) == 1:
                route.fulfill(status=503, json={"error": "暂时无法检查下载"})
            else:
                route.fulfill(json={"ok": True})
        self.page.route("**/api/download/check**", check)
        self.page.route("**/api/download?**", lambda route: route.fulfill(
            body=b"original", headers={"Content-Disposition": "attachment; filename=original.xyz"}))
        self.page.goto(self.reader_url("xyz"))
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'failed'")
        self.assertIn("请下载原文件", self.page.locator(".reader-error").text_content())
        self.page.locator("#download").click()
        self.page.wait_for_function("() => document.querySelector('#download-feedback').textContent === '暂时无法检查下载'")
        with self.page.expect_download() as event:
            self.page.locator("#download").click()
        self.assertEqual(event.value.suggested_filename, "original.xyz")
        self.assertEqual(len(checks), 2)

    def test_pdf_embedded_ocr_selection_search_and_pagination(self):
        module = support.PDF_MODULE.replace("numPages: 30", "numPages: 3").replace(
            "return { width: 600 * scale, height: 800 * scale };",
            "return { width: 600 * scale, height: 800 * scale, scale, transform: [scale,0,0,-scale,0,800*scale], convertToViewportPoint:(x,y)=>[x*scale,(800-y)*scale] };")
        module = module.replace(
            "getTextContent() { return Promise.resolve",
            "async getTextContent() { await new Promise(resolve => setTimeout(resolve, 30)); return Promise.resolve"
        )
        items = [dict(str=s, transform=[20, 0, 0, 20, x, 700], width=w, height=20, fontName="f")
                 for s, x, w in [("毛 ", 50, 30), ("泽", 80, 20), (" 东", 100, 30), (" 手。机 hello world", 130, 200)]]
        items += [dict(str="毛 泽 东", transform=[20, 0, 0, 20, 50, 650-i*10],
                       width=80, height=20, fontName="f", hasEOL=True) for i in range(40)]
        items.append(dict(str="竖 排 正 文", transform=[20, 0, 0, 20, 500, 700],
                          width=20, height=140, dir="ttb", fontName="f"))
        text = json.dumps(dict(items=items, styles={"f": dict(fontFamily="sans-serif", ascent=0.8)}), ensure_ascii=False)
        module = module.replace("{ items: [{ str: 'Accessible PDF text', hasEOL: false }] }", text)
        self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route: route.fulfill(content_type="text/javascript", body=module))
        self.open(self.reader_url("pdf"))
        run = self.page.locator('.reader-page[data-page="1"] .reader-pdf-text-run').first
        def bounds():
            return run.evaluate("""node => {const r=node.getBoundingClientRect(), p=node.closest('.reader-page').getBoundingClientRect();
              return {x:(r.x-p.x)/p.width,y:(r.y-p.y)/p.height,width:r.width/p.width,height:r.height/p.width,
                hit:document.elementFromPoint(r.x+2,r.y+2)===node};} """)
        before = bounds()
        self.assertAlmostEqual(before['x'], 50/600, delta=0.002)
        self.assertAlmostEqual(before['y'], 84/800, delta=0.002)
        self.assertAlmostEqual(before['width'], 30/600, delta=0.002)
        self.assertTrue(before['hit'])
        vertical = self.page.locator('.reader-page[data-page="1"] .reader-pdf-text-run').last
        self.assertAlmostEqual(vertical.evaluate("e=>e.getBoundingClientRect().height/e.closest('.reader-page').getBoundingClientRect().height"), 140/800, delta=0.003)
        self.page.set_viewport_size({"width": 390, "height": 844})
        after = bounds()
        for key in ('x', 'y', 'width', 'height'):
            self.assertAlmostEqual(before[key], after[key], delta=0.003)
        selected = run.evaluate("""node => {const r=document.createRange();r.selectNodeContents(node);
          const s=getSelection();s.removeAllRanges();s.addRange(r);return s.toString();}""")
        self.assertEqual(selected, '毛 ')
        self.page.evaluate('getSelection().removeAllRanges()')
        self.page.locator('#history').click()
        self.page.locator('#full-search-toggle').click()
        self.page.locator('#full-search-input').fill('毛泽东')
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent.includes('正在搜索') && document.querySelectorAll('.full-search-result').length > 0")
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '123 个结果'")
        self.assertEqual(self.page.locator('.full-search-result').count(), 50)
        self.assertEqual(self.page.locator('.reader-page[data-page="1"] mark').first.text_content(), '毛 ')
        self.page.locator('#full-search-page-next').click()
        self.page.wait_for_function("() => document.querySelector('#full-search-page').value === '2'")
        self.page.locator('#full-search-page-next').click()
        self.page.wait_for_function("() => document.querySelector('#full-search-page').value === '3'")
        self.assertEqual(self.page.locator('.full-search-result').count(), 23)
        self.page.locator('.full-search-result').last.click()
        self.assertEqual(self.page.locator('#page-number').input_value(), '3')
        self.page.locator('#history').click()
        self.assertFalse(self.page.locator('#full-search-view').is_hidden())
        self.page.locator('#full-search-input').fill('手机')
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '未找到正文匹配'")
        self.page.locator('#full-search-input').fill('hello world')
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '3 个结果'")

    def test_pdf_first_query_reuses_rendered_page_text(self):
        module = support.PDF_MODULE.replace("numPages: 30", "numPages: 1").replace(
            "getTextContent() { return Promise.resolve",
            "getTextContent() { window.__pdfTextCalls = (window.__pdfTextCalls || 0) + 1; return Promise.resolve",
        )
        self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route: route.fulfill(
            content_type="text/javascript", body=module))
        self.open(self.reader_url("pdf"))
        self.page.wait_for_function("() => document.querySelector('.reader-page')?.dataset.textReady === '1'")
        self.search("Accessible")
        self.assertEqual(self.page.locator("#full-search-status").text_content(), "1 个结果")
        self.assertEqual(self.page.evaluate("window.__pdfTextCalls"), 1)

    def test_pdf_search_and_research_share_pending_render_text(self):
        module = support.PDF_MODULE.replace("numPages: 30", "numPages: 1").replace(
            "getTextContent() { return Promise.resolve({ items: [{ str: 'Accessible PDF text', hasEOL: false }] }); },",
            """getTextContent() {
              window.__pdfTextCalls = (window.__pdfTextCalls || 0) + 1;
              return window.__heldText ||= new Promise(resolve => {
                window.__releaseText = () => resolve({items: [{str: 'Accessible PDF text', hasEOL: false}]});
              });
            },""",
        )
        self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route: route.fulfill(
            content_type="text/javascript", body=module))
        def instrument(route):
            response = route.fetch()
            route.fulfill(response=response, body=response.text() + """
              const originalSearchText = loadPdfSearchText;
              loadPdfSearchText = (...args) => {
                window.__searchTextRequests = (window.__searchTextRequests || 0) + 1;
                return originalSearchText(...args);
              };
            """)
        self.page.route("**/static/reader.js*", instrument)
        self.open(self.reader_url("pdf"))
        self.page.wait_for_function("() => !!window.__releaseText")
        self.page.locator("#history").click()
        self.page.locator("#full-search-toggle").click()
        self.page.locator("#full-search-input").fill("Accessible")
        self.page.wait_for_function("() => window.__searchTextRequests === 1")
        self.page.locator("#full-search-input").fill("PDF")
        self.page.wait_for_function("() => window.__searchTextRequests === 2")
        self.assertEqual(self.page.evaluate("window.__pdfTextCalls"), 1)
        self.page.evaluate("window.__releaseText()")
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")
        self.page.wait_for_function("() => document.querySelector('.reader-page')?.dataset.textReady === '1'")
        self.assertIn("PDF", self.page.locator(".full-search-result").text_content())

    def test_pdf_second_query_reuses_extracted_page_text(self):
        module = support.PDF_MODULE.replace(
            "getTextContent() { return Promise.resolve",
            "getTextContent() { window.__pdfTextCalls = (window.__pdfTextCalls || 0) + 1; return Promise.resolve"
        )
        self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route: route.fulfill(
            content_type="text/javascript", body=module))
        self.open(self.reader_url("pdf"))
        self.page.locator("#history").click()
        self.page.locator("#full-search-toggle").click()
        self.page.locator("#full-search-input").fill("Accessible")
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '30 个结果'")
        first = self.page.evaluate("window.__pdfTextCalls")
        self.page.locator("#full-search-input").fill("PDF")
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '30 个结果'")
        self.assertEqual(self.page.evaluate("window.__pdfTextCalls"), first)

    def test_pdf_text_failure_retries_and_disposal_releases_pending_work(self):
        def instrument(route):
            response = route.fetch()
            route.fulfill(response=response, body=response.text() + """
              window.__textOwnershipProbe = async () => {
                let calls = 0;
                const page = {getTextContent() {
                  calls++;
                  if (calls === 1) throw Error('extraction failed');
                  return {items: [{str: 'retry succeeded'}]};
                }};
                const failure = await loadPdfTextContent(999, page).catch(error => error.message);
                const text = await loadPdfTextContent(999, page);
                const settled = pdfTextContentPromises.size;
                let release, started;
                const startedPromise = new Promise(resolve => { started = resolve; });
                const pending = loadPdfTextContent(1000, {getTextContent: () =>
                  new Promise(resolve => { release = resolve; started(); })}).catch(error => error.name);
                await startedPromise;
                readerRuntime.dispose();
                const disposed = pdfTextContentPromises.size;
                const outcome = await pending;
                release({items: [{str: 'obsolete'}]});
                await Promise.resolve();
                return [failure, calls, text.items[0].str, settled, disposed, outcome,
                  pdfTextContentCache.size, pdfTextContentCacheBytes];
              };
            """)
        self.page.route("**/static/reader.js*", instrument)
        self.serve(support.minimal_pdf(), "application/pdf")
        self.open(self.reader_url("pdf"))
        self.page.wait_for_function("() => document.querySelector('.reader-page')?.dataset.textReady === '1'")
        self.assertEqual(self.page.evaluate("window.__textOwnershipProbe()"),
                         ["extraction failed", 2, "retry succeeded", 0, 0, "AbortError", 0, 0])

    def test_pdf_search_cache_cleanup_resets_byte_budget(self):
        def instrument(route):
            response = route.fetch()
            route.fulfill(response=response, body=response.text() + "\nwindow.__pdfCacheProbe = () => { cachePdfSearchText(1, 'cached'); readerRuntime.dispose(); return [pdfSearchTextCache.size, pdfSearchTextCacheBytes]; };\n")
        self.page.route("**/static/reader.js*", instrument)
        self.serve(support.minimal_pdf(), "application/pdf")
        self.open(self.reader_url("pdf"))
        self.assertEqual(self.page.evaluate("window.__pdfCacheProbe()"), [0, 0])

    def test_pdf_search_pages_reextract_evicted_text_and_ignore_cancelled_load(self):
        def instrument(route):
            response = route.fetch()
            route.fulfill(response=response, body=response.text() + "\nwindow.__dropPdfSearchCache = () => { pdfSearchTextCache.clear(); pdfSearchTextCacheBytes = 0; pdfTextContentCache.clear(); pdfTextContentCacheBytes = 0; };\n")
        self.page.route("**/static/reader.js*", instrument)
        module = support.PDF_MODULE.replace("numPages: 30", "numPages: 3").replace(
            "getPage: () => Promise.resolve(page)", """getPage: (number) => Promise.resolve({ ...page,
              getTextContent() {
                window.__pdfTextCalls = (window.__pdfTextCalls || 0) + 1;
                if (number === 1 && window.__holdPdfPage) {
                  window.__holdPdfPage = false;
                  return new Promise(resolve => { window.__releasePdfPage = () => resolve({ items: [{ str: 'needle '.repeat(60), hasEOL: false }] }); });
                }
                return Promise.resolve({ items: [{ str: 'needle '.repeat(60), hasEOL: false }] });
              } })""")
        self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route: route.fulfill(
            content_type="text/javascript", body=module))
        self.open(self.reader_url("pdf"))
        self.search("needle")
        self.assertEqual(self.page.locator("#full-search-status").text_content(), "180 个结果")
        self.assertEqual(self.page.locator(".full-search-result").count(), 50)
        self.page.evaluate("window.__dropPdfSearchCache()")
        calls = self.page.evaluate("window.__pdfTextCalls")
        self.page.locator("#full-search-page-next").click()
        self.page.wait_for_function("() => document.querySelector('.full-search-rank')?.textContent === '51.'")
        self.assertGreater(self.page.evaluate("window.__pdfTextCalls"), calls)
        self.page.locator("#full-search-page").fill("4")
        self.page.locator("#full-search-page").dispatch_event("change")
        self.page.wait_for_function("() => document.querySelector('.full-search-rank')?.textContent === '151.'")
        self.assertEqual(self.page.locator(".full-search-result").count(), 30)
        self.assertEqual(self.page.locator(".full-search-result").first.locator("small").text_content(), "第 3 页")
        self.page.evaluate("() => { window.__dropPdfSearchCache(); window.__holdPdfPage = true; }")
        self.page.locator("#full-search-page").fill("2")
        self.page.locator("#full-search-page").dispatch_event("change")
        self.page.wait_for_function("() => !!window.__releasePdfPage && document.querySelector('#full-search-status').textContent === '180 个结果'")
        self.page.locator("#full-search-cancel").click()
        self.page.evaluate("window.__releasePdfPage()")
        self.page.wait_for_timeout(100)
        self.assertEqual(self.page.locator("#full-search-status").text_content(), "搜索已取消")
        self.assertEqual(self.page.locator(".full-search-result").count(), 0)
        self.page.locator("#full-search-retry").click()
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '180 个结果'")
        self.page.locator("#full-search-page").fill("4")
        self.page.locator("#full-search-page").dispatch_event("change")
        self.page.wait_for_function("() => document.querySelector('.full-search-rank')?.textContent === '151.'")
        self.page.locator(".full-search-result").first.click()
        self.page.wait_for_function("() => document.querySelector('#page-number').value === '3'")

    def test_pdf_deep_result_page_can_cancel_while_skipping_hits(self):
        def instrument(route):
            response = route.fetch()
            script = response.text().replace(
                "function waitForReader(delay = 0, animationFrame = false) {",
                """function waitForReader(delay = 0, animationFrame = false) {
                  if (window.__holdSearchPage && delay === 0 && !animationFrame) {
                    window.__holdSearchPage = false;
                    return new Promise(resolve => { window.__releaseSearchPage = resolve; });
                  }"""
            )
            route.fulfill(response=response, body=script)
        self.page.route("**/static/reader/core/reader-lifecycle.mjs*", instrument)
        module = support.PDF_MODULE.replace("numPages: 30", "numPages: 2").replace(
            "getPage: () => Promise.resolve(page)", """getPage: () => Promise.resolve({ ...page,
              getTextContent() { return Promise.resolve({ items: [{ str: 'needle '.repeat(6000), hasEOL: false }] }); } })""")
        self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route: route.fulfill(
            content_type="text/javascript", body=module))
        self.open(self.reader_url("pdf"))
        self.search("needle")
        self.assertEqual(self.page.locator("#full-search-status").text_content(), "12000 个结果")
        self.page.evaluate("window.__holdSearchPage = true")
        self.page.locator("#full-search-page").fill("200")
        self.page.locator("#full-search-page").dispatch_event("change")
        self.page.wait_for_function("() => !!window.__releaseSearchPage && document.querySelector('#full-search-status').textContent === '12000 个结果'")
        self.page.locator("#full-search-cancel").click()
        self.page.evaluate("window.__releaseSearchPage()")
        self.page.wait_for_timeout(100)
        self.assertEqual(self.page.locator("#full-search-status").text_content(), "搜索已取消")
        self.assertEqual(self.page.locator(".full-search-result").count(), 0)

    def test_failed_pdf_search_page_retry_keeps_target_page(self):
        def instrument(route):
            response = route.fetch()
            needle = "async function loadPdfSearchText(pdf, page, generation) {"
            script = response.text()
            self.assertIn(needle, script)
            route.fulfill(response=response, body=script.replace(needle, needle + """
              if (page === 2 && window.__failSearchPage) {
                window.__failSearchPage = false;
                throw new Error('temporary page load');
              }"""))
        self.page.route("**/static/reader/pdf/reader-pdf-search.mjs*", instrument)
        module = support.PDF_MODULE.replace("numPages: 30", "numPages: 3").replace(
            "getPage: () => Promise.resolve(page)", """getPage: () => Promise.resolve({ ...page,
              getTextContent() { return Promise.resolve({ items: [{ str: 'needle '.repeat(60), hasEOL: false }] }); } })""")
        self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route: route.fulfill(
            content_type="text/javascript", body=module))
        self.open(self.reader_url("pdf"))
        self.search("needle")
        self.page.locator("#full-search-page-next").click()
        self.page.wait_for_function("() => document.querySelector('.full-search-rank')?.textContent === '51.'")
        self.page.evaluate("window.__failSearchPage = true")
        self.page.locator("#full-search-page-next").click()
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === 'temporary page load'")
        self.assertEqual(self.page.locator("#full-search-retry").text_content(), "重试本页")
        self.assertEqual(self.page.locator(".full-search-rank").first.text_content(), "51.")
        self.page.locator("#full-search-toggle").click()
        self.page.locator("#full-search-toggle").click()
        self.assertTrue(self.page.locator("#full-search-retry").is_visible())
        self.page.locator("#full-search-retry").click()
        self.page.wait_for_function("() => document.querySelector('.full-search-rank')?.textContent === '101.'")
        self.assertEqual(self.page.locator("#full-search-page").input_value(), "3")
        self.assertEqual(self.page.locator("#full-search-status").text_content(), "180 个结果")

    def test_pdf_with_unavailable_ocr_index_falls_back_to_native_text(self):
        self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route: route.fulfill(
            content_type="text/javascript", body=support.PDF_MODULE))
        manifest = self.origin + "/api/reader-bucket-resource?path=objects/aa/" + "a" * 64 + "/" + "b" * 16 + "/ocr-manifest.json"
        self.page.route("**/api/reader-bucket-resource**", lambda route: route.fulfill(status=503, body="unavailable"))
        self.open(self.reader_url("pdf", ocr_manifest=manifest))
        self.page.locator("#history").click()
        self.page.locator("#full-search-toggle").click()
        self.page.locator("#full-search-input").fill("Accessible")
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '30 个结果'")
        self.assertEqual(self.page.locator(".full-search-result").count(), 30)

    def test_pdf_with_valid_ocr_index_searches_index_not_native_text(self):
        self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route: route.fulfill(
            content_type="text/javascript", body=support.PDF_MODULE.replace("numPages: 30", "numPages: 1").replace(
                "getTextContent() { return Promise.resolve", "getTextContent() { window.__nativeTextReads=(window.__nativeTextReads||0)+1; return Promise.resolve")))
        root = "objects/aa/" + "a" * 64 + "/" + "b" * 16
        manifest_path = root + "/ocr-manifest.json"
        book_path = root + "/ocr/book-text.json.gz"
        text = "索引独有文字"
        book = gzip.compress(json.dumps({"version": 2, "kind": "pdf-book-text", "complete": True,
            "offset_unit": "unicode-codepoint", "source_sha256": "a" * 64,
            "page_count": 1, "pages": [{"page": 1, "text": text,
                "layout": {"offset_unit": "unicode-codepoint"},
                "text_spans": [{"start": 0, "end": len(text), "box": [0.1, 0.2, 0.4, 0.3]}]}]}).encode())
        manifest = {"version": 1, "kind": "pdf-ocr", "complete": True,
            "source_sha256": "a" * 64, "profile": "test-layout-v1-index",
            "page_count": 1, "pages": [{"p": 1, "o": root + "/ocr/page-000001.json.gz"}],
            "book_text": {"path": book_path, "bytes": len(book), "sha256": hashlib.sha256(book).hexdigest()}}
        requests, held = [], []
        def resource(route):
            path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)["path"][0]
            requests.append(path)
            if path == manifest_path:
                route.fulfill(json=manifest)
            elif path == book_path:
                route.fulfill(content_type="application/gzip", body=book)
            else:
                route.fulfill(status=404)
        self.page.route("**/api/reader-bucket-resource**", resource)
        manifest_url = self.origin + "/api/reader-bucket-resource?path=" + manifest_path
        self.open(self.reader_url("pdf", ocr_manifest=manifest_url))
        self.page.wait_for_timeout(7000)
        layer_path = root + "/ocr/page-000001.json.gz"
        self.assertEqual([path for path in requests if path != layer_path], [manifest_path, book_path])
        self.assertLessEqual(requests.count(layer_path), 1)
        native_reads = self.page.evaluate("window.__nativeTextReads || 0")
        self.page.locator("#history").click()
        self.page.locator("#full-search-toggle").click()
        self.page.locator("#full-search-input").fill("索引独有")
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")
        self.assertEqual(self.page.locator(".full-search-result").count(), 1)
        self.assertEqual([path for path in requests if path != layer_path], [manifest_path, book_path])
        self.assertLessEqual(requests.count(layer_path), 1)
        self.assertEqual(self.page.evaluate("window.__nativeTextReads || 0"), native_reads)
        self.page.locator('.full-search-result').click()
        self.page.locator('.reader-page[data-page="1"] .reader-text-hit-box').wait_for(state='attached')

    def test_pdf_ocr_progress_preserves_full_first_page_and_focus(self):
        def pause_after_first_page(route):
            response = route.fetch()
            script = response.text()
            pause = """
                if (scanned === 1) await new Promise(resolve => {
                  const release = event => {
                    if (event.data.type !== 'test-release') return;
                    self.removeEventListener('message', release);
                    resolve();
                  };
                  self.addEventListener('message', release);
                });"""
            legacy = "scanned, pages, ...partial.page(0) });"
            partitioned = "scanned, pages, ...page });"
            if legacy in script:
                script = script.replace("progress: (partial, scanned, pages) => {",
                    "progress: async (partial, scanned, pages) => {")
                script = script.replace(legacy, legacy + pause, 1)
            else:
                self.assertIn(partitioned, script)
                message = "self.postMessage({ id: data.id, session: session.id, progress: true,\n            " + partitioned
                script = script.replace(message, pause + "\n          " + message, 1)
            route.fulfill(response=response, body=script)
        self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route: route.fulfill(
            content_type="text/javascript", body=support.PDF_MODULE.replace("numPages: 30", "numPages: 3")))
        root = "objects/aa/" + "a" * 64 + "/" + "b" * 16
        manifest_path = root + "/ocr-manifest.json"
        book_path = root + "/ocr/book-text.json.gz"
        texts = ["needle " * 60, "needle", "end"]
        book = gzip.compress(json.dumps({"version": 2, "kind": "pdf-book-text", "complete": True,
            "offset_unit": "unicode-codepoint", "source_sha256": "a" * 64, "page_count": 3,
            "pages": [{"page": i + 1, "text": text, "layout": {"offset_unit": "unicode-codepoint"},
                "text_spans": []} for i, text in enumerate(texts)]}).encode())
        manifest = {"version": 1, "kind": "pdf-ocr", "complete": True,
            "source_sha256": "a" * 64, "profile": "test-layout-v1-index", "page_count": 3,
            "pages": [{"p": i + 1, "o": root + f"/ocr/page-{i + 1:06d}.json.gz"} for i in range(3)],
            "book_text": {"path": book_path, "bytes": len(book), "sha256": hashlib.sha256(book).hexdigest()}}
        def resource(route):
            path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)["path"][0]
            if path == manifest_path:
                route.fulfill(json=manifest)
            elif path == book_path:
                route.fulfill(content_type="application/gzip", body=book)
            else:
                route.fulfill(status=404)
        self.page.route("**/api/reader-bucket-resource**", resource)
        self.open(self.reader_url("pdf", ocr_manifest=self.origin + "/api/reader-bucket-resource?path=" + manifest_path))
        self.page.locator("#history").click()
        self.page.locator("#full-search-toggle").click()
        self.page.locator("#full-search-input").fill("needle")
        self.page.wait_for_function("() => document.querySelectorAll('.full-search-result').length === 50")
        self.page.evaluate("() => { window.__firstOcrRow = document.querySelector('.full-search-result'); __firstOcrRow.focus(); }")
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '61 个结果'")
        self.assertTrue(self.page.evaluate("() => document.querySelector('.full-search-result') === window.__firstOcrRow && document.activeElement === window.__firstOcrRow"))

    def test_pdf_ocr_worker_pages_deep_results_and_reuses_book(self):
        def control_prefetch(route):
            response = route.fetch()
            script = response.text()
            schedule = '  function schedulePdfBookSearchPrefetch() {'
            call = '      await client.prefetch();'
            self.assertEqual(script.count(schedule), 1)
            self.assertEqual(script.count(call), 1)
            script = script.replace(schedule, schedule + '''
              window.__triggerPdfPrefetch = async () => {
                await readerContext.prefetchPdfBookSearch();
                return readerContext.pdfBookSearchPrefetchPromise;
              };
              return;''')
            script = script.replace(call, '      window.__pdfPrefetchResult = await client.prefetch();')
            route.fulfill(response=response, body=script)
        self.page.route('**/static/reader/pdf/reader-pdf-search.mjs*', control_prefetch)
        self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route: route.fulfill(
            content_type="text/javascript", body=support.PDF_MODULE.replace("numPages: 30", "numPages: 2")))
        root = "objects/aa/" + "a" * 64 + "/" + "b" * 16
        manifest_path = root + "/ocr-manifest.json"
        book_path = root + "/ocr/book-text.json.gz"
        book = gzip.compress(json.dumps({"version": 2, "kind": "pdf-book-text", "complete": True,
            "offset_unit": "unicode-codepoint", "source_sha256": "a" * 64, "page_count": 2,
            "pages": [{"page": page, "text": text, "layout": {"offset_unit": "unicode-codepoint"},
                       "text_spans": []} for page, text in ((1, "needle " * 620), (2, "tail"))]}).encode())
        manifest = {"version": 1, "kind": "pdf-ocr", "complete": True,
                    "source_sha256": "a" * 64, "profile": "test-layout-v1-index", "page_count": 2,
                    "pages": [{"p": page, "o": root + f"/ocr/page-{page:06d}.json.gz"} for page in (1, 2)],
                    "book_text": {"path": book_path, "bytes": len(book), "sha256": hashlib.sha256(book).hexdigest()}}
        book_requests = []
        def resource(route):
            path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)["path"][0]
            if path == manifest_path:
                route.fulfill(json=manifest)
            elif path == book_path:
                book_requests.append(path)
                route.fulfill(content_type="application/gzip", body=book)
            else:
                route.fulfill(status=404)
        self.page.route("**/api/reader-bucket-resource**", resource)
        self.open(self.reader_url("pdf", ocr_manifest=self.origin + "/api/reader-bucket-resource?path=" + manifest_path))
        self.page.locator("#history").click()
        self.page.locator("#full-search-toggle").click()
        self.page.locator("#full-search-input").fill("needle")
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '620 个结果'")
        prefetch = self.page.evaluate('''async () => {
          await window.__triggerPdfPrefetch();
          return window.__pdfPrefetchResult || null;
        }''')
        self.assertTrue(prefetch['ready'])
        self.assertIsInstance(prefetch['session'], int)
        self.page.locator("#full-search-page").fill("11")
        self.page.locator("#full-search-page").dispatch_event("change")
        self.page.wait_for_function("() => document.querySelector('.full-search-rank')?.textContent === '501.'")
        self.assertEqual(self.page.locator(".full-search-result").count(), 50)
        self.page.locator("#full-search-input").fill("tail")
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")
        self.assertIn("第 2 页", self.page.locator(".full-search-result").first.text_content())
        self.assertEqual(book_requests, [book_path])

    def test_pdf_ocr_worker_retries_corrupt_book_and_can_cancel(self):
        self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route: route.fulfill(
            content_type="text/javascript", body=support.PDF_MODULE.replace("numPages: 30", "numPages: 1")))
        root = "objects/aa/" + "a" * 64 + "/" + "b" * 16
        manifest_path, book_path = root + "/ocr-manifest.json", root + "/ocr/book-text.json.gz"
        book = gzip.compress(json.dumps({"version": 2, "kind": "pdf-book-text", "complete": True,
            "offset_unit": "unicode-codepoint", "source_sha256": "a" * 64, "page_count": 1,
            "pages": [{"page": 1, "text": "needle", "layout": {"offset_unit": "unicode-codepoint"},
                       "text_spans": []}]}).encode())
        manifest = {"version": 1, "kind": "pdf-ocr", "complete": True,
                    "source_sha256": "a" * 64, "profile": "test-layout-v1-index", "page_count": 1,
                    "pages": [{"p": 1, "o": root + "/ocr/page-000001.json.gz"}],
                    "book_text": {"path": book_path, "bytes": len(book), "sha256": hashlib.sha256(book).hexdigest()}}
        requests, held = [], []
        def resource(route):
            path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)["path"][0]
            if path == manifest_path:
                route.fulfill(json=manifest)
            elif path == book_path:
                requests.append(path)
                if len(requests) == 1:
                    held.append(route)
                    return
                payload = b"x" * len(book) if len(requests) == 2 else book
                route.fulfill(content_type="application/gzip", body=payload)
            else:
                route.fulfill(status=404)
        self.page.route("**/api/reader-bucket-resource**", resource)
        self.open(self.reader_url("pdf", ocr_manifest=self.origin + "/api/reader-bucket-resource?path=" + manifest_path))
        self.page.locator("#history").click()
        self.page.locator("#full-search-toggle").click()
        with self.page.expect_request(lambda request: urllib.parse.parse_qs(
                urllib.parse.urlsplit(request.url).query).get("path") == [book_path]):
            self.page.locator("#full-search-input").fill("needle")
        self.page.locator("#full-search-cancel").click()
        self.assertEqual(self.page.locator("#full-search-status").text_content(), "搜索已取消")
        for route in held:
            try: route.abort()
            except support.PlaywrightError: pass
        self.page.locator("#full-search-retry").click()
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent.includes('PDF_OCR_HASH_MISMATCH')")
        self.page.locator("#full-search-retry").click()
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")
        self.assertEqual(requests, [book_path] * 3)

    def test_txt_preserves_literal_unicode_replacement_characters_and_search(self):
        text = 'prefix \ufffd needle\n' * 3
        self.serve(text.encode('utf-8'), 'text/plain; charset=utf-8')
        self.open(self.reader_url('txt'))
        self.assertEqual(self.page.locator('.reader-text').text_content(), text)
        self.page.locator('#history').click()
        self.page.locator('#full-search-toggle').click()
        self.page.locator('#full-search-input').fill('\ufffd')
        self.page.wait_for_function("()=>document.querySelector('#full-search-status').textContent==='3 个结果'")

    def test_media_waits_for_metadata_before_reporting_ready(self):
        held = []
        self.page.route('**/api/reader-content**', lambda route: held.append(route))
        self.page.goto(self.reader_url('wav'), wait_until='domcontentloaded')
        self.page.locator('audio').wait_for()
        self.assertEqual(self.page.locator('audio').evaluate('m => m.readyState'), 0)
        self.assertNotEqual(self.page.locator('html').get_attribute('data-reader-phase'), 'ready')
        self.assertTrue(held)
        held[0].fulfill(content_type='audio/wav', body=support.minimal_wav())
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        self.assertGreaterEqual(self.page.locator('audio').evaluate('m => m.readyState'), 1)

    def test_pending_media_loading_feedback_does_not_displace_player(self):
        for mode, extension in [('audio', 'wav'), ('video', 'mp4')]:
            for width in (390, 1100):
                with self.subTest(mode=mode, width=width):
                    held = []
                    self.page.set_viewport_size({'width': width, 'height': 844})
                    self.page.route('**/api/reader-content**', lambda route: held.append(route))
                    self.page.goto(self.reader_url(extension), wait_until='domcontentloaded')
                    self.page.locator(mode).wait_for()
                    self.assertNotEqual(self.page.locator('html').get_attribute('data-reader-phase'), 'ready')
                    self.assertTrue(self.page.locator('.reader-loading-indicator').is_hidden())
                    geometry = self.page.locator(mode).evaluate('''m => {
                      const a=m.getBoundingClientRect(),v=document.querySelector('#viewport').getBoundingClientRect();
                      return {top:a.top,bottom:a.bottom,height:a.height,center:a.top+a.height/2,
                        vtop:v.top,vbottom:v.bottom,vheight:v.height,vcenter:v.top+v.height/2};
                    }''')
                    self.assertAlmostEqual(geometry['center'], geometry['vcenter'], delta=1)
                    if mode == 'video':
                        self.assertAlmostEqual(geometry['height'], geometry['vheight'], delta=1)
                    self.assertGreaterEqual(geometry['top'], geometry['vtop'] - 1)
                    self.assertLessEqual(geometry['bottom'], geometry['vbottom'] + 1)
                    self.page.evaluate("window.dispatchEvent(new Event('voice-reader-dispose'))")
                    for route in held:
                        try: route.abort()
                        except support.PlaywrightError: pass

    def test_media_metadata_stall_recovers_without_reader_reload(self):
        self.assert_media_metadata_stall(True)

    def test_media_proxy_retry_retains_position_and_paused_state(self):
        self.assert_media_retry_position(False)

    def test_media_proxy_retry_resumes_active_playback(self):
        self.assert_media_retry_position(True)

    def media_retry_url(self):
        # Bucket proxies are accepted by the production media retry validator.
        return self.origin + '/api/reader-bucket-resource?path=media/audio/native/' + 'a' * 64 + '/audio.wav'

    def assert_media_retry_position(self, playing):
        buffer = io.BytesIO()
        with wave.open(buffer, 'wb') as audio:
            audio.setparams((1, 2, 8000, 80000, 'NONE', 'not compressed'))
            audio.writeframes(b'\0\0' * 80000)
        data = buffer.getvalue()
        def serve_audio(route):
            start = int(route.request.headers.get('range', 'bytes=0-').split('=')[1].split('-')[0])
            route.fulfill(status=206,content_type='audio/wav',body=data[start:],headers={
                'Accept-Ranges':'bytes','Content-Range':f'bytes {start}-{len(data)-1}/{len(data)}'})
        requests, direct = [], []
        self.page.route(self.media_retry_url(),
                        lambda route: (requests.append(route.request.url), serve_audio(route)))
        self.page.route('https://huggingface.co/datasets/**',
                        lambda route: (direct.append(route.request.url), route.abort()))
        self.open(self.reader_url('wav', url=self.media_retry_url(),
                                  download='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/refactor.wav'))
        self.page.locator('audio').evaluate("m => { m.muted=true; return m.play(); }")
        self.page.wait_for_function("()=>document.querySelector('audio').currentTime>.02")
        self.page.locator('audio').evaluate('m=>m.pause()')
        self.page.locator('audio').evaluate("m => { m.currentTime=.05; }")
        self.page.wait_for_function("()=>!document.querySelector('audio').seeking")
        self.assertAlmostEqual(self.page.locator('audio').evaluate('m=>m.currentTime'), .05)
        self.page.locator('audio').evaluate('m=>{m.playbackRate=1.25;}')
        if playing:
            self.page.locator('audio').evaluate('m=>m.play()')
        with self.page.expect_request(self.media_retry_url()):
            self.page.locator('audio').evaluate("m => m.dispatchEvent(new Event('error'))")
        try:
            self.page.wait_for_function("playing=>{const m=document.querySelector('audio');return m.readyState>=1 && (playing ? !m.paused && m.currentTime>=.05 : m.paused && m.currentTime===.05);}",arg=playing)
        except support.PlaywrightError:
            self.fail(str(self.page.evaluate("()=>{const m=document.querySelector('audio');return {src:m?.src,time:m?.currentTime,duration:m?.duration,retry:m?._readerSourceRetry,phase:document.documentElement.dataset.readerPhase}}")))
        self.assertEqual(set(requests), {self.media_retry_url()})
        self.assertEqual(direct, [])
        self.assertEqual(self.page.locator('audio').evaluate('m=>m.paused'),not playing)
        self.assertEqual(self.page.locator('audio').evaluate('m=>m.playbackRate'),1.25)

    def test_media_retry_does_not_save_reset_time_on_close(self):
        buffer = io.BytesIO()
        with wave.open(buffer, 'wb') as audio:
            audio.setparams((1, 2, 8000, 80000, 'NONE', 'not compressed'))
            audio.writeframes(b'\0\0' * 80000)
        data = buffer.getvalue()
        requests, held, direct = [], [], []
        def proxy(route):
            requests.append(route.request.url)
            if len(requests) == 1:
                route.fulfill(status=206, content_type='audio/wav', body=data,
                              headers={'Accept-Ranges':'bytes','Content-Range':f'bytes 0-{len(data)-1}/{len(data)}'})
            else:
                held.append(route)
                self.page.evaluate('window.__mediaRetryHeld = true')
        self.page.route(self.media_retry_url(), proxy)
        self.page.route('https://huggingface.co/datasets/**',
                        lambda route: (direct.append(route.request.url), route.abort()))
        self.open(self.reader_url('wav', url=self.media_retry_url(),
                                  download='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/refactor.wav'))
        self.page.locator('audio').evaluate("m => { m.muted=true; return m.play(); }")
        self.page.wait_for_function("()=>document.querySelector('audio').currentTime>.02")
        self.page.locator('audio').evaluate('m=>m.pause()')
        self.page.locator('audio').evaluate("m => { m.currentTime=.05; }")
        self.page.wait_for_function("()=>!document.querySelector('audio').seeking")
        self.page.locator('audio').evaluate("m => m.dispatchEvent(new Event('error'))")
        self.page.wait_for_function('() => window.__mediaRetryHeld === true')
        self.assertEqual(set(requests), {self.media_retry_url()})
        self.assertEqual(direct, [])
        with self.page.expect_event('requestfailed', lambda request: request == held[-1].request):
            self.page.evaluate("window.dispatchEvent(new Event('voice-reader-dispose'))")
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'disposed'")
        entry = self.page.evaluate("async()=>await VoiceOfMLReaderStore.get(new URL(location.href).searchParams.get('url'))")
        self.assertEqual(entry['mediaTime'], .05)
        for route in held:
            try:route.abort()
            except support.PlaywrightError:pass

    def test_media_metadata_exhaustion_exposes_reload_and_can_recover(self):
        self.assert_media_metadata_stall(False)

    def test_disposal_cancels_pending_media_metadata_without_retry(self):
        self.page.add_init_script('''const timer=window.setTimeout.bind(window);
          window.setTimeout=(callback,delay,...args)=>{
            if(delay===15000){window.__mediaIdle=()=>callback(...args);return timer(()=>{},delay);}
            return timer(callback,delay,...args);
          };''')
        held, originals = [], []
        def hold_proxy(route):
            held.append(route)
            self.page.evaluate('window.__mediaRequestHeld = true')
        self.page.route('**/api/reader-content**', hold_proxy)
        self.page.route('https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/refactor.wav',
                        lambda route: (originals.append(route.request.url), route.abort()))
        with self.page.expect_request('**/api/reader-content**') as pending:
            self.page.goto(self.reader_url('wav'), wait_until='domcontentloaded')
        with self.page.expect_event('requestfailed', lambda request: request == pending.value):
            self.page.evaluate("window.dispatchEvent(new Event('voice-reader-dispose'))")
        self.assertIsNone(self.page.locator('audio').get_attribute('src'))
        self.page.evaluate('() => window.__mediaIdle()')
        self.assertEqual(len(held), 1)
        self.assertEqual(originals, [])
        self.assertEqual(self.page.locator('html').get_attribute('data-reader-phase'), 'disposed')
        self.assertIsNone(self.page.locator('audio').get_attribute('src'))
        for route in held:
            try: route.abort()
            except support.PlaywrightError: pass

    def assert_media_metadata_stall(self, recover):
        self.page.add_init_script('''const timer=window.setTimeout.bind(window);
          window.setTimeout=(callback,delay,...args)=>timer(callback,delay===15000?150:delay,...args);''')
        held, requests, direct = [], [], []
        allow = [False]
        def proxy(route):
            requests.append(route.request.url)
            if allow[0] or (recover and held):
                route.fulfill(content_type='audio/wav',body=support.minimal_wav())
            else:
                held.append(route)
        self.page.route(self.media_retry_url(), proxy)
        self.page.route('https://huggingface.co/datasets/**',
                        lambda route: (direct.append(route.request.url), route.abort()))
        self.page.goto(self.reader_url('wav', url=self.media_retry_url(),
                                       download='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/refactor.wav'),
                       wait_until='domcontentloaded')
        if not recover:
            self.page.locator('#reader-engine-retry').wait_for()
            self.assertEqual(self.page.locator('#content').get_attribute('data-error-code'), 'READER_MEDIA')
            self.assertEqual(direct, [])
            allow[0] = True
            self.page.locator('#reader-engine-retry').click()
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready' && document.querySelector('audio').readyState >= 1")
        self.assertTrue(held, 'the first proxy response stayed stalled')
        self.assertGreaterEqual(len(requests), 2, 'playback recovered from the stalled request')
        self.assertEqual(set(requests), {self.media_retry_url()})
        self.assertEqual(direct, [])
        self.page.evaluate("window.dispatchEvent(new Event('voice-reader-dispose'))")
        self.assertFalse(self.page.locator('audio').get_attribute('src'))
        for route in held:
            try: route.abort()
            except support.PlaywrightError: pass

    def test_bucket_media_transient_503_recovers_automatically(self):
        self.assert_media_503_recovery(bucket=True)

    def test_media_proxy_transient_503_recovers_automatically(self):
        self.assert_media_503_recovery()

    def test_media_proxy_failure_recovers_on_manual_retry_without_direct_source(self):
        self.assert_media_503_recovery(manual_retry=True)

    def assert_media_503_recovery(self, *, bucket=False, manual_retry=False):
        buffer = io.BytesIO()
        with wave.open(buffer, 'wb') as audio:
            audio.setparams((1, 2, 8000, 8000, 'NONE', 'not compressed'))
            audio.writeframes(b'\0\0' * 8000)
        data = buffer.getvalue()
        requests, direct, navigations = [], [], []
        unavailable = True
        def proxy(route):
            nonlocal unavailable
            requests.append((route.request.url, 503 if unavailable else 206))
            if unavailable:
                if not manual_retry:
                    unavailable = False
                route.fulfill(status=503, body='unavailable')
                return
            start = int(route.request.headers.get('range', 'bytes=0-').split('=')[1].split('-')[0])
            route.fulfill(status=206, content_type='audio/wav', body=data[start:],
                          headers={'Accept-Ranges': 'bytes', 'Content-Range': f'bytes {start}-{len(data)-1}/{len(data)}'})

        self.page.route('**/api/reader-bucket-resource**' if bucket else '**/api/reader-content**', proxy)
        self.page.route('https://huggingface.co/datasets/**',
                        lambda route: (direct.append(route.request.url), route.abort()))
        self.page.on('framenavigated', lambda frame: navigations.append(frame.url) if frame == self.page.main_frame else None)
        options = dict(url=self.media_retry_url(),
                       download='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/refactor.wav') if bucket else {}
        reader_url = self.reader_url('wav', **options)
        retry = self.page.locator('#reader-engine-retry')
        if not manual_retry:
            self.page.add_init_script('''
              window.__sawMediaError = false;
              new MutationObserver(records => {
                if (records.some(({target, oldValue}) =>
                  oldValue === 'READER_MEDIA' || target.dataset.errorCode === 'READER_MEDIA'))
                  window.__sawMediaError = true;
              }).observe(document, {subtree: true, attributes: true,
                attributeFilter: ['data-error-code'], attributeOldValue: true});
            ''')

        def open_or_retry(reload=False):
            nonlocal unavailable
            unavailable = True
            requests.clear()
            navigations.clear()
            if reload:
                self.page.reload(wait_until='domcontentloaded')
            else:
                self.page.goto(reader_url, wait_until='domcontentloaded')
            if manual_retry:
                retry.wait_for()
                self.assertEqual(self.page.locator('html').get_attribute('data-reader-phase'), 'failed')
                self.assertEqual(self.page.locator('#content').get_attribute('data-error-code'), 'READER_MEDIA')
                self.assertEqual({status for _, status in requests}, {503})
                self.assertEqual(navigations, [reader_url])
                self.assertEqual(direct, [])

                # Keep every media request failing until the retry button reloads the reader.
                def recover_on_reload(route):
                    nonlocal unavailable
                    unavailable = False
                    route.continue_()

                self.page.route(lambda url: url == reader_url, recover_on_reload, times=1)
                with self.page.expect_navigation(wait_until='domcontentloaded'):
                    retry.click()
            self.page.wait_for_function("""() => document.documentElement.dataset.readerPhase === 'ready' &&
                                        document.querySelector('audio')?.readyState >= 1""")
            self.assertEqual(navigations, [reader_url, reader_url] if manual_retry else [reader_url])
            # The Node contract owns the retry budget; browsers may issue extra range requests.
            self.assertEqual(requests[0][1], 503)
            self.assertIn(206, [status for _, status in requests])
            current_src = self.page.locator('audio').evaluate('node => node.currentSrc')
            self.assertEqual({url for url, _ in requests}, {current_src})
            self.assertEqual(direct, [])
            self.assertEqual(self.page.locator('.reader-error, #reader-engine-retry').count(), 0)
            if not manual_retry:
                self.assertFalse(self.page.evaluate('window.__sawMediaError'))

        open_or_retry()
        self.assertEqual(self.page.locator('audio').evaluate('node => node.duration'), 1)
        self.page.evaluate("async () => { const media = document.querySelector('audio'); media.currentTime = 0.5; await VoiceOfMLReaderStore.put({url: new URL(location.href).searchParams.get('url'), mediaTime: 0.5}); }")
        open_or_retry(reload=True)
        self.page.wait_for_function("() => document.querySelector('audio')?.currentTime === 0.5")

        # A later player error still surfaces a manual retry if the proxy stays down.
        unavailable = True
        self.page.locator('audio').evaluate("media => media.dispatchEvent(new Event('error'))")
        retry.wait_for()
        self.assertEqual(self.page.locator('html').get_attribute('data-reader-phase'), 'failed')
        self.assertEqual(self.page.locator('#content').get_attribute('data-error-code'), 'READER_MEDIA')
        self.assertEqual({url for url, _ in requests}, {requests[0][0]})
        self.assertEqual(direct, [])

    def test_chapter_links_load_target_without_leaving_reader(self):
        prefix = 'chapters/ebook/epub/' + 'b' * 64 + '/' + 'a' * 16 + '/'
        bodies = {i: f'<h1>Chapter {i}</h1><p id="target" style="height:12000px">正文</p>' for i in range(1, 13)}
        bodies[1] = '<html><body id="contents"><a href="chapter-0012.xhtml#target">跨章节跳转</a><a href="chapter-0012.xhtml#chapter-root">章节首页</a><a href="part0010.html#missing">失效旧链接</a>' + bodies[1] + '</body></html>'
        bodies[12] = '<html:html xmlns:html="http://www.w3.org/1999/xhtml"><html:body id="chapter-root"><html:h1>Chapter 12</html:h1><html:p id="target"><html:a href="chapter-0001.xhtml#contents">返回目录</html:a></html:p><html:ruby><html:rb>朝露<html:a id="w3"/></html:rb><html:rtc><html:rt>zhāo lù</html:rt></html:rtc></html:ruby><html:p style="height:12000px">正文</html:p></html:body></html:html>'
        manifest = dict(version=1, kind='epub-chapters', chapters=[dict(index=i, path=f'chapters/chapter-{i:04d}.xhtml', title=str(i), bytes=len(bodies[i].encode())) for i in bodies])
        def serve(route):
            path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)['path'][0]
            body = json.dumps(manifest) if path.endswith('chapter-manifest.json') else bodies[int(path.rsplit('-', 1)[1].split('.')[0])]
            route.fulfill(content_type='application/json' if path.endswith('.json') else 'application/xhtml+xml', body=body)
        self.page.route('**/api/reader-bucket-resource**', serve)
        manifest_path = prefix + 'chapter-manifest.json'
        manifest_url = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=' + urllib.parse.quote(manifest_path, safe='')
        self.open(self.reader_url('epub-chapters', url=manifest_url))
        before = self.page.url
        self.page.get_by_text('跨章节跳转', exact=True).click()
        self.page.wait_for_function("() => !!document.querySelector('.reader-epub-chapter[data-chapter=\"12\"] #target')")
        self.page.wait_for_function("() => document.querySelector('#viewport').scrollTop > 1000")
        self.assertEqual(self.page.url, before)
        self.assertLess(abs(self.page.locator('.reader-epub-chapter[data-chapter="12"] #target').evaluate("node => node.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top")), 5)
        self.page.get_by_text('返回目录', exact=True).click()
        self.assertLess(abs(self.page.locator('.reader-epub-chapter[data-chapter="1"]').evaluate("node => node.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top")), 5)
        self.page.get_by_text('章节首页', exact=True).click()
        self.assertEqual(self.page.locator('.reader-epub-chapter[data-chapter="12"]').get_attribute('id'), 'chapter-root')
        self.assertEqual(self.page.locator('#chapter-root rb').inner_text(), '朝露')
        self.assertEqual(self.page.locator('#chapter-root rtc rt').inner_text(), 'zhāo lù')
        self.assertEqual(self.page.locator('#chapter-root rb #w3').count(), 1)
        self.assertLess(abs(self.page.locator('#chapter-root').evaluate("node => node.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top")), 5)
        self.page.get_by_text('返回目录', exact=True).click()
        self.page.get_by_text('失效旧链接', exact=True).click()
        self.assertEqual(self.page.locator('.reader-chapter-link-error').count(), 0)
        mapped = self.page.evaluate("""async () => {
          const {chapterTextMap} = await import('/static/reader/search/reader-chapter-search.mjs');
          return chapterTextMap([document.querySelector('.reader-epub-chapter[data-chapter="1"]')]).text;
        }""")
        self.assertNotIn('无法定位', mapped)
        self.assertIn('正文', mapped)
        self.assertEqual(self.page.url, before)
        source = manifest_url
        self.page.evaluate("""async source => {
          window.dispatchEvent(new PageTransitionEvent('pagehide', {persisted:false}));
          await new Promise(resolve => setTimeout(resolve, 0));
          await VoiceOfMLReaderStore.put({url:source, chapterIndex:9999, chapterOffset:123,
            lastReadAt:Date.now()+1});
        }""", source)
        self.page.reload()
        # An obsolete locator is not a chapter fetch failure. Open at the first
        # chapter, then verify normal cross-chapter navigation and new history.
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        self.assertIsNone(self.page.locator('#content').get_attribute('data-error-code'))
        self.assertTrue(self.page.locator('.reader-epub-chapter[data-chapter="1"] #contents, .reader-epub-chapter[data-chapter="1"]#contents').is_visible())
        self.page.get_by_text('跨章节跳转', exact=True).click()
        self.wait_for_store("async source => {const item=await VoiceOfMLReaderStore.get(source);return item?.chapterIndex===12 && item?.chapterManifest===source;}", source)
        self.page.reload()
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        self.assertTrue(self.page.locator('#chapter-root #target').is_visible())
        self.assertLess(abs(self.page.locator('#chapter-root #target').evaluate("node => node.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top")), 10)

    def test_encoded_toc_fragment_tracks_manual_scroll_and_navigates(self):
        body = '<h2 id="plain">First section</h2>' + '<p>First section text</p>' * 80
        body += '<h2 id="café">Encoded section</h2>' + '<p>Encoded section text</p>' * 80
        manifest = {
            'version': 1, 'kind': 'epub-chapters',
            'chapters': [{'index': 1, 'path': 'chapters/chapter-0001.xhtml', 'bytes': len(body.encode())}],
            'toc': [{'title': 'First section', 'chapter': 1, 'depth': 0, 'fragment': 'plain'},
                    {'title': 'Encoded section', 'chapter': 1, 'depth': 0, 'fragment': 'caf%C3%A9'}],
        }
        base = 'chapters/ebook/epub/' + 'a' * 64 + '/' + 'b' * 16 + '/'
        self.page.route('**/api/reader-bucket-resource**', lambda route: route.fulfill(json=manifest)
                        if 'chapter-manifest.json' in route.request.url
                        else route.fulfill(content_type='application/xhtml+xml', body=body))
        url = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=' + base + 'chapter-manifest.json'
        self.page.emulate_media(reduced_motion='reduce')
        self.open(self.reader_url('epub-chapters', url=url))
        self.page.locator('#history').click()
        current = self.page.locator('#toc-list [aria-current="location"]')
        first = self.page.get_by_role('link', name='First section', exact=True)
        encoded = self.page.get_by_role('link', name='Encoded section', exact=True)
        self.page.locator('#viewport').evaluate("""node => {
          const first = document.querySelector('#plain');
          node.scrollTop += first.getBoundingClientRect().top - node.getBoundingClientRect().top + 20;
        }""")
        self.assertEqual(current.text_content(timeout=2500), 'First section')
        self.page.locator('#viewport').evaluate("""node => {
          const target = document.getElementById('café');
          node.scrollTop += target.getBoundingClientRect().top - node.getBoundingClientRect().top + 20;
        }""")
        self.page.wait_for_function("() => document.querySelector('#toc-list [aria-current=location]')?.textContent === 'Encoded section'", timeout=2500)
        first.click()
        self.page.locator('#history').click()
        encoded.click()
        self.page.wait_for_function("""() => Math.abs(document.getElementById('café').getBoundingClientRect().top -
            document.querySelector('#viewport').getBoundingClientRect().top) < 5""")

    def test_chapter_search_v2_bucket_index_keeps_checksum_retry_paging_and_highlight(self):
        documents, prefixes, requests = {}, {}, []
        for extension in ('epub', 'mobi', 'azw3', 'fb2'):
            prefix = f'chapters/ebook/{extension}/' + 'a' * 64 + '/' + 'b' * 16 + '/'
            prefixes[extension] = prefix
            bodies = {1:'<h1>First</h1><p>needle</p>', 2:'<h1>Tail</h1>' + '<p>needle</p>' * 65}
            if extension == 'fb2':
                bodies[1] = '<html><head><title>Cover</title></head><body>' + bodies[1] + '</body></html>'
            chapters = [{'index':index, 'path':f'chapters/chapter-{index:04d}.xhtml',
                         'title':f'Chapter {index}', 'bytes':len(body.encode())} for index,body in bodies.items()]
            texts = [{**chapter, 'text':'First needle' if chapter['index'] == 1 else 'Tail ' + ' '.join(['needle'] * 65)}
                     for chapter in chapters]
            if extension == 'fb2':
                texts[0]['text'] = 'Cover ' + texts[0]['text']
            packed = gzip.compress(json.dumps({'version':1, 'kind':'epub-search-index', 'chapters':texts}).encode(), mtime=0)
            manifest = {'version':1, 'kind':'epub-chapters', 'chapters':chapters,
                        'search_index':{'path':'epub-search-index.json.gz', 'bytes':len(packed),
                                        'sha256':hashlib.sha256(packed).hexdigest()}}
            documents[prefix+'chapter-manifest.json'] = ('application/json', json.dumps(manifest))
            documents[prefix+'epub-search-index.json.gz'] = ('application/gzip', packed)
            for chapter in chapters:
                documents[prefix+chapter['path']] = ('text/html', bodies[chapter['index']])

        def serve(route):
            path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)['path'][0]
            requests.append(path)
            mime, body = documents[path]
            if path == prefixes['epub']+'epub-search-index.json.gz' and requests.count(path) == 1:
                body = body[:-1] + bytes([body[-1] ^ 1])
            route.fulfill(content_type=mime, body=body, headers={'Access-Control-Allow-Origin':'*'})

        self.context.route('**/api/reader-bucket-resource**', serve)
        for extension,prefix in prefixes.items():
            with self.subTest(extension=extension):
                source = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?' + urllib.parse.urlencode({'path':prefix+'chapter-manifest.json'})
                self.open(self.reader_url('epub-chapters', url=source))
                self.assertNotIn(prefix+'epub-search-index.json.gz', requests)
                support.open_reader_panel(self.page)
                self.page.locator('#full-search-toggle').click()
                self.page.locator('#full-search-input').fill('needle')
                if extension == 'epub':
                    self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent.includes('索引校验失败')")
                    self.page.locator('#full-search-retry').click()
                self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '66 个结果'")
                self.assertEqual(self.page.locator('.full-search-result').count(), 50)
                self.page.locator('#full-search-page').fill('2')
                self.page.locator('#full-search-page').dispatch_event('change')
                self.page.wait_for_function("() => document.querySelector('.full-search-rank')?.textContent === '51.'")
                self.assertEqual(self.page.locator('.full-search-result').count(), 16)
                self.page.locator('.full-search-result').last.click()
                self.page.wait_for_function("() => document.querySelector('.reader-epub-chapter[data-chapter=\"2\"] mark.full-search-highlight')?.textContent === 'needle'")
                self.assertEqual(requests.count(prefix+'epub-search-index.json.gz'), 2 if extension == 'epub' else 1)
                if extension == 'fb2':
                    support.open_reader_panel(self.page)
                    self.page.locator('#full-search-input').fill('Cover')
                    self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")
                    self.page.locator('.full-search-result').first.click()
                    self.page.locator('.reader-chapter-search-heading mark').wait_for()
                    self.assertEqual(self.page.locator('.reader-chapter-search-heading mark').all_text_contents(), ['Cover'])
                    support.open_reader_panel(self.page)
                    self.page.locator('#full-search-input').fill('needle')
                    self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '66 个结果'")
                    self.page.locator('.full-search-result').first.click()
                    self.page.locator('.reader-epub-chapter[data-chapter="1"] mark').wait_for()
                    self.assertEqual(self.page.locator('.reader-epub-chapter[data-chapter="1"] mark').all_text_contents(), ['needle'])
                    self.assertEqual(self.page.locator('.reader-chapter-search-heading').count(), 0)

    def test_chapter_search_exact_dom_profile_preserves_literals_and_legacy_offsets(self):
        documents = {}
        cases = [('dom-text-v1', 'c'), (None, 'd')]
        for profile, identity in cases:
            prefix = 'chapters/ebook/chm/' + identity * 64 + '/' + 'a' * 16 + '/'
            body = '<h1>Start</h1>' + '<p>literal &amp;#0 &amp;nbsp; tail</p>' * 65 + '<p>end</p>'
            literal = 'literal &#0 &nbsp; tail' if profile else 'literal � tail'
            text = 'Start ' + ' '.join([literal] * 65) + ' end'
            chapter = dict(index=1, title='literal', path='chapters/chapter-0001.xhtml', bytes=len(body.encode()))
            data = dict(version=1, kind='epub-search-index', chapters=[dict(chapter, text=text)])
            if profile:
                data['text_profile'] = profile
            packed = gzip.compress(json.dumps(data).encode(), mtime=0)
            ref = dict(path='epub-search-index.json.gz', bytes=len(packed), sha256=hashlib.sha256(packed).hexdigest())
            if profile:
                ref['text_profile'] = profile
            manifest = dict(version=1, kind='epub-chapters', chapters=[chapter], search_index=ref)
            documents[prefix+'chapter-manifest.json'] = ('application/json', json.dumps(manifest))
            documents[prefix+'epub-search-index.json.gz'] = ('application/gzip', packed)
            documents[prefix+chapter['path']] = ('text/html', body)

        def serve(route):
            path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)['path'][0]
            mime, body = documents[path]
            route.fulfill(content_type=mime, body=body, headers={'Access-Control-Allow-Origin':'*'})

        self.context.route('**/api/reader-bucket-resource**', serve)
        for profile, identity in cases:
            with self.subTest(profile=profile):
                prefix = 'chapters/ebook/chm/' + identity * 64 + '/' + 'a' * 16 + '/'
                source = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?' + urllib.parse.urlencode({'path':prefix+'chapter-manifest.json'})
                self.open(self.reader_url('epub-chapters', url=source))
                for query in (['&nbsp;', '&#0', 'tail'] if profile else ['tail']):
                    support.open_reader_panel(self.page)
                    if not self.page.locator('#full-search-input').is_visible():
                        self.page.locator('#full-search-toggle').click()
                    self.page.locator('#full-search-input').fill(query)
                    self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '65 个结果'")
                    self.assertEqual(self.page.locator('.full-search-result').count(), 50)
                    self.page.locator('#full-search-page').fill('2')
                    self.page.locator('#full-search-page').dispatch_event('change')
                    self.page.wait_for_function("() => document.querySelector('.full-search-rank')?.textContent === '51.'")
                    self.assertEqual(self.page.locator('.full-search-result').count(), 15)
                    self.page.locator('.full-search-result').last.click()
                    self.page.wait_for_function("query => document.querySelector('mark.full-search-highlight')?.textContent === query", arg=query)
                    self.assertIn('&#0 &nbsp;', self.page.locator('.reader-epub-chapter').inner_text())

    def test_bucket_chapter_stream_loads_manifest_chapter_and_resource(self):
        prefix = "chapters/ebook/epub/" + "c" * 64 + "/" + "b" * 16 + "/"
        chapter = '<html><body><h1>Bucket chapter</h1><img src="../resources/shared/cover.png"></body></html>'
        chapter_path = prefix + "chapters/chapter-0001.xhtml"
        manifest_path = prefix + "chapter-manifest.json"
        resource_path = prefix + "resources/shared/cover.png"
        manifest = {"version": 1, "kind": "epub-chapters", "chapters": [
            {"index": 1, "path": "chapters/chapter-0001.xhtml", "title": "Bucket chapter",
             "bytes": len(chapter.encode()), "sha256": hashlib.sha256(chapter.encode()).hexdigest()}
        ]}
        requested = []
        def serve(route):
            path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)["path"][0]
            requested.append(path)
            if path == manifest_path:
                route.fulfill(content_type="application/json", body=json.dumps(manifest))
            elif path == chapter_path:
                route.fulfill(content_type="application/xhtml+xml", body=chapter)
            elif path == resource_path:
                route.fulfill(content_type="image/png", body=b"not-a-real-png")
            else:
                route.fulfill(status=404, body="missing")
        self.page.route("https://voiceofml-search.hf.space/api/reader-bucket-resource**", serve)
        url = "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + urllib.parse.quote(manifest_path, safe="")
        self.open(self.reader_url("epub-chapters", url=url))
        self.assertIn("Bucket chapter", self.page.locator(".reader-epub-chapter").inner_text())
        self.page.wait_for_function("() => document.querySelector('.reader-epub-chapter img')?.src.includes('reader-bucket-resource')")
        self.assertIn(manifest_path, requested)
        self.assertIn(chapter_path, requested)
        self.assertIn(resource_path, requested)

    def test_bucket_chapter_internal_links_keep_reader_navigation(self):
        prefix = "chapters/ebook/epub/" + "d" * 64 + "/" + "c" * 16 + "/"
        bodies = {
            1: '<html><body><a href="chapter-0002.xhtml#target">跨章节目录</a><h1>目录</h1></body></html>',
            2: '<html><body><h1 id="target">目标章节</h1><p style="height:12000px">正文</p></body></html>',
        }
        chapter_paths = {index: prefix + f"chapters/chapter-{index:04d}.xhtml" for index in bodies}
        manifest_path = prefix + "chapter-manifest.json"
        manifest = {"version": 1, "kind": "epub-chapters", "chapters": [
            {"index": index, "path": f"chapters/chapter-{index:04d}.xhtml", "title": f"Chapter {index}",
             "bytes": len(body.encode()), "sha256": hashlib.sha256(body.encode()).hexdigest()}
            for index, body in bodies.items()
        ]}
        requests = []
        def serve(route):
            path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)["path"][0]
            requests.append(path)
            if path == manifest_path:
                route.fulfill(content_type="application/json", body=json.dumps(manifest))
            else:
                index = next((i for i, item in chapter_paths.items() if item == path), None)
                route.fulfill(content_type="application/xhtml+xml", body=bodies[index]) if index else route.fulfill(status=404)
        self.page.route("https://voiceofml-search.hf.space/api/reader-bucket-resource**", serve)
        url = "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + urllib.parse.quote(manifest_path, safe="")
        self.open(self.reader_url("epub-chapters", url=url))
        before = self.page.url
        self.page.get_by_text("跨章节目录", exact=True).click()
        self.page.wait_for_function("() => !!document.querySelector('.reader-epub-chapter[data-chapter=\"2\"] #target')")
        self.assertEqual(self.page.url, before)
        self.assertIn(chapter_paths[2], requests)

    def search(self, query):
        support.open_reader_panel(self.page)
        self.page.locator("#full-search-toggle").click()
        self.page.locator("#full-search-input").fill(query)
        self.page.wait_for_function("() => /^(?:\d+ 个结果|未找到正文匹配)$/.test(document.querySelector('#full-search-status').textContent)")

    def wait_for_store(self, predicate, arg=None):
        self.page.evaluate("""async arg => {
          const check = """ + predicate + """;
          const deadline = performance.now() + 6000;
          while (performance.now() < deadline) {
            if (await check(arg)) return;
            await new Promise(resolve => setTimeout(resolve, 30));
          }
          throw new Error('Store condition did not become true');
        }""", arg)

    def test_failed_chapter_restoration_preserves_saved_position(self):
        requests, base = self.serve_chapter_search()
        source = "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + base + "chapter-manifest.json"
        self.page.evaluate("""async source => {
          window.dispatchEvent(new PageTransitionEvent('pagehide', {persisted:false}));
          await new Promise(resolve => setTimeout(resolve, 0));
          await VoiceOfMLReaderStore.put({url:source, title:'Saved chapter',
            chapterIndex:12, chapterOffset:345, lastReadAt:Date.now()+1});
        }""", source)
        self.page.route("**/api/reader-bucket-resource?path=*chapter-0012.xhtml",
                        lambda route: route.fulfill(status=503, body="temporary"))
        self.page.reload()
        self.page.wait_for_timeout(1200)
        saved = self.page.evaluate("source => VoiceOfMLReaderStore.get(source)", source)
        self.assertEqual(saved["chapterIndex"], 12)
        self.assertEqual(saved["chapterOffset"], 345)
        self.assertEqual(self.page.locator("#content").get_attribute("data-error-code"), "READER_RESTORE")
        self.assertTrue(self.page.get_by_role("button", name="重试加载").is_visible())
        self.page.unroute("**/api/reader-bucket-resource?path=*chapter-0012.xhtml")
        self.page.get_by_role("button", name="重试加载").click()
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        self.wait_for_store("async source => (await VoiceOfMLReaderStore.get(source))?.chapterIndex === 12", source)
        offset = self.page.locator('.reader-epub-chapter[data-chapter="12"]').evaluate(
            "node => document.querySelector('#viewport').getBoundingClientRect().top + 8 - node.getBoundingClientRect().top")
        self.assertAlmostEqual(offset, 345, delta=3)

    def test_parent_abort_saves_last_position_before_disposal(self):
        self.serve("reading\n" * 3000)
        self.open(self.reader_url())
        self.page.wait_for_timeout(650)
        self.page.evaluate("""() => {
          const viewport=document.querySelector('#viewport');
          viewport.scrollTop=900;viewport.dispatchEvent(new Event('scroll'));
          window.dispatchEvent(new MessageEvent('message', {origin:location.origin,
            source:window.parent,data:{type:'voice-reader-abort'}}));
        }""")
        source = urllib.parse.parse_qs(urllib.parse.urlsplit(self.page.url).query)["url"][0]
        self.page.wait_for_timeout(100)
        saved = self.page.evaluate("source => VoiceOfMLReaderStore.get(source)", source)
        self.assertEqual(saved["scrollTop"], 900)

    def test_store_lists_preserve_legacy_and_leave_unknown_records_untouched(self):
        self.page.goto(self.reader_url().split('?')[0])
        result = self.page.evaluate('''async () => {
          const store=VoiceOfMLReaderStore;
          await store.put({url:'book-a',lastReadAt:10});
          await store.put({url:'book-b',lastReadAt:20});
          await store.put({url:'book-c',lastReadAt:30});
          await store.put({url:'book-c',lastReadAt:1});
          const db=await new Promise((resolve,reject)=>{
            const request=indexedDB.open(store.DB_NAME,store.DB_VERSION);
            request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(request.error);
          });
          await new Promise((resolve,reject)=>{
            const tx=db.transaction('bookmarks','readwrite'), bookmarks=tx.objectStore('bookmarks');
            for(const entry of [
              {id:'z',url:'book-a',createdAt:1,schemaVersion:1}, {id:'a',url:'book-a',createdAt:3,schemaVersion:1},
              {id:'b',url:'book-b',createdAt:2,schemaVersion:1}, {id:'bad',url:42,createdAt:4},
              {id:'legacy',url:'book-a',createdAt:6},
              {id:'future',url:'book-a',createdAt:5,schemaVersion:2}
            ]) bookmarks.put(entry);
            tx.oncomplete=resolve;tx.onerror=()=>reject(tx.error);
          });
          const history=(await store.list(2)).map(entry=>entry.url);
          const empty=(await store.list(0)).length;
          const all=(await store.listAllBookmarks()).map(entry=>entry.id);
          const one=(await store.listBookmarks('book-a')).map(entry=>entry.id);
          const raw=await new Promise((resolve,reject)=>{
            const tx=db.transaction('bookmarks'), request=tx.objectStore('bookmarks').getAll();
            tx.oncomplete=()=>resolve(request.result);tx.onerror=()=>reject(tx.error);
          });
          db.close();await store.removeBookmark('a');
          return {history,empty,all,one,remaining:(await store.listBookmarks('book-a')).map(entry=>entry.id),
            future:raw.some(entry=>entry.id==='future' && entry.schemaVersion===2),
            legacy:raw.some(entry=>entry.id==='legacy'),
            corruptRetained:raw.some(entry=>entry.id==='bad')};
        }''')
        self.assertEqual(result, dict(history=['book-c', 'book-b'], empty=0, all=['legacy', 'a', 'b', 'z'],
                                      one=['legacy', 'a', 'z'], remaining=['legacy', 'z'], future=True,
                                      legacy=True, corruptRetained=True))

    def test_full_history_warns_that_new_progress_is_not_saved(self):
        self.page.goto(self.origin + '/static/reader.html?ext=unsupported')
        self.page.evaluate('''async () => {
          for(let i=0;i<VoiceOfMLReaderStore.MAX_ENTRIES;i++)
            await VoiceOfMLReaderStore.put({url:'retained-'+i,lastReadAt:i+1});
        }''')
        self.serve('reading\n' * 3000)
        url = self.reader_url(name='capacity-warning')
        source = urllib.parse.parse_qs(urllib.parse.urlsplit(url).query)['url'][0]
        self.open(url)
        self.page.locator('#viewport').evaluate("node => {node.scrollTop=900; node.dispatchEvent(new Event('scroll'));}")
        self.page.wait_for_function("() => document.querySelector('#download-feedback').textContent.includes('进度未保存')")
        self.assertEqual(self.page.evaluate("() => VoiceOfMLReaderStore.list(201).then(items => items.length)"), 200)
        self.assertIsNone(self.page.evaluate('source => VoiceOfMLReaderStore.get(source)', source))
        self.assertIsNotNone(self.page.evaluate("() => VoiceOfMLReaderStore.get('retained-0')"))

    def test_cross_book_bookmark_restores_selected_position_and_rejects_mismatch(self):
        self.serve("start\n" + "ordinary text\n" * 3000)
        book_b = self.reader_url(name="book-b")
        source_b = urllib.parse.parse_qs(urllib.parse.urlsplit(book_b).query)["url"][0]
        self.open(book_b)
        self.page.evaluate("""async ({url, readerUrl}) => {
          await VoiceOfMLReaderStore.putBookmark({id:'selected-bookmark', url, readerUrl,
            title:'Book B', label:'Selected passage', scrollTop:900, createdAt:1});
          await VoiceOfMLReaderStore.put({url, readerUrl, title:'Book B', scrollTop:2500, lastReadAt:Date.now()});
        }""", {"url": source_b, "readerUrl": book_b})
        self.open(self.reader_url(name="book-a"))
        # Override any pagehide save from the old B page before opening its bookmark.
        self.page.evaluate("""async url => VoiceOfMLReaderStore.put({url, title:'Book B',
          scrollTop:2500, lastReadAt:Date.now()+1})""", source_b)
        self.page.locator("#history").click()
        self.page.locator("#bookmarks-tab").click()
        self.page.locator("#bookmarks-all").click()
        self.page.locator("#bookmarks-list .panel-item-main", has_text="Selected passage").click()
        self.page.wait_for_url(book_b)
        self.page.wait_for_function("() => Math.abs(document.querySelector('#viewport').scrollTop - 900) < 2")
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        self.page.evaluate("""() => { document.querySelector('#viewport').scrollTop = 2500;
          document.dispatchEvent(new Event('visibilitychange')); }""")
        self.page.wait_for_timeout(650)
        self.page.reload()
        self.page.wait_for_function("() => Math.abs(document.querySelector('#viewport').scrollTop - 2500) < 2")
        self.open(self.reader_url(name="book-a"))
        self.page.locator("#history").click()
        self.page.locator("#bookmarks-tab").click()
        self.page.locator("#bookmarks-all").click()
        self.page.locator("#bookmarks-list .panel-item-main", has_text="Selected passage").click()
        self.page.wait_for_url(book_b)
        self.page.wait_for_function("() => Math.abs(document.querySelector('#viewport').scrollTop - 900) < 2")
        self.page.locator("#viewport").evaluate("node => { node.scrollTop = 2500; node.dispatchEvent(new Event('scroll')); }")
        self.page.wait_for_timeout(650)
        invalid = book_b + "&bookmark=selected-bookmark&bookmark_source=wrong-source"
        self.open(invalid)
        self.page.wait_for_function("() => Math.abs(document.querySelector('#viewport').scrollTop - 2500) < 2")
        saved = self.page.evaluate("url => VoiceOfMLReaderStore.get(url)", source_b)
        self.assertNotIn("bookmark=", saved["readerUrl"])

    def test_overlay_bookmark_consumes_parent_navigation_records_and_reloads_history(self):
        self.serve("reading\n" * 3000)
        book = self.reader_url(name="overlay-book")
        source = urllib.parse.parse_qs(urllib.parse.urlsplit(book).query)["url"][0]
        self.open(book)
        self.page.evaluate("""async ({source, book}) => {
          await VoiceOfMLReaderStore.putBookmark({id:'overlay-bookmark', url:source,
            readerUrl:book, label:'Overlay', scrollTop:900, createdAt:1});
        }""", {"source": source, "book": book})
        handoff = book + "&" + urllib.parse.urlencode({
            "bookmark": "overlay-bookmark", "bookmark_source": source,
            "return": self.origin + "/Test?q=retained", "nav": "return-token"
        })
        shell = """<!doctype html><body><script>
          window.openReader = readerUrl => {
            const share = new URL(readerUrl); share.searchParams.delete('return'); share.searchParams.delete('nav');
            history.replaceState({voiceReaderOverlay:true, readerUrl, extra:'keep'}, '', share.href);
            sessionStorage.setItem('reader-navigation-current', JSON.stringify({readerUrl, shareUrl:share.href,
              returnScroll:{top:123}, extra:'keep'}));
            document.querySelector('iframe')?.remove();
            const frame = document.createElement('iframe'); frame.className='reader-overlay';
            frame.style='width:100%;height:750px'; frame.src=readerUrl; document.body.append(frame);
          };
          openReader(history.state?.readerUrl || JSON.parse(sessionStorage.getItem('reader-navigation-current') || 'null')?.readerUrl || HANDOFF);
        </script>""".replace("HANDOFF", json.dumps(handoff))
        def overlay(route):
            if route.request.is_navigation_request() and route.request.frame == self.page.main_frame:
                route.fulfill(content_type="text/html", body=shell)
            else:
                route.fallback()
        self.page.route("**/static/reader.html?**", overlay)
        self.page.goto(handoff)
        frame = self.page.frame_locator("iframe.reader-overlay")
        frame.locator("#viewport").evaluate("node => node.scrollTop")
        self.page.wait_for_function("() => !new URL(location.href).searchParams.has('bookmark')")
        state = self.page.evaluate("({state:history.state, saved:JSON.parse(sessionStorage.getItem('reader-navigation-current'))})")
        self.assertNotIn("bookmark=", state["state"]["readerUrl"])
        self.assertNotIn("bookmark=", state["saved"]["readerUrl"])
        self.assertNotIn("bookmark=", state["saved"]["shareUrl"])
        self.assertEqual(state["state"]["extra"], "keep")
        self.assertEqual(state["saved"]["returnScroll"], {"top": 123})
        self.assertIn("nav=return-token", state["state"]["readerUrl"])
        self.assertEqual(frame.locator("#viewport").evaluate("node => node.scrollTop"), 900)
        frame.locator("#viewport").evaluate("node => {node.scrollTop=2500; node.dispatchEvent(new Event('scroll'));}")
        self.wait_for_store("async source => (await document.querySelector('iframe').contentWindow.VoiceOfMLReaderStore.get(source))?.scrollTop === 2500", source)
        for session_only in (False, True):
            if session_only:
                self.page.evaluate("history.replaceState(null, '', location.href)")
            self.page.reload()
            self.page.wait_for_function("() => document.querySelector('iframe')?.contentDocument?.querySelector('#viewport')?.scrollTop === 2500")
        self.page.evaluate("url => openReader(url)", handoff)
        self.page.wait_for_function("() => document.querySelector('iframe')?.contentDocument?.querySelector('#viewport')?.scrollTop === 900 && !new URL(location.href).searchParams.has('bookmark')")

    def test_remote_history_deletion_blocks_queued_and_future_saves_until_reopen(self):
        self.serve("reading\n" * 3000)
        url = self.reader_url(name="remote-history")
        source = urllib.parse.parse_qs(urllib.parse.urlsplit(url).query)["url"][0]
        peer = self.context.new_page()
        store_path = urllib.parse.urlsplit(url).path.replace("reader.html", "reader/core/reader-store.js")
        peer.route("**/store-peer", lambda route: route.fulfill(content_type="text/html", body=f'<script src="{store_path}"></script>'))
        peer.goto(self.origin + "/store-peer")
        for event_type in ("history-remove", "history-clear"):
            with self.subTest(event_type=event_type):
                self.open(url)
                self.wait_for_store("async source => !!(await VoiceOfMLReaderStore.get(source))", source)
                self.page.evaluate("""() => {
                  const store=VoiceOfMLReaderStore; window.__writes=0; window.__changes=[];
                  store.subscribe(change => { if(change.remote) window.__changes.push(change.type); });
                  window.VoiceOfMLReaderStore={...store, put:async entry => {
                    ++window.__writes; await store.put(entry);
                    if(window.__writes===1) await new Promise(resolve => window.__releaseWrite=resolve);
                  }};
                  document.querySelector('#viewport').scrollTop=900;
                }""")
                self.page.wait_for_function("() => !!window.__releaseWrite")
                self.page.locator("#viewport").evaluate("node => {node.scrollTop=1500; node.dispatchEvent(new Event('scroll'));}")
                self.page.wait_for_timeout(650)
                await_event = {"type": event_type, "source": source}
                peer.evaluate("async ({type,source}) => type==='history-clear' ? VoiceOfMLReaderStore.clearHistory() : VoiceOfMLReaderStore.remove(source)", await_event)
                self.page.wait_for_function("type => window.__changes.includes(type)", arg=event_type)
                self.page.evaluate("window.__releaseWrite()")
                self.page.locator("#viewport").evaluate("node => {node.scrollTop=2200; node.dispatchEvent(new Event('scroll'));}")
                self.page.wait_for_timeout(750)
                self.assertEqual(self.page.evaluate("window.__writes"), 1)
                self.assertIsNone(peer.evaluate("source => VoiceOfMLReaderStore.get(source)", source))
                self.page.reload()
                # Wait for startup separately, as open() does, so a slow reload
                # cannot consume the window for the reopened Reader's save.
                self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
                self.wait_for_store("async source => !!(await VoiceOfMLReaderStore.get(source))", source)
        peer.close()

    def test_bookmark_cleanup_preserves_unrelated_parent_and_session_navigation(self):
        self.serve("reading\n" * 3000)
        book = self.reader_url(name="cleanup-target")
        source = urllib.parse.parse_qs(urllib.parse.urlsplit(book).query)["url"][0]
        self.open(book)
        self.page.evaluate("async ({source,book}) => VoiceOfMLReaderStore.putBookmark({id:'cleanup-mark',url:source,readerUrl:book,label:'Target',scrollTop:900,createdAt:1})", {"source": source, "book": book})
        handoff = book + "&" + urllib.parse.urlencode({"bookmark": "cleanup-mark", "bookmark_source": source})
        unrelated = self.reader_url(name="different", bookmark="other", bookmark_source="other")
        record = {"readerUrl": unrelated, "shareUrl": unrelated, "extra": "preserve"}
        shell = """<!doctype html><body><script>
          history.replaceState({voiceReaderOverlay:true, readerUrl:OTHER}, '', OTHER);
          sessionStorage.setItem('reader-navigation-current', JSON.stringify(RECORD));
          const frame=document.createElement('iframe'); frame.className='reader-overlay';
          frame.style='height:750px;width:100%'; frame.src=HANDOFF; document.body.append(frame);
        </script>""".replace("OTHER", json.dumps(unrelated)).replace("RECORD", json.dumps(record)).replace("HANDOFF", json.dumps(handoff))
        self.page.route("**/unrelated-overlay", lambda route: route.fulfill(content_type="text/html", body=shell))
        self.page.goto(self.origin + "/unrelated-overlay")
        self.page.wait_for_function("() => {const w=document.querySelector('iframe')?.contentWindow; return w?.document.querySelector('#viewport')?.scrollTop===900 && !new URL(w.location.href).searchParams.has('bookmark');}")
        self.assertEqual(self.page.url, unrelated)
        self.assertEqual(self.page.evaluate("history.state.readerUrl"), unrelated)
        self.assertEqual(self.page.evaluate("JSON.parse(sessionStorage.getItem('reader-navigation-current'))"), record)

    def test_remote_unrelated_history_removal_does_not_suppress_current_media(self):
        self.serve(support.minimal_wav(), "audio/wav")
        self.open(self.reader_url("wav", name="remote-media"))
        self.page.wait_for_function("() => document.querySelector('audio').readyState >= 1")
        self.page.evaluate("""() => {
          window.__changes=[]; VoiceOfMLReaderStore.subscribe(change => {if(change.remote) window.__changes.push(change.type);});
          const media=document.querySelector('audio');
          Object.defineProperty(media,'currentTime',{value:45,writable:true});
        }""")
        peer = self.context.new_page()
        peer.goto(self.origin + "/static/reader.html?ext=unsupported")
        peer.evaluate("() => VoiceOfMLReaderStore.remove('unrelated')")
        self.page.wait_for_function("() => window.__changes.includes('history-remove')")
        self.page.locator("audio").evaluate("media => media.dispatchEvent(new Event('timeupdate'))")
        self.wait_for_store("async () => (await VoiceOfMLReaderStore.get(new URL(location.href).searchParams.get('url')))?.mediaTime===45")
        peer.evaluate("() => VoiceOfMLReaderStore.clearHistory()")
        self.page.wait_for_function("() => window.__changes.includes('history-clear')")
        self.page.locator("audio").evaluate("media => {media.currentTime=60; for(const type of ['timeupdate','pause','seeked']) media.dispatchEvent(new Event(type));}")
        self.page.wait_for_timeout(750)
        self.assertIsNone(self.page.evaluate("() => VoiceOfMLReaderStore.get(new URL(location.href).searchParams.get('url'))"))
        peer.close()

    def test_late_txt_history_survives_empty_search_but_yields_to_query_or_navigation(self):
        store = support.STORE_SCRIPT.replace(
            "get: () => new Promise((resolve) => setTimeout(() => resolve(null), 300)),",
            "get: url => new Promise(resolve => { window.__releaseRestore = () => resolve({url, scrollTop: 85000}); }),",
        )
        self.page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(
            content_type="text/javascript", body=store))
        self.serve("a long line of text for the saved reading position\n" * 10000 + "needle")
        self.page.emulate_media(reduced_motion="reduce")
        for action in ("open-only", "blank-input", "query", "navigation"):
            with self.subTest(action=action):
                self.page.goto(self.reader_url(name=action), wait_until="domcontentloaded")
                self.page.wait_for_function("() => window.__releaseRestore && document.querySelectorAll('.reader-text-block').length > 8")
                viewport = self.page.locator("#viewport")
                self.assertEqual(viewport.evaluate("node => node.scrollTop"), 0)
                self.assertFalse(self.page.evaluate("!!window.__savedReaderProgress"))
                if action == "navigation":
                    self.page.keyboard.press("PageDown")
                    self.page.wait_for_function("() => document.querySelector('#viewport').scrollTop > 0")
                else:
                    self.page.locator("#history").click()
                    self.page.locator("#full-search-toggle").click()
                    if action == "blank-input":
                        self.page.locator("#full-search-input").fill("   ")
                        self.page.locator("#full-search-clear").click()
                        self.page.locator("#full-search-toggle").click()
                expected = 85000 if action in ("open-only", "blank-input") else viewport.evaluate("node => node.scrollTop")
                if action == "query":
                    # Commit the input and release the lookup in the same task, before debounce.
                    self.page.evaluate('''() => {
                      const input = document.querySelector('#full-search-input');
                      input.value = 'needle';
                      input.dispatchEvent(new Event('input', {bubbles: true}));
                      window.__releaseRestore();
                    }''')
                else:
                    self.page.evaluate("window.__releaseRestore()")
                self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
                if action == "query":
                    self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")
                self.assertEqual(viewport.evaluate("node => node.scrollTop"), expected)
                self.page.wait_for_function("top => window.__savedReaderProgress?.scrollTop === top", arg=expected)

    def test_search_reopen_retains_live_targets(self):
        self.serve("prefix\n" * 500 + "needle" + "\nending" * 500)
        self.open(self.reader_url())
        self.search("needle")
        self.page.locator("#full-search-toggle").click()
        self.assertEqual(self.page.locator("#content .full-search-highlight").count(), 1)
        self.page.locator("#full-search-toggle").click()
        self.page.locator("#full-search-results .full-search-result").click()
        self.page.wait_for_function("() => document.querySelector('#viewport').scrollTop > 1000")
        self.assertEqual(self.page.locator("#content .full-search-highlight").text_content(), "needle")

    def test_search_reopen_keeps_results_and_clear_control_state(self):
        self.serve("begin " + "middle " * 400 + "needle at the end")
        self.open(self.reader_url())
        self.page.locator("#history").click()
        self.assertTrue(self.page.locator("#full-search-clear").is_hidden())
        self.page.locator("#full-search-toggle").click()
        self.assertEqual(self.page.locator("#full-search-toggle").text_content(), "关闭全文搜索")
        self.page.locator("#full-search-input").fill("needle")
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")
        self.assertEqual(self.page.locator(".full-search-rank").text_content(), "1.")
        self.assertIn("正文 ", self.page.locator(".full-search-location").text_content())
        self.assertTrue(self.page.locator("#full-search-clear").is_visible())
        self.page.locator(".full-search-result").click()
        self.page.locator("#history").click()
        self.assertFalse(self.page.locator("#full-search-view").is_hidden())
        self.assertEqual(self.page.locator("#full-search-status").text_content(), "1 个结果")
        self.page.locator("#full-search-toggle").click()
        self.assertEqual(self.page.locator("#full-search-toggle").text_content(), "全文搜索")
        self.page.locator("#full-search-toggle").click()
        self.assertEqual(self.page.locator("#full-search-status").text_content(), "1 个结果")
        self.page.locator("#full-search-clear").click()
        self.assertTrue(self.page.locator("#full-search-clear").is_hidden())

    def test_top_level_reader_adds_no_history_guard_and_system_back_leaves(self):
        # A standalone Reader (e.g. a restored tab) must not push a guard entry:
        # Chromium marks entries created without a user activation as skippable.
        self.serve("needle " * 300)
        url = self.reader_url()
        self.page.goto("about:blank")
        before = self.page.evaluate("history.length")
        self.page.goto(url)
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        self.assertEqual(self.page.evaluate("history.length"), before + 1)
        self.assertFalse(self.page.evaluate("!!history.state?.voiceReaderGuard"))
        self.page.locator("#history").click()
        self.page.wait_for_function("() => document.querySelector('#history-panel').classList.contains('is-open')")
        self.page.go_back()
        self.assertEqual(self.page.url, "about:blank")

    def test_txt_small_chunks_reuse_preview_decoder_and_visit_samples_once(self):
        def instrument(route):
            response = route.fetch()
            script = response.text()
            needle = 'for (const chunk of sampleChunks) {'
            self.assertIn(needle, script)
            route.fulfill(response=response, body=script.replace(needle,
                needle + ' window.__sampleVisits = (window.__sampleVisits || 0) + 1;'))
        self.page.route('**/static/reader/formats/reader-text-format.mjs*', instrument)
        self.page.add_init_script('''const nativeFetch = window.fetch.bind(window), Decoder = window.TextDecoder;
          window.__previewDecoders = 0;
          window.TextDecoder = class extends Decoder {
            constructor(label, ...args) { super(label, ...args); if (!label || label === 'utf-8') window.__previewDecoders++; }
          };
          window.fetch = (url, init) => String(url).includes('/api/reader-content?')
            ? Promise.resolve(new Response(new ReadableStream({start(controller) {
                controller.enqueue(new TextEncoder().encode('h'));
                controller.enqueue(new TextEncoder().encode('ea'));
                controller.enqueue(new TextEncoder().encode('d'));
                window.__finishChunks = () => {
                  for (let i = 0; i < 600; i++) controller.enqueue(new TextEncoder().encode('x'.repeat(64)));
                  for (const byte of new TextEncoder().encode('\\n\u4e2d\u6587')) controller.enqueue(new Uint8Array([byte]));
                  controller.close();
                };
              }}), {headers:{'Content-Type':'text/plain'}})) : nativeFetch(url, init);''')
        self.page.goto(self.reader_url(), wait_until='domcontentloaded')
        self.page.locator('.reader-text').filter(has_text='head').wait_for()
        self.assertEqual(self.page.locator('.reader-text').text_content(), 'head')
        self.search('head')
        self.page.evaluate('window.__finishChunks()')
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        self.assertEqual(self.page.locator('.reader-text').text_content(), 'head' + 'x' * 38400 + '\n中文')
        self.assertLessEqual(self.page.evaluate('window.__sampleVisits'), 1220)
        self.assertLessEqual(self.page.evaluate('window.__previewDecoders'), 5)

    def test_txt_preview_cursor_preserves_split_legacy_encodings(self):
        self.page.add_init_script('''const nativeFetch = window.fetch.bind(window);
          window.fetch = (url, init) => String(url).includes('/api/reader-content?')
            ? Promise.resolve(new Response(new ReadableStream({start(controller) {
                const bytes = new Uint8Array(JSON.parse(new URL(location.href).searchParams.get('test_bytes')));
                for (const byte of bytes.slice(0, 4)) controller.enqueue(new Uint8Array([byte]));
                window.__finishLegacy = () => {
                  for (const byte of bytes.slice(4)) controller.enqueue(new Uint8Array([byte]));
                  controller.close();
                };
              }}))) : nativeFetch(url, init);''')
        cases = [('丠丠ABCD', 'utf-16le', 'Encoding'), ('中文文本', 'utf-16', 'Encoding'),
                 ('中文文本', 'utf-16be', 'Encoding'), ('head中文文本', 'gb18030', '中文'),
                 ('Русский текст', 'cp1251', 'Русский'), ('head中文', 'utf-8-sig', 'Encoding')]
        for text, encoding, title in cases:
            with self.subTest(encoding=encoding):
                encoded = text.encode(encoding)
                if encoding == 'utf-16be':
                    encoded = b'\xfe\xff' + encoded
                self.page.goto(self.reader_url(title=title, test_bytes=json.dumps(list(encoded))), wait_until='domcontentloaded')
                self.page.wait_for_function('() => !!window.__finishLegacy')
                if encoding == 'utf-16le':
                    self.page.wait_for_function("() => document.querySelector('.reader-text')?.textContent === ' N N'")
                self.page.evaluate('window.__finishLegacy()')
                self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
                self.assertEqual(self.page.locator('.reader-text').text_content(), text)

    def test_text_search_publishes_partial_results_before_full_scan(self):
        self.page.add_init_script("""const native = window.setTimeout.bind(window);
          window.setTimeout = (fn, ms, ...args) => native(fn, ms === 0 ? 20 : ms, ...args);""")
        self.serve("needle " + "x" * 600000 + " needle")
        self.open(self.reader_url())
        self.page.locator("#history").click()
        self.page.locator("#full-search-toggle").click()
        self.page.locator("#full-search-input").fill("needle")
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent.includes('正在搜索') && document.querySelectorAll('.full-search-result').length === 1")
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '2 个结果'")
        self.assertEqual(self.page.locator(".full-search-rank").all_text_contents(), ["1.", "2."])

    def test_typing_new_full_search_disables_old_navigation_immediately(self):
        self.serve("oldword " * 65 + "freshword")
        self.open(self.reader_url())
        self.search("oldword")
        self.assertEqual(self.page.locator("#full-search-status").text_content(), "65 个结果")
        self.assertTrue(self.page.locator(".full-search-pagination").is_visible())
        self.page.locator("#full-search-input").fill("freshword")
        self.assertEqual(self.page.locator(".full-search-result").count(), 0)
        self.assertTrue(self.page.locator(".full-search-pagination").is_hidden())
        self.assertTrue(self.page.locator("#full-search-next").is_disabled())
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")

    def test_disposal_cancels_debounced_full_search(self):
        self.page.add_init_script("""const nativeTimeout = window.setTimeout.bind(window);
          window.__searchDebounceCallbacks = 0;
          window.setTimeout = (callback, delay, ...args) => nativeTimeout(
            delay === 180 ? (...values) => {
              window.__searchDebounceCallbacks++;
              callback(...values);
            } : callback, delay, ...args);""")
        self.serve("needle " * 100)
        self.open(self.reader_url())
        self.page.evaluate("""() => {
          const input = document.querySelector('#full-search-input');
          input.value = 'needle';
          input.dispatchEvent(new Event('input', {bubbles: true}));
          window.dispatchEvent(new Event('voice-reader-dispose'));
        }""")
        self.page.wait_for_timeout(300)
        self.assertEqual(self.page.locator('html').get_attribute('data-reader-phase'), 'disposed')
        self.assertEqual(self.page.evaluate('window.__searchDebounceCallbacks'), 0)
        self.assertEqual(self.page.locator('.full-search-result').count(), 0)

    def test_pending_text_result_cannot_highlight_after_new_search(self):
        def hold_activation(route):
            response = route.fetch()
            needle = ("let collected = await fullSearchTextNodes("
                      "root, searchGeneration, end, checkpoint, collectMatch);")
            script = response.text()
            self.assertIn(needle, script)
            route.fulfill(response=response, body=script.replace(needle,
                "await new Promise(resolve => { window.__releaseActivation = resolve; }); " +
                needle + " window.__activationSettled = true;"))
        self.page.route("**/static/reader/search/reader-dom-search.mjs*", hold_activation)
        self.serve("oldword " * 70 + "freshword")
        self.open(self.reader_url())
        self.search("oldword")
        self.page.locator(".full-search-result").first.click()
        self.page.wait_for_function("() => !!window.__releaseActivation")
        self.page.locator("#full-search-input").fill("freshword")
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")
        self.page.evaluate("window.__releaseActivation()")
        self.page.wait_for_function("() => window.__activationSettled")
        self.assertEqual(self.page.locator("#content mark.full-search-highlight").all_text_contents(), ["freshword"])

    def test_dom_search_navigation_only_walks_through_selected_match(self):
        html = '<p>before <span>nee</span><b>dl</b><i>e</i> after</p>' + '<p>ordinary</p>' * 8000 + '<p>last <span>nee</span><b>dl</b><i>e</i></p>'
        def instrument(route):
            response = route.fetch()
            route.fulfill(response=response, body=response.text() + """
              window.__probeActivationWalk = () => {
                const doc = (htmlFrame?.contentDocument?.body || content).ownerDocument;
                const native = doc.createTreeWalker.bind(doc);
                window.__activationVisited = 0;
                doc.createTreeWalker = (...args) => {
                  const walker = native(...args), next = walker.nextNode.bind(walker);
                  walker.nextNode = () => { window.__activationVisited++; return next(); };
                  return walker;
                };
              };
            """)
        self.page.route("**/static/reader.js*", instrument)
        for extension in ('html', 'md', 'txt'):
            with self.subTest(extension=extension):
                self.serve('before needle after\n' + 'ordinary\n' * 8000 + 'last needle' if extension == 'txt' else html,
                           'text/html' if extension == 'html' else 'text/plain')
                source = self.reader_url(extension)
                self.open(source)
                self.search('needle')
                self.assertEqual(self.page.locator('#full-search-status').text_content(), '2 个结果')
                self.page.evaluate('window.__probeActivationWalk()')
                self.page.locator('.full-search-result').first.click()
                target = self.page.frame_locator('.html-frame') if extension == 'html' else self.page
                self.assertEqual(''.join(target.locator('mark.full-search-highlight').all_text_contents()), 'needle')
                self.assertLessEqual(self.page.evaluate('window.__activationVisited'), 4)
                self.page.locator('#history').click()
                self.page.evaluate('window.__activationVisited = 0')
                self.page.locator('.full-search-result').last.click()
                target.locator('mark.full-search-highlight').first.wait_for()
                self.assertEqual(''.join(target.locator('mark.full-search-highlight').all_text_contents()), 'needle')
                self.assertLessEqual(self.page.evaluate('window.__activationVisited'), 130)
                self.page.locator('#history').click()
                self.page.evaluate('window.__activationVisited = 0')
                self.page.locator('.full-search-result').last.click()
                self.assertEqual(''.join(target.locator('mark.full-search-highlight').all_text_contents()), 'needle')
                self.assertLessEqual(self.page.evaluate('window.__activationVisited'), 130)

    def expose_dom_search_locator(self):
        expose_dom_search_tools(self.page)
        def instrument(route):
            response = route.fetch()
            route.fulfill(response=response, body=response.text() + '''
              window.__domLocator = () => window.__domSearchTools.locator();
              window.__activateDomResult = async index => {
                const doc = (htmlFrame?.contentDocument?.body || content).ownerDocument;
                const native = doc.createTreeWalker.bind(doc);
                let visits = 0;
                doc.createTreeWalker = (...args) => {
                  const walker = native(...args), next = walker.nextNode.bind(walker);
                  walker.nextNode = () => { visits++; return next(); };
                  return walker;
                };
                try { return {ok: await searchState.results[index].activate(), visits}; }
                finally { doc.createTreeWalker = native; }
              };
              window.__headingOracle = async entries => {
                const root = htmlFrame.contentDocument.body;
                setToc(entries.map(entry => ({label:entry.label, target:root.querySelector(entry.selector)})));
                const offsets = [];
                await window.__domSearchTools.textNodes(root, readerRuntime.currentGeneration('search'), Infinity, null,
                  (node, start, end) => offsets.push({node, start, end}));
                const length = offsets.at(-1)?.end || 0;
                const lookup = window.__domSearchTools.headingLookup(root, offsets);
                const compare = () => offsets.map(part => {
                  const heading = [...navigationState.tocEntries].reverse().find(entry => entry.target &&
                    (entry.target === part.node.parentElement ||
                     (entry.target.compareDocumentPosition(part.node) & Node.DOCUMENT_POSITION_FOLLOWING)));
                  const page = part.node.parentElement.closest('[data-page]');
                  const expected = page ? '第 ' + page.dataset.page + ' 页' :
                    heading ? heading.label : '正文 ' + Math.min(100, Math.floor(part.start / Math.max(1,length) * 100)) + '%';
                  return [window.__domSearchTools.location(part.node, part.start, length, lookup), expected];
                });
                const pairs = compare();
                setToc([...navigationState.tocEntries].reverse());
                return {indexed:!!lookup, pairs:[...pairs, ...compare()]};
              };
            ''')
        self.page.route('**/static/reader.js*', instrument)

    def test_dom_search_locator_invalidates_on_mutation_and_releases_on_query_and_disposal(self):
        self.expose_dom_search_locator()
        self.serve('<p>needle</p>' + '<p>ordinary</p>' * 9000 + '<p>last needle</p>', 'text/html')
        self.open(self.reader_url('html'))
        self.search('needle')
        self.assertLessEqual(self.page.evaluate('__activateDomResult(1)')['visits'], 130)
        # No task boundary: pending observer records must invalidate synchronously too.
        result = self.page.evaluate('''() => {
          const root = document.querySelector('.html-frame').contentDocument.body;
          root.append(root.ownerDocument.createTextNode(' appended needle'));
          return __activateDomResult(1);
        }''')
        self.assertTrue(result['ok'])
        self.assertGreater(result['visits'], 9000)
        self.page.evaluate('window.__oldLocator = __domLocator()')
        self.page.locator('#full-search-input').fill('ordinary')
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '9000 个结果'")
        self.assertFalse(self.page.evaluate('__oldLocator.current()'))
        self.page.locator('#full-search-input').fill('needle')
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '3 个结果'")
        self.assertEqual(self.page.locator('#full-search-status').text_content(), '3 个结果')
        result = self.page.evaluate('__activateDomResult(2)')
        self.assertTrue(result['ok'])
        self.assertLessEqual(result['visits'], 130)
        result = self.page.evaluate('''() => {
          const root = document.querySelector('.html-frame').contentDocument.body;
          root.prepend(root.ownerDocument.createTextNode('shift prefix '));
          return __activateDomResult(2);
        }''')
        self.assertFalse(result['ok'])
        self.assertEqual(self.page.frame_locator('.html-frame').locator('mark.full-search-highlight').count(), 0)
        self.page.evaluate('window.__oldLocator = __domLocator(); window.dispatchEvent(new Event("pagehide"))')
        self.assertFalse(self.page.evaluate('__oldLocator.current()'))
        self.assertTrue(self.page.evaluate('__domLocator() === null'))

    def test_dom_search_heading_boundaries_preserve_labels_after_repeated_navigation_and_paging(self):
        self.serve('<p>needle before</p>' + ''.join(
            f'<h2 id="heading-{index}">Heading {index}</h2><p>needle</p>' for index in range(150)), 'text/html')
        self.open(self.reader_url('html'))
        self.search('needle')
        self.assertEqual(self.page.locator('#full-search-status').text_content(), '151 个结果')
        self.assertEqual(self.page.locator('.full-search-location').all_text_contents()[1:],
                         [f'Heading {index}' for index in range(49)])
        self.page.locator('.full-search-result').last.click()
        self.page.locator('#history').click()
        self.page.locator('#full-search-page').fill('3')
        self.page.locator('#full-search-page').dispatch_event('change')
        self.page.wait_for_function("() => document.querySelector('.full-search-rank')?.textContent === '101.'")
        self.assertEqual(self.page.locator('.full-search-location').all_text_contents(),
                         [f'Heading {index}' for index in range(99,149)])
        self.page.locator('.full-search-result').last.click()
        self.assertEqual(self.page.frame_locator('.html-frame').locator('mark.full-search-highlight').all_text_contents(), ['needle'])

    def test_dom_search_heading_lookup_matches_ordered_duplicate_empty_and_unordered_toc(self):
        self.expose_dom_search_locator()
        self.serve('''<p>Before</p><h2 id="one">One</h2><div>Outer<h3 id="two">Two</h3>After</div>
          <h2 id="empty"></h2><h2 id="three">Three</h2><p data-page="7">Page text</p><p>Tail</p>''', 'text/html')
        self.open(self.reader_url('html'))
        ordered = [{'selector':'#one','label':'One'}, {'selector':'#two','label':'Two'},
                   {'selector':'#two','label':'Duplicate'}, {'selector':'#empty','label':'Empty'},
                   {'selector':'#three','label':'Three'}]
        for entries, indexed in ((ordered, True), ([ordered[0]], True), (list(reversed(ordered)), False)):
            result = self.page.evaluate('__headingOracle', entries)
            self.assertEqual(result['indexed'], indexed)
            for actual, expected in result['pairs']:
                self.assertEqual(actual, expected)

    def test_search_scans_beyond_20000_nodes_and_cancels_old_query(self):
        self.serve("<main>" + "<span>ordinary </span>" * 21000 + "<p>unique-tail</p></main>", "text/html")
        self.open(self.reader_url("html"))
        self.search("unique-tail")
        self.assertEqual(self.page.locator(".full-search-result").count(), 1)
        self.page.locator("#full-search-input").evaluate("""input => {
          input.value='ordinary'; input.dispatchEvent(new Event('input'));
          input.value='unique-tail'; input.dispatchEvent(new Event('input'));
        }""")
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")
        self.assertEqual(self.page.frame_locator(".html-frame").locator(".full-search-highlight").all_text_contents(), ["unique-tail"])

    def test_search_retains_matches_across_character_batches_and_pages_all_results(self):
        text = "x" * 65533 + "boundary-needle" + " y" * 100
        self.serve(text)
        self.open(self.reader_url())
        self.search("boundary-needle")
        self.assertEqual(self.page.locator(".full-search-result").count(), 1)
        self.page.locator("#full-search-input").fill("x")
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '65533 个结果'")
        self.assertEqual(self.page.locator("#content mark").count(), 100)
        self.page.locator("#full-search-page").fill("3")
        self.page.locator("#full-search-page").press("Enter")
        self.page.wait_for_function("() => document.querySelector('#full-search-page').value === '3' && document.querySelector('.full-search-rank')?.textContent === '101.'")
        self.page.locator(".full-search-result").first.click()
        self.assertEqual(self.page.locator("#content mark.full-search-highlight").all_text_contents(), ["x"])

    def test_html_preparation_reuses_sanitized_dom_without_changing_safe_output(self):
        def expose(route):
            response = route.fetch()
            script = response.text()
            anchor = 'export function createReaderHtmlFormat(readerContext) {'
            self.assertEqual(script.count(anchor), 1)
            route.fulfill(response=response, body=script.replace(
                anchor, anchor + '\nwindow.__sanitizeHtml = sanitizeOfflineHtml;'))
        self.page.route('**/formats/reader-html-format.mjs*', expose)
        self.serve('<p>Ready</p>', 'text/html')
        self.open(self.reader_url('html'))
        result = self.page.evaluate(r'''() => {
          const inputs = [
            '<meta charset="utf-8"><title>Title</title><p>中文🌼 &amp; text <b>bold</b></p>',
            '<style>@import "https://invalid.test/css";p{color:#111;background:url(https://invalid.test/bg)}</style><p style="margin:0">Text</p>',
            '<p style="background:url(javascript:bad);color:#111">Content</p><img src="https://invalid.test/img" onerror="evil()">',
            '<base href="https://invalid.test"><script>evil()</script><iframe srcdoc="evil()"></iframe><form><input formaction="x"></form><a href="javascript:bad" onclick="evil()">Link</a>',
            '<table>before<tr><td>A<td>B</tr>after</table><p>a<b>b<i>c</b>d</i><hr><p>tail',
            '<svg><foreignObject><p>Not HTML</p></foreignObject></svg><math><mtext><table><mglyph><style><!--</style><img title="--><img src=1 onerror=evil()>">',
            '<template><p>template text</p></template><noscript><p>fallback</p></noscript><p id="__proto__">End</p>',
            '<div class="reader-spreadsheet-sheet"><table><tr><td style="color:red">Cell</td></tr></table></div>',
            '<div>' + '<p style="margin:0;color:#111">Complete <b>needle</b></p>'.repeat(500) + '</div>'
          ];
          const reference = text => {
            const clean = DOMPurify.sanitize(text, {
              USE_PROFILES:{html:true},ADD_TAGS:['style'],
              FORBID_TAGS:['base','embed','form','iframe','object','script'],
              FORBID_ATTR:['action','formaction','srcdoc'],
              ALLOWED_URI_REGEXP:/^data:image\/(?:gif|png|jpeg|webp|svg\+xml);/i
            });
            const template=document.createElement('template');template.innerHTML=clean;
            const strip=value=>value.replace(/@import[^;]+;|url\s*\([^)]*\)/gi,'');
            for(const style of template.content.querySelectorAll('style'))style.textContent=strip(style.textContent);
            for(const node of template.content.querySelectorAll('[style]'))node.setAttribute('style',strip(node.getAttribute('style')));
            return template.innerHTML;
          };
          return inputs.map(text=>{
            const actual=__sanitizeHtml(text),expected=reference(text),template=document.createElement('template');
            template.innerHTML=actual;
            const unsafe=!!template.content.querySelector('script,iframe,object,embed,base,form,[onclick],[onerror],[srcdoc],[formaction]');
            const remote=!!template.content.querySelector('[src^="http"],[href^="http"],[href^="javascript"]');
            const styles=[...template.content.querySelectorAll('style,[style]')].some(n=>/url\s*\(|@import/i.test(n.localName==='style'?n.textContent:n.getAttribute('style')));
            return {equal:actual===expected,unsafe,remote,styles};
          });
        }''')
        self.assertEqual(result, [dict(equal=True, unsafe=False, remote=False, styles=False)] * 9)

    def test_back_tapped_before_reader_module_binds_still_exits(self):
        held = []
        self.page.route("**/static/reader.js*", lambda route: held.append(route))
        landing = self.origin + ("/search/" if "/search/" in self.reader_url() else "/")
        self.page.route(lambda url: url == landing,
                        lambda route: route.fulfill(content_type="text/html", body="<p>search page</p>"))
        self.serve("early back\n" * 50)
        self.page.goto(self.reader_url(name="early-back"), wait_until="commit")
        self.page.locator("#back").wait_for(state="visible")
        deadline = time.time() + 10
        while not held and time.time() < deadline:
            self.page.wait_for_timeout(50)
        self.assertTrue(held, "reader module was not requested")
        url = self.page.url
        self.page.locator("#back").click()
        self.assertEqual(self.page.url, url, 'a slow module still owns successful startup Back')
        held.pop(0).continue_()
        self.page.wait_for_url(landing, timeout=8000)

    def test_standalone_back_after_module_dependency_failure(self):
        landing = self.origin + "/"
        target = landing + "Test?q=return"
        for destination in (landing, target):
            self.page.route(destination, lambda route: route.fulfill(content_type="text/html", body="search page"))
        self.page.route("**/static/reader/core/reader-bindings.mjs*", lambda route: route.abort())
        # An exact token retains a native Back (not a push or replacement).
        self.page.goto(target)
        self.page.evaluate("sessionStorage.setItem('reader-return:test', location.href)")
        url = self.reader_url(name="module-failure", nav="test", **{"return": target})
        self.page.goto(url, wait_until="load")
        self.page.locator("#back").click()
        self.page.wait_for_url(target)
        self.assertIsNone(self.page.evaluate("sessionStorage.getItem('reader-return:test')"))
        self.page.go_forward(wait_until="load")
        self.assertEqual(self.page.url, url)
        # A foreign return cannot replace the same-origin search fallback.
        self.page.goto(self.reader_url(**{"return": "https://elsewhere.test/"}), wait_until="load")
        self.page.locator("#back").click()
        self.page.wait_for_url(landing)

    def test_html_paper_wraps_and_compacts_legacy_indents(self):
        self.page.set_viewport_size({"width": 390, "height": 844})
        self.page.add_init_script('localStorage.setItem("theme", "light")')
        self.serve(("""<!doctype html><meta charset=gbk><article style='width:1200px'>
          <p id='indent' style='white-space:nowrap'>   首段<br>      换行</p>
          <p id='ordinary'>正文内   空格<kbd>   Ctrl</kbd></p>
          <p><a id='url' href='#target'>""" + "https://example.test/" + "segment" * 28 + """</a></p>
          <p id='transparent' style='color:transparent'>透明标记</p>
          <div style='background:rgba(255,255,255,.12)'><p id='translucent' style='color:white'>可读文字</p></div>
          <pre id='pre'>   """ + "unwrapped-code" * 45 + """</pre>
          <table id='target' style='width:1000px'><tr><td>表格</td></tr></table></article>""").encode('gb18030'), 'text/html')
        self.open(self.reader_url('htm', 'old-prose'))
        frame = self.page.locator('.html-frame').element_handle().content_frame()
        self.assertEqual(frame.locator('#indent').text_content(), '  首段  换行')
        self.assertEqual(frame.locator('#ordinary').text_content(), '正文内   空格   Ctrl')
        self.assertTrue(frame.locator('#pre').text_content().startswith('   '))
        self.assertEqual(frame.locator('#url').get_attribute('href'), '#target')
        self.assertEqual(frame.locator('#transparent').evaluate('n => getComputedStyle(n).color'), 'rgba(0, 0, 0, 0)')
        self.assertEqual(frame.locator('body').evaluate('n => getComputedStyle(n).fontSize'), '14px')
        self.assertIn(frame.locator('html').evaluate('n => getComputedStyle(n).webkitTextSizeAdjust'), ('none', '100%'))
        support.open_reader_panel(self.page)
        for expected in ('rgb(247, 243, 235)', 'rgb(32, 34, 36)', 'rgb(247, 243, 235)'):
            if frame.locator('body').evaluate('n => getComputedStyle(n).backgroundColor') != expected:
                self.page.locator('#theme-toggle').click()
            frame.wait_for_function('(expected) => getComputedStyle(document.body).backgroundColor === expected', arg=expected)
            self.assertTrue(frame.evaluate('document.scrollingElement.scrollWidth <= document.scrollingElement.clientWidth + 1'))
            self.assertEqual(frame.locator('#translucent').evaluate('n => getComputedStyle(n).color'),
                             'rgb(255, 255, 255)' if expected == 'rgb(32, 34, 36)' else 'rgb(17, 17, 17)')
            for selector in ('#pre', '.reader-ebook-table-scroll'):
                self.assertTrue(frame.locator(selector).evaluate('n => n.scrollWidth > n.clientWidth'))

    def test_html_table_illustration_does_not_push_article_past_the_viewport(self):
        self.page.set_viewport_size({'width': 390, 'height': 844})
        dot = ('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8'
               '/x8AAwMB/6XWbqkAAAAASUVORK5CYII=')
        self.serve(f'''<table id="story"><tr><td><img src="{dot}" width="620" height="20">
          <p id="story-text">{'正文可以完整阅读。' * 20}</p></td></tr></table>
          <table id="data" style="min-width:620px"><tr><th>栏目</th><th>数值</th></tr><tr><td>A</td><td>42</td></tr></table>''',
                   'text/html')
        self.open(self.reader_url('html'))
        document = self.page.frame_locator('.html-frame')
        story = document.locator('#story')
        self.assertTrue(story.evaluate('n => n.parentElement.scrollWidth <= n.parentElement.clientWidth + 1'))
        self.assertTrue(story.locator('img').evaluate('n => n.getBoundingClientRect().width <= 390'))
        self.assertTrue(document.locator('#data').evaluate('n => n.parentElement.scrollWidth > n.parentElement.clientWidth'))
        self.assertEqual(document.locator('#data th').count(), 2)

    def test_converted_web_keeps_literal_script_like_prose_but_drops_script_elements(self):
        path = 'documents/web/mht/' + 'b' * 64 + '/document.html'
        source = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=' + urllib.parse.quote(path, safe='')
        prose = 'var example = document.getElementById("note");'
        html = (f'<p id="note">{prose}</p><script>legacyPayload()</script>'
                '<a href="#note">查看</a><table><tr><td>正文单元格</td></tr></table>')
        self.page.route('https://voiceofml-search.hf.space/api/reader-bucket-resource**',
                        lambda route: route.fulfill(content_type='text/html', body=html))
        self.open(self.reader_url('html', url=source))
        frame = self.page.frame_locator('.html-frame')
        self.assertEqual(frame.locator('#note').inner_text(), prose)
        self.assertEqual(frame.locator('a').get_attribute('href'), '#note')
        self.assertEqual(frame.locator('td').inner_text(), '正文单元格')
        self.assertEqual(frame.locator('script').count(), 0)
        self.assertNotIn('legacyPayload', frame.locator('body').inner_text())

    def test_txt_layout_preserves_text_spaces_and_two_blank_lines_and_builds_toc(self):
        path = 'documents/text/txt/' + '2' * 64 + '/document.txt'
        source = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=' + urllib.parse.quote(path, safe='')
        line = '            这是一段完整的正文。保留行内   空格。'
        text = ('第一卷 总览\r\n' + (line + '\r\n') * 5 + ' \r\n\r\n \r\n\t\r\n' +
                '第二节 续读\r\n' + (line + '\r\n') * 8 + '第一章结束了。')
        self.page.route('https://voiceofml-search.hf.space/api/reader-bucket-resource**',
                        lambda route: route.fulfill(content_type='text/plain', body=text))
        self.serve(text)
        for url in (source, None):
            with self.subTest(url=url):
                self.open(self.reader_url('txt', **({'url': url} if url else {})))
                root = self.page.locator('.reader-text')
                self.assertEqual(root.text_content(), text)
                rendered = root.inner_text().replace('\r\n', '\n')
                self.assertIn('\n  这是一段完整的正文。保留行内   空格。', rendered)
                self.assertIn('空格。\n \n\n第二节 续读', rendered)
                if self.page.locator('#history').get_attribute('aria-expanded') != 'true':
                    support.open_reader_panel(self.page)
                self.page.get_by_role('link', name='第二节 续读', exact=True).click()
                self.assertEqual(root.locator('.reader-text-chapter-title').last.inner_text(), '第二节 续读')
                # Landing closes the drawer asynchronously; don't reopen it
                # while the same navigation still owns the close.
                self.page.locator('#history-panel').wait_for(state='hidden')
                self.search('行内   空格')
                self.page.locator('.full-search-result').first.click()
                self.assertEqual(root.locator('.full-search-highlight').inner_text(), '行内   空格')
                self.assertEqual(root.text_content(), text)

    def test_txt_layout_does_not_reformat_preformatted_lines_or_invent_headings(self):
        text = '配置说明\n  第一行\n\n第二行\n\n\n            col    value\n第一章结束了。'
        self.serve(text)
        self.open(self.reader_url('txt'))
        root = self.page.locator('.reader-text')
        self.assertEqual(root.text_content(), text)
        self.assertEqual(root.inner_text(), text)
        self.assertEqual(root.locator('.reader-text-padding, .reader-text-chapter-title').count(), 0)

    def test_markdown_infers_outline_only_from_standalone_chapter_labels(self):
        self.page.emulate_media(reduced_motion='reduce')
        self.page.route('**/static/reader/core/reader-store.js*', lambda route: route.fulfill(
            content_type='text/javascript', body='window.VoiceOfMLReaderStore={get:async()=>null,put:async()=>{},list:async()=>[]};'))
        filler = '\n\n' + ('足够长的正文,提供真实的滚动距离。\n\n' * 70)
        for heading in ('# 书名\n\n', ''):
            with self.subTest(title=bool(heading)):
                raw = (heading + '| 目录 |\n| --- |\n| [第一章 始](#101) |\n\n'
                       '第一章 始\n\n**第二章 后续**\n\n**重要说明**\n\n'
                       '**第三章 只是引文** 后面还有正文。\n\n第九章 不能把正文误判为标题。\n\n'
                       '> **第四章 引文**\n\n```text\n第五章 代码\n```\n\n' + filler +
                       '**第三章 目标**\n\n' + filler + '第四章 收尾\n\n' + filler)
                self.serve(raw)
                url = self.reader_url('md', 'outline-with-title' if heading else 'outline-without-title')
                self.open(url)
                self.page.wait_for_function("() => document.querySelector('#history').getAttribute('aria-expanded') === 'true'")
                toc = self.page.locator('#toc-list .toc-item')
                expected = (['书名'] if heading else []) + ['第一章 始', '第二章 后续', '第三章 目标', '第四章 收尾']
                self.assertEqual(toc.locator('.panel-item-main').all_text_contents(), expected)
                article = self.page.locator('.reader-markdown')
                before = article.text_content()
                self.page.locator('#toc-list').get_by_role('link', name='第三章 目标', exact=True).click()
                self.page.locator('#history-panel').wait_for(state='hidden')
                self.page.wait_for_function("() => {const p=[...document.querySelectorAll('.reader-markdown > p')].find(p=>p.textContent==='第三章 目标');return Math.abs(p.getBoundingClientRect().top-document.querySelector('#viewport').getBoundingClientRect().top)<4;}")
                self.assertEqual(article.text_content(), before)
                self.assertEqual(article.locator('a[href="#101"]').count(), 1)
                self.assertEqual(self.page.url, url)
                self.open(url)
                self.assertEqual(self.page.locator('#history').get_attribute('aria-expanded'), 'false')
                self.page.unroute('**/api/reader-content**')

    def test_markdown_does_not_infer_when_existing_structure_is_usable(self):
        cases = (
            ('# 书名\n\n## 原有小节\n\n**第一章 甲**\n\n**第二章 乙**', ['书名', '原有小节']),
            ('# 书名\n\n[第一章 甲](#one) [第二章 乙](#two)\n\n'
             '<p id="one"><b>第一章 甲</b></p>\n\n<p id="two"><b>第二章 乙</b></p>', ['书名']),
            ('开头\n\n**第一章 书中举例**\n\n' + '正文没有章节。\n\n' * 300, [])
        )
        for i, (raw, expected) in enumerate(cases):
            with self.subTest(case=i):
                self.serve(raw)
                self.open(self.reader_url('md', f'authored-outline-{i}'))
                self.assertEqual(self.page.locator('#toc-list .panel-item-main').all_text_contents(), expected)
                self.page.unroute('**/api/reader-content**')

    def test_markdown_uses_authored_heading_levels_for_chapter_navigation(self):
        self.serve('# 第一卷\n\n开头\n\n## 第一节\n\n正文\n\n```text\n# 不是章节\n```')
        self.open(self.reader_url('md'))
        support.open_reader_panel(self.page)
        self.assertEqual(self.page.locator('.toc-item').all_inner_texts(), ['第一卷', '第一节'])
        self.page.locator('.toc-item', has_text='第一节').click()
        self.assertTrue(self.page.locator('.reader-markdown h2').is_visible())

    def test_offline_html_keeps_layout_attributes_and_enforces_frame_csp(self):
        dot = ("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8"
               "/x8AAwMB/6XWbqkAAAAASUVORK5CYII=")
        document = (
            '<!doctype html><html><head><meta charset="utf-8"></head><body>'
            '<table><tr><td id="merged" colspan="2" rowspan="3" width="120" lang="zh" dir="ltr">合并</td></tr></table>'
            '<a id="remote-link" href="https://link.remote.test/x">x</a>'
            f'<img id="inline" src="{dot}"><img id="remote" src="https://img.remote.test/a.png">'
            '</body></html>'
        )
        remote = []
        self.page.on("request", lambda request: remote.append(request.url) if ".remote.test" in request.url else None)
        self.serve(document, "text/html")
        self.open(self.reader_url("html", "layout"))
        frame = self.page.locator("iframe.html-frame").element_handle().content_frame()
        cell = frame.locator("#merged")
        self.assertEqual([cell.get_attribute(name) for name in ("colspan", "rowspan", "width", "lang", "dir")],
                         ["2", "3", "120", "zh", "ltr"])
        self.assertIsNone(frame.locator("#remote-link").get_attribute("href"))
        self.assertIsNone(frame.locator("#remote").get_attribute("src"))
        self.assertTrue(frame.locator("#inline").get_attribute("src").startswith("data:image/png;"))
        # The restrictive frame CSP must be a <head> child to be enforced; a remote
        # image is then a CSP violation (Playwright still reports blocked requests).
        result = self.page.evaluate("""async () => {
          const doc = document.querySelector('iframe.html-frame').contentDocument, violations = [];
          doc.addEventListener('securitypolicyviolation', event => violations.push(event.violatedDirective));
          const image = doc.createElement('img');
          image.src = 'https://img.remote.test/late.png';
          doc.body.append(image);
          await new Promise(resolve => setTimeout(resolve, 400));
          return {policy: !!doc.head.querySelector('meta[http-equiv="Content-Security-Policy"]'), violations};
        }""")
        self.assertEqual(result, {"policy": True, "violations": ["img-src"]})
        self.assertNotIn("https://img.remote.test/a.png", remote)

    def test_offline_html_relative_same_document_links_jump_without_navigation(self):
        self.page.add_init_script('''
          window.__htmlLinkResolutions = 0;
          URL = new Proxy(URL, {construct(target, args, newTarget) {
            if (args[0]?.startsWith?.('./report.html#') || args[0]?.startsWith?.('./appendix.html#'))
              window.__htmlLinkResolutions++;
            return Reflect.construct(target, args, newTarget);
          }});
        ''')
        repeated = ''.join(f'<a class="local" href="./report.html#note-{i}">note</a>'
                           f'<a class="other" href="./appendix.html#note-{i}">other</a>'
                           for i in range(512))
        self.serve('''<!doctype html><body>
            <a id="relative" href="./report.html#methods">Methods (relative)</a>
            <a id="fragment" href="#methods">Methods</a>
            <a id="other-file" href="./appendix.html#methods">Appendix</a>
            <a id="same-name" href="../report.html#methods">Other report</a>
            <a id="other-query" href="./report.html?edition=2#methods">Other edition</a>
            <a id="space-in-path" href="./report.html #methods">Different path</a>
            <a id="control-in-fragment" href="./report.html#met&#9;hods">Invalid fragment</a>
            <p style="height: 1800px">Introduction</p>
            <h2 id="methods">Methods</h2><p style="height: 1200px">Details</p>
            ''' + repeated + '</body>', "text/html")
        self.open(self.reader_url("html", "books/report"))
        frame = self.page.locator("iframe.html-frame").element_handle().content_frame()
        # The 1,026 links to these two paths used to construct one URL each.
        self.assertEqual(self.page.evaluate('window.__htmlLinkResolutions'), 2)
        self.assertEqual(frame.locator('a.local').evaluate_all('links => links.map(a => a.getAttribute("href"))'),
                         [f'#note-{i}' for i in range(512)])
        self.assertEqual(frame.locator('a.other[href]').count(), 0)
        history_length = self.page.evaluate("history.length")
        reader_url = self.page.url
        for link_id in ("other-file", "same-name", "other-query", "space-in-path", "control-in-fragment"):
            self.assertIsNone(frame.locator(f"#{link_id}").get_attribute("href"), link_id)
        for link_id in ("relative", "fragment"):
            with self.subTest(link=link_id):
                frame.evaluate("scrollTo(0, 0)")
                link = frame.locator(f"#{link_id}")
                self.assertEqual(link.get_attribute("href"), "#methods")
                link.click()
                frame.wait_for_function("Math.abs(document.querySelector('#methods').getBoundingClientRect().top) < 2")
                self.assertEqual(frame.url, "about:srcdoc")
                self.assertEqual(self.page.url, reader_url)
                self.assertEqual(self.page.evaluate("history.length"), history_length)

    def frame_host_reader(self, overlay=False, cross_origin=False):
        # The Reader must decide by its real host whether parent messages are handled.
        reader = self.reader_url(name="framed", path="Test/docs")
        base = urllib.parse.urlsplit(reader)
        prefix = base.path[:-len("/static/reader.html")]
        folder = (self.origin + prefix + "/#/Test?folder_self=docs") if prefix else (self.origin + "/Test?folder_self=docs")
        reader += "&" + urllib.parse.urlencode({"folder_url": folder})
        folder += "&path=docs"
        home = self.origin + (prefix + "/" if prefix else "/")
        host_origin = self.origin.replace("127.0.0.1", "localhost") if cross_origin else self.origin
        self.assertNotEqual(host_origin == self.origin, cross_origin)
        if cross_origin:  # localhost -> 127.0.0.1 is otherwise a blocked local-network frame
            self.context.grant_permissions(["local-network-access"], origin=host_origin)
        frame_class = 'class="reader-overlay" ' if overlay else ""
        shell = ("<!doctype html><body><script>window.__messages=[];"
                 "addEventListener('message', event => __messages.push(event.data?.type));</script>"
                 f'<iframe {frame_class}style="width:1000px;height:700px" '
                 f"src={json.dumps(reader)}></iframe></body>")
        landing = {home, folder.split("#", 1)[0]}
        self.page.route(lambda url: url == host_origin + "/frame-host",
                        lambda route: route.fulfill(content_type="text/html", body=shell))
        self.page.route(lambda url: url in landing,
                        lambda route: route.fulfill(content_type="text/html", body="<p>search page</p>"))
        self.serve("framed reading\n" * 200)
        self.page.goto(host_origin + "/frame-host")
        frame = next(item for item in self.page.frames if item.url.startswith(self.origin + base.path))
        frame.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        return frame, home, folder

    def test_non_overlay_frame_host_navigates_reader_in_place(self):
        for cross_origin in (False, True):
            for action in ("back", "folder"):
                with self.subTest(cross_origin=cross_origin, action=action):
                    frame, home, folder = self.frame_host_reader(cross_origin=cross_origin)
                    frame.locator("#back" if action == "back" else "#reader-path").click()
                    expected = home if action == "back" else folder
                    frame.wait_for_url(expected, timeout=4000)
                    if not cross_origin:
                        sent = self.page.evaluate("__messages")
                        for message in ("voice-reader-close", "voice-reader-navigate", "voice-reader-open"):
                            self.assertNotIn(message, sent)

    def test_search_overlay_frame_still_receives_reader_messages(self):
        frame, _home, _folder = self.frame_host_reader(overlay=True)
        reader = frame.url
        frame.locator("#back").click()
        self.page.wait_for_function("() => __messages.includes('voice-reader-close')")
        self.assertEqual(frame.url, reader)

    def test_blocked_or_full_local_storage_keeps_reader_theme_and_zoom(self):
        blocked = """Object.defineProperty(window, 'localStorage', {configurable: true,
          get() { throw new DOMException('The operation is insecure.', 'SecurityError'); }});"""
        full = """Storage.prototype.setItem = function () {
          throw new DOMException('The quota has been exceeded.', 'QuotaExceededError'); };"""
        for name, script in (("blocked", blocked), ("full", full)):
            with self.subTest(storage=name):
                page = self.context.new_page()
                page.set_default_timeout(int(os.environ.get("READER_TEST_TIMEOUT_MS", "6000")))
                page.on("pageerror", lambda error: self.errors.append(f"{name}: {error}"))
                page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(
                    content_type="text/javascript", body=support.STORE_SCRIPT))
                page.route("**/api/reader-content**", lambda route: route.fulfill(
                    content_type="text/plain", body="storage reading\n" * 400))
                page.add_init_script(script)
                page.goto(self.reader_url(name="storage-" + name))
                page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'", timeout=6000)
                page.wait_for_function("() => window.__savedReaderProgress?.zoom === 100")
                page.locator("#zoom-in").click()
                self.assertEqual(page.locator("#zoom").input_value(), "110")
                self.assertEqual(page.locator("#content").evaluate(
                    "node => node.style.getPropertyValue('--reader-zoom')"), "1.1")
                page.wait_for_function("() => window.__savedReaderProgress?.zoom === 110")
                theme = page.locator("html").get_attribute("data-theme")
                support.open_reader_panel(page)
                page.locator("#theme-toggle").click()
                self.assertNotEqual(page.locator("html").get_attribute("data-theme"), theme)
                self.assertEqual(page.locator("#theme-toggle").get_attribute("aria-pressed"),
                                 str(theme == "dark").lower())
                page.close()

    def open_security_chapter(self, chapter):
        prefix = "chapters/ebook/epub/" + "e" * 64 + "/" + "f" * 16 + "/"
        manifest_path = prefix + "chapter-manifest.json"
        chapter_path = "chapters/chapter-0001.xhtml"
        manifest = {"version": 1, "kind": "epub-chapters", "chapters": [
            {"index": 1, "path": chapter_path, "bytes": len(chapter),
             "sha256": hashlib.sha256(chapter).hexdigest()}]}

        def bucket(route):
            path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)["path"][0]
            if path == manifest_path:
                route.fulfill(json=manifest)
            elif path == prefix + chapter_path:
                route.fulfill(content_type="application/xhtml+xml", body=chapter)
            else:
                route.fulfill(status=404)

        self.page.route("**/api/reader-bucket-resource?**", bucket)
        source = ("https://voiceofml-search.hf.space/api/reader-bucket-resource?" +
                  urllib.parse.urlencode({"path": manifest_path}))
        self.open(self.reader_url("epub-chapters", url=source))
        return self.page.locator(".reader-epub-chapter")

    def test_chapter_svg_xlink_control_whitespace_cannot_execute_in_reader_context(self):
        chapter = b'''<html xmlns="http://www.w3.org/1999/xhtml"><body>
          <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
            <a id="probe" xlink:href="java&#x09;script:window.__readerSecurityMarker=17;void(0)">
              <text x="10" y="20">safe label</text>
            </a>
          </svg>
        </body></html>'''
        chapter_root = self.open_security_chapter(chapter)
        probe = chapter_root.locator("#probe")
        self.assertEqual(probe.get_attribute("xlink:href"), None)
        probe.click()
        self.assertFalse(self.page.evaluate("() => window.__readerSecurityMarker === 17"))

    def test_chapter_prefixed_xlink_and_smil_href_cannot_execute_in_reader_context(self):
        chapter = b'''<html xmlns="http://www.w3.org/1999/xhtml"><body>
          <svg xmlns="http://www.w3.org/2000/svg" xmlns:x="http://www.w3.org/1999/xlink" width="240" height="70">
            <a id="probe" x:href="javascript:window.__readerSecurityMarker=23;void(0)">
              <text x="10" y="20">prefixed label</text>
            </a>
            <a id="animated">
              <set attributeName="href" to="javascript:window.__readerSecurityMarker=29;void(0)"/>
              <text x="10" y="50">animated label</text>
            </a>
          </svg>
        </body></html>'''
        chapter_root = self.open_security_chapter(chapter)
        probe = chapter_root.locator("#probe")
        self.assertIsNone(probe.evaluate("n => n.getAttributeNS('http://www.w3.org/1999/xlink', 'href')"))
        self.assertEqual(chapter_root.locator("#animated set").count(), 0)
        probe.click()
        chapter_root.locator("#animated").click()
        self.page.wait_for_timeout(200)
        self.assertIsNone(self.page.evaluate("() => window.__readerSecurityMarker ?? null"))

    def test_epub_html_and_svg_references_cannot_load_remote_resources(self):
        vectors = ('<p style="background:image-set(\'https://img.remote.test/a.png\' 1x)">a</p>'
                   '<p style="background:\\75rl(https://img.remote.test/b.png)">b</p>'
                   '<table background="https://img.remote.test/c.png"><tr>'
                   '<td id="cell" background="//img.remote.test/d.png">cell</td></tr></table>'
                   '<input type="image" src="https://img.remote.test/e.png"/>'
                   '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="20" height="20">'
                   '<defs><circle id="dot" r="2"/><filter id="ff"><feImage href="https://img.remote.test/f.png"/>'
                   '<feImage xlink:href="https://img.remote.test/g.png"/></filter></defs>'
                   '<rect width="10" height="10" filter="url(#ff)"/><use id="local-use" href="#dot"/>'
                   '<use href="https://img.remote.test/h.svg#a"/></svg><p id="kept">kept text</p>')
        chapter = ('<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Refs</title></head><body>'
                   + vectors + '</body></html>')
        remote = []
        self.page.on("request", lambda request: remote.append(request.url) if ".remote.test" in request.url else None)
        chapter_root = self.open_security_chapter(chapter.encode())
        chapter_root.locator("#kept").wait_for(state="attached")
        self.page.wait_for_timeout(400)
        self.assertEqual(remote, [])
        self.assertEqual(chapter_root.locator("#local-use").get_attribute("href"), "#dot")

    def expose_html_contrast(self):
        self.page.add_init_script('localStorage.setItem("theme", "light")')
        def instrument(route):
            response = route.fetch()
            script = response.text()
            self.assertIn('readerContext.repairHtmlContrast(frame);', script)
            route.fulfill(response=response, body=script.replace('readerContext.repairHtmlContrast(frame);', ''))
        self.page.route('**/static/reader/formats/reader-html-format.mjs*', instrument)
        def expose(route):
            response = route.fetch()
            route.fulfill(response=response, body=response.text() + '''
              window.__repairContrast = () => repairHtmlContrast(htmlFrame);
            ''')
        self.page.route('**/static/reader.js*', expose)

    def test_html_contrast_reuses_transparent_ancestors_and_refreshes_between_passes(self):
        self.expose_html_contrast()
        self.serve('<main style="color:#111">' + '<div>' * 24 +
                   '<span>Readable text</span>' * 1200 + '</div>' * 24 + '</main>', 'text/html')
        self.open(self.reader_url('html'))
        result = self.page.evaluate('''() => {
          const frame = document.querySelector('.html-frame'), win = frame.contentWindow;
          const native = win.getComputedStyle.bind(win);
          let calls = 0;
          win.getComputedStyle = (...args) => { calls++; return native(...args); };
          __repairContrast();
          const firstCalls = calls;
          const spans = [...frame.contentDocument.querySelectorAll('span')];
          const untouched = spans.every(node => !node.style.color);
          frame.contentDocument.querySelector('main').style.color = '#fff';
          __repairContrast();
          win.getComputedStyle = native;
          return {firstCalls, untouched, repaired: spans.every(node =>
            node.style.color === 'rgb(17, 17, 17)' && node.style.getPropertyPriority('color') === 'important')};
        }''')
        self.assertLessEqual(result['firstCalls'], 1230)
        self.assertTrue(result['untouched'])
        self.assertTrue(result['repaired'])

    def test_html_contrast_keeps_sequential_currentcolor_inheritance_and_alpha_rules(self):
        self.expose_html_contrast()
        self.serve('''<div id="changing" style="color:#777;background:currentColor">
          <span id="first" style="color:white">First</span> Parent
          <span id="last" style="color:white">Last</span></div>
          <div id="inherit" style="color:white">Parent<span id="child">Child</span></div>
          <div style="background:#111"><span id="dark" style="color:#111">Dark</span></div>
          <div style="background:rgba(0,0,0,.1)"><span id="ignored" style="color:white">Ignored</span></div>
          <div style="background:rgba(0,0,0,.11)"><span id="accepted" style="color:#111">Accepted</span></div>
          <a id="link" style="color:#0645ad">Link</a>''', 'text/html')
        self.open(self.reader_url('html'))
        result = self.page.evaluate('''() => {
          __repairContrast();
          const doc = document.querySelector('.html-frame').contentDocument;
          return Object.fromEntries(['changing','first','last','inherit','child','dark','ignored','accepted','link']
            .map(id => [id, [doc.getElementById(id).style.color,
                            doc.getElementById(id).style.getPropertyPriority('color')]]));
        }''')
        self.assertEqual(result, {
            'changing': ['rgb(245, 245, 245)', 'important'], 'first': ['white', ''],
            'last': ['rgb(17, 17, 17)', 'important'], 'inherit': ['rgb(17, 17, 17)', 'important'],
            'child': ['', ''], 'dark': ['rgb(245, 245, 245)', 'important'],
            'ignored': ['rgb(17, 17, 17)', 'important'], 'accepted': ['rgb(17, 17, 17)', ''],
            'link': ['rgb(6, 69, 173)', ''],
        })

    def test_html_preserves_css_prose_and_tracks_progress_and_headings(self):
        html = "<p>Examples: url(icon.png) and @import theme.css;</p>" + "".join(
            f"<h1 id='chapter-{i}'>Chapter {i}</h1><p style='height:1100px'>text</p>" for i in range(4))
        self.serve(html, "text/html")
        self.open(self.reader_url("html"))
        frame = self.page.frame_locator(".html-frame")
        self.assertIn("url(icon.png) and @import theme.css;", frame.locator("body").inner_text())
        self.assertTrue(self.page.locator(".html-frame").get_attribute("title"))
        frame.locator("#chapter-2").evaluate("node => node.scrollIntoView()")
        support.open_reader_panel(self.page)
        self.page.wait_for_function("() => Number(document.querySelector('.reader-progress-range').value) > 40")
        self.page.wait_for_function("() => document.querySelectorAll('.toc-item')[2].classList.contains('is-current')")
        self.page.locator(".reader-chapter-next").click()
        self.page.wait_for_function("() => document.querySelectorAll('.toc-item')[3].classList.contains('is-current')")

    def test_plain_html_skips_forum_dom_probe_but_keeps_sanitization(self):
        self.page.add_init_script('''(() => {
          const parse = DOMParser.prototype.parseFromString;
          window.__parsedHtml = [];
          DOMParser.prototype.parseFromString = function(text, mime) {
            if (mime === 'text/html' && String(text).includes('ordinary-document-marker'))
              window.__parsedHtml.push(new Error().stack);
            return parse.call(this,text,mime);
          };
        })()''')
        self.serve('<h1>ordinary-document-marker</h1><p>Ordinary document</p><script>/* removed */</script>', 'text/html')
        self.open(self.reader_url('html', 'plain-html'))
        body = self.page.frame_locator('.html-frame')
        self.assertEqual(body.locator('h1').inner_text(), 'ordinary-document-marker')
        self.assertEqual(body.locator('p').inner_text(), 'Ordinary document')
        self.assertEqual(body.locator('script').count(), 0)
        # DOMPurify may also call DOMParser with the original document. Check
        # the probe's call site instead of expecting a particular wrapper.
        self.assertFalse(self.page.evaluate("()=>window.__parsedHtml.some(stack=>stack?.includes('buildDiscourseDocument'))"))

    def test_word_signature_indent_fits_mobile_without_changing_desktop(self):
        self.page.set_viewport_size({'width':390,'height':844})
        self.serve('<p class="MsoNormal" style="text-indent:24pt">普通段落</p>'
                   '<p id="date" class="MsoNormal" style="text-indent:288pt">2010年7月4日</p>'
                   '<table><tr><td><p class="MsoNormal" style="text-indent:288pt">数据</p></td></tr></table>', 'text/html')
        self.open(self.reader_url('html', name='word-signature'))
        frame = self.page.frame_locator('.html-frame')
        date = frame.locator('#date')
        self.assertEqual(frame.locator('[data-reader-word-inset]').count(),1)
        self.assertTrue(date.evaluate('e => e.scrollWidth <= e.clientWidth + 1'))
        self.assertEqual(date.inner_text(),'2010年7月4日')
        self.page.set_viewport_size({'width':1200,'height':850})
        self.assertEqual(date.evaluate('e => getComputedStyle(e).textIndent'),'384px')

    def test_html_inactive_anchors_are_not_painted_as_links(self):
        html = ('<!doctype html><meta charset="utf-8"><p><a id="kept">无链接词</a> '
                '<a href="#kept">真实跳转</a></p>')
        self.serve(html, 'text/html')
        self.open(self.reader_url('html', name='inert-anchors'))
        p = self.page.frame_locator('.html-frame').locator('p')
        for forced in ('none', 'active'):
            with self.subTest(forced=forced):
                self.page.emulate_media(forced_colors=forced)
                colors = p.evaluate('p => [p, ...p.querySelectorAll("a")].map(n => getComputedStyle(n).color)')
                self.assertEqual(colors[0], colors[1])
                self.assertNotEqual(colors[0], colors[2])
        self.assertEqual(p.locator('#kept').inner_text(), '无链接词')
        self.assertEqual(p.locator('a[href]').get_attribute('href'), '#kept')

    def test_phpwind_reflows_post_shells_without_changing_content_tables(self):
        def shell(author, body):
            return (f'<div><table width="98%"><tr><td width="20%">{author}</td><td width="80%">'
                    '<table><tr><td><a>查看作者资料</a><a>发送短消息</a><a>发送邮件</a>'
                    '<a>推荐此帖</a><a>引用回复这个帖子</a><br><br>'
                    f'<span class="tpc_content">{body}</span></td></tr><tr><td>发表时间</td></tr>'
                    '<tr><td>签名</td></tr></table></td></tr></table></div>')

        posts = (shell('第一位作者', '<p id="posted">首帖</p><table><caption>数据</caption>'
                       '<tr><th>年份</th><td>2026</td></tr></table>') +
                 shell('第二位作者', '<p>次帖<a href="#posted">跳回首帖</a></p><pre>  保留缩进</pre>'))
        self.page.set_viewport_size({'width': 390, 'height': 844})
        malformed = ''.join(posts.rsplit('<tr><td>签名</td></tr>', 1))
        for name, powered, body, layout in (
            ('phpwind', ' - powered by phpwind.net', posts, True),
            ('ordinary', '', posts, False),
            ('malformed-thread', ' - powered by phpwind.net', malformed, False),
        ):
            with self.subTest(template=name):
                self.serve(f'<!doctype html><meta charset="utf-8"><title>讨论{powered}</title>{body}', 'text/html')
                self.open(self.reader_url('html', name=name))
                frame = self.page.frame_locator('.html-frame')
                self.assertEqual(frame.locator('[data-reader-phpwind="shell"]').count(), 2 if layout else 0)
                if not layout:
                    self.assertEqual(frame.locator('[data-reader-phpwind]').count(), 0)
                self.assertEqual(frame.locator('.tpc_content').count(), 2)
                self.assertEqual(frame.locator('.tpc_content table').evaluate('t => getComputedStyle(t).display'), 'table')
                self.assertEqual(frame.locator('caption').inner_text(), '数据')
                self.assertEqual(frame.locator('pre').text_content(), '  保留缩进')
                self.assertEqual(frame.locator('a[href="#posted"]').count(), 1)
                self.assertEqual(frame.locator('#posted').inner_text(), '首帖')
                self.assertEqual(frame.get_by_text('发送短消息', exact=True).first.is_visible(), not layout)
                if layout:
                    metrics = frame.locator('.tpc_content').evaluate_all('xs => xs.map(x => x.getBoundingClientRect().width)')
                    self.assertGreaterEqual(min(metrics), 310)

    def allow_clean_reading_fixture(self, html, sha):
        # Only this test's synthetic bytes stand in for the reviewed real asset.
        def expose(route):
            res = route.fetch()
            source = res.text()
            self.assertEqual(source.count(sha), 1)
            route.fulfill(response=res, body=source.replace(sha, hashlib.sha256(html.encode('utf-8')).hexdigest()))
        self.page.route('**/formats/reader-html-format.mjs*', expose)

    def test_clean_phpwind_posts_keep_collapsed_text_and_open_anchor_targets(self):
        def shell(title, contents, anchor):
            return ('<div><table width="960"><tr><td>作者栏</td><td><table>'
                    f'<tr><td><a name="{anchor}"></a><span class="tpc_title">{title}</span>'
                    f'<span class="tpc_content">{contents}</span></td></tr>'
                    '<tr><td>发表时间</td></tr><tr><td>签名栏</td></tr></table></td></tr></table></div>')
        posts = shell('讨论标题','<p>完整首帖 <a href="#reply">定位回复</a></p>','first') + shell(
            '', '一篇独立回复标题<br><p id="answer">完整回复</p><pre>  保留缩进</pre>', 'reply')
        self.page.set_viewport_size({'width': 390, 'height': 844})
        html = ('<!doctype html><meta charset="utf-8"><title>讨论 - powered by phpwind.net</title>'
                '<nav>控制面板</nav>' + posts)
        self.allow_clean_reading_fixture(html, '9ddff06d033c44900801a44937334194a4500103816aafda52b837f9f71765d9')
        self.serve(html, 'text/html')
        self.open(self.reader_url('html', name='clean-discussion', view='reading'))
        frame = self.page.frame_locator('.html-frame')
        self.assertEqual(frame.locator('h1').inner_text(), '讨论标题')
        self.assertEqual(frame.locator('nav').count(), 0)
        self.assertEqual(frame.locator('.tpc_content').count(), 2)
        summary = frame.locator('summary')
        reply = frame.locator('details')
        self.assertEqual(summary.inner_text(), '1 楼 · 一篇独立回复标题')
        self.assertFalse(frame.locator('#answer').is_visible())
        summary.press('Space')
        self.assertTrue(frame.locator('#answer').is_visible())
        summary.press('Enter')
        self.assertFalse(frame.locator('#answer').is_visible())
        frame.get_by_text('定位回复', exact=True).click()
        self.assertTrue(reply.evaluate('d => d.open'))
        self.assertEqual(frame.locator('pre').text_content(), '  保留缩进')
        summary.press('Enter')
        self.assertFalse(frame.locator('#answer').is_visible())
        self.search('完整回复')
        self.page.locator('.full-search-result').first.click()
        self.assertTrue(frame.locator('#answer').is_visible())
        self.wait_saved_replies([1])
        # A second tab in the same context exercises a fresh Reader with
        # the persisted position, rather than reusing the active frame.
        url = self.page.url
        original = self.page
        self.page = self.context.new_page()
        try:
            self.page.set_default_timeout(int(os.environ.get('READER_TEST_TIMEOUT_MS', '8000')))
            self.serve(html, 'text/html')
            self.allow_clean_reading_fixture(html, '9ddff06d033c44900801a44937334194a4500103816aafda52b837f9f71765d9')
            self.open(url)
            reopened = self.page.frame_locator('.html-frame')
            reopened.locator('#answer').wait_for(state='visible')
            reopened.locator('summary').press('Enter')
            self.wait_saved_replies([])
        finally:
            self.page.close()
            self.page = original

    def test_reviewed_short_archive_reflows_only_its_single_column_tables(self):
        html = ('<!doctype html><meta charset="utf-8"><h2>归档标题</h2>'
                '<div data-reader-table-scroll><table width="530"><tr><td><p>来源与日期</p></td></tr>'
                '</table></div><div data-reader-table-scroll><table width="530"><tr><td>'
                '<a href="#kept">原有链接</a><p id="kept">备份出处</p></td></tr></table></div>')
        html += ' ' * (2215 - len(html.encode('utf-8')))
        sha = '394cd4d8287b45c3a6d77c418af749b02654241a18d9977f5d34ef2930764b39'
        self.allow_clean_reading_fixture(html, sha)
        self.page.set_viewport_size({'width': 390, 'height': 844})
        for i, payload in enumerate((html, html.replace('归档标题', '归档副题'))):
            with self.subTest(archive=i):
                self.assertEqual(len(payload.encode('utf-8')), 2215)
                self.serve(payload, 'text/html')
                self.open(self.reader_url('html', name=f'reviewed-layout-{i}'))
                frame = self.page.frame_locator('.html-frame')
                tables = frame.locator('div[data-reader-table-scroll] table')
                self.assertEqual(tables.count(), 2)
                widths = tables.evaluate_all('ts => ts.map(t => t.getBoundingClientRect().width)')
                if i == 0:
                    self.assertTrue(all(280 < width < 390 for width in widths), widths)
                    self.page.set_viewport_size({'width': 1280, 'height': 900})
                    self.assertEqual(tables.evaluate_all('ts => ts.map(t => t.getBoundingClientRect().width)'), [530, 530])
                    self.page.set_viewport_size({'width': 390, 'height': 844})
                else:
                    self.assertEqual(widths, [530, 530])
                self.assertEqual(frame.locator('#kept').text_content(), '备份出处')
                self.assertEqual(frame.locator('a[href="#kept"]').count(), 1)
        self.assertEqual(self.page.locator('#zoom').input_value(), '100')

    def test_exact_tieba_reading_keeps_posts_media_and_archive(self):
        pixel = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jFuoAAAAASUVORK5CYII='
        posts = []
        for i in range(18):
            images = f'<img class="BDE_Image" src="{pixel}">' * (2 if i < 11 else 1)
            gaps = '<img class="BDE_Smiley">' * (2 if i < 2 else 1)
            reply = ('<ul><li class="j_lzl_s_p"><div class="lzl_cnt"><a class="at j_user_card">副作者</a>'
                     '<span class="lzl_content_main">作者回复<br></span><span class="lzl_time">回复时间</span></div></li></ul>') if i < 5 else ''
            posts.append(f'<div class="l_post_bright j_l_post"><a class="p_author_name">主作者{i}</a>'
                         f'<div class="d_post_content_main"><div class="p_content"><div class="d_post_content j_d_post_content" '
                         f'id="post_content_{i}">正文{i}<br>{images}{gaps}</div></div></div>'
                         '<div class="post-tail-wrap"><span class="tail-info">'
                         f'{i+1}楼</span><span class="tail-info">2020-01-01 12:00</span></div>{reply}</div>')
        ad = ('<div class="l_post_bright n5c3d35bb7"><a class="p_author_name">百度传课</a>'
              '<div class="p_content_nameplate"><div class="d_post_content">推广位</div></div></div>')
        html = ('<!doctype html><meta charset="utf-8"><div>旧站脚本残留</div><h3 class="core_title_txt">存档标题</h3>'
                '<div id="j_p_postlist">' + ad + ''.join(posts) + '</div>')
        self.page.set_viewport_size({'width': 390, 'height': 844})
        original = '41114af695f939fe98eaa18e09db29cb61fc55eb816e0e688515781a903c55be'
        def pin(route):
            response = route.fetch()
            script = response.text()
            self.assertEqual(script.count(original), 1)
            self.assertEqual(script.count('10_296_371'), 1)
            route.fulfill(response=response, body=script.replace(original, hashlib.sha256(html.encode()).hexdigest())
                          .replace('10_296_371', str(len(html.encode()))))
        self.page.route('**/formats/reader-html-format.mjs*', pin)
        self.serve(html, 'text/html')
        url = self.reader_url('html', name='reviewed-tieba')
        self.open(url)
        frame = self.page.frame_locator('.html-frame')
        clean = frame.locator('article.reader-tieba-view')
        self.assertEqual(clean.locator('.reader-tieba-post').count(), 18)
        self.assertEqual(clean.locator('.reader-tieba-reply').count(), 5)
        self.assertEqual(clean.locator('img[src]').count(), 29)
        self.assertEqual(clean.locator('.reader-tieba-missing-emoticon').count(), 20)
        self.assertEqual(clean.locator('.j_d_post_content').evaluate_all('nodes => nodes.map(n => n.id)'),
                         [f'post_content_{i}' for i in range(18)])
        self.assertEqual(frame.get_by_text('旧站脚本残留', exact=True).count(), 0)
        self.assertTrue(frame.locator('#post_content_17').text_content().startswith('正文17'))
        self.assertEqual(frame.locator('body').evaluate('n=>n.ownerDocument.documentElement.scrollWidth'),
                         frame.locator('body').evaluate('n=>n.ownerDocument.documentElement.clientWidth'))
        panel = self.page.locator('#history-panel')
        if not panel.evaluate('p => p.classList.contains("is-open")'):
            self.page.locator('#history').click()
        archive = self.page.get_by_role('link', name='存档视图', exact=True)
        archive.wait_for(state='visible')
        self.assertEqual(urllib.parse.parse_qs(urllib.parse.urlsplit(archive.get_attribute('href')).query)['view'], ['archive'])
        archive.press('Enter')
        frame.get_by_text('旧站脚本残留', exact=True).wait_for()
        self.assertEqual(clean.count(), 0)
        self.page.go_back(wait_until='commit')
        clean.wait_for()
        self.page.go_forward(wait_until='commit')
        frame.get_by_text('旧站脚本残留', exact=True).wait_for()
        if not panel.evaluate('p => p.classList.contains("is-open")'):
            self.page.locator('#history').click()
        posts_link = self.page.get_by_role('link', name='纯帖子', exact=True)
        posts_link.wait_for(state='visible')
        posts_link.press('Enter')
        clean.wait_for()
        self.assertEqual(urllib.parse.parse_qs(urllib.parse.urlsplit(self.page.url).query).get('view'), None)
        self.serve(html.replace('旧站脚本残留', '旧站模板残留'), 'text/html')
        self.open(self.reader_url('html', name='unreviewed-tieba'))
        self.assertEqual(clean.count(), 0)
        self.assertEqual(frame.get_by_text('旧站模板残留', exact=True).count(), 1)
        self.assertEqual(self.page.locator('#history-panel > header a.text-action').count(), 0)

    def test_reviewed_phpwind_stamp_requires_robust_extraction_and_exact_bytes(self):
        def post(title, text, tail=''):
            return ('<table><tr><td>作者</td><td><table><tr><td>'
                    f'<span class="tpc_title">{title}</span><span class="tpc_content">{text}</span>'
                    f'</td></tr><tr><td>时间</td></tr><tr><td>签名</td></tr>{tail}</table></td></tr></table>')

        prefix = ('<!doctype html><meta charset="utf-8"><title>题目 - powered by phpwind.net</title>'
                  '<article class="reader-clean-web" data-reader-reviewed-thread="forged">原文</article>')
        digest = '9ddff06d033c44900801a44937334194a4500103816aafda52b837f9f71765d9'
        url = self.reader_url('html', name='reviewed-thread-stamp', view='reading')
        valid = prefix + post('题目', '首帖') + post('', '回复')
        cases = ((prefix + post('', '首帖') + post('', '回复'), False),
                 (prefix + post('题目', '首帖') + post('', '回复', '<tr><td>其他</td></tr>'), False),
                 (valid, True), (valid.replace('forged', 'forgeD'), False))
        for index, (html, extracted) in enumerate(cases):
            with self.subTest(case=index):
                if index < 3:
                    self.page.unroute('**/formats/reader-html-format.mjs*')
                    self.allow_clean_reading_fixture(html, digest)
                self.serve(html, 'text/html')
                self.open(url)
                frame = self.page.frame_locator('.html-frame')
                marker = frame.locator('article[data-reader-reviewed-thread]')
                self.assertEqual(marker.count(), int(extracted))
                self.assertEqual(frame.locator('.tpc_content').all_text_contents(), ['首帖', '回复'])
                if extracted:
                    self.assertEqual(marker.get_attribute('data-reader-reviewed-thread'), hashlib.sha256(html.encode()).hexdigest())
                else:
                    self.assertEqual(frame.get_by_text('原文', exact=True).count(), 1)

    def wait_saved_replies(self, expected):
        for _ in range(60):
            found = self.page.evaluate('''async () => {
              const source = new URL(location.href).searchParams.get('url');
              return (await VoiceOfMLReaderStore.get(source))?.htmlOpenReplies ?? null;
            }''')
            if found == expected:
                return
            self.page.wait_for_timeout(50)
        self.assertEqual(found, expected)

    def test_clean_legacy_article_keeps_content_and_falls_back_for_unknown_appendix(self):
        photo = '<img alt="照片" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">'
        body = ('<div id="ArticleContent"><p>完整正文  <a href="#note">脚注</a></p>'
                '<table><tr><td>' + photo + '</td></tr><tr><td>照片题注</td></tr></table>'
                '<table id="data"><caption>数据</caption><tr><th>列</th><td>结果</td></tr></table>'
                '<p id="note">原脚注</p></div>')
        html = ('<!doctype html><meta charset="utf-8"><nav>站点登录</nav>'
                '<table class="center_tdbgall" width="960"><tr><td class="main_tdbgall">'
                '<table class="tdbg_top_left_right" width="715">'
                '<tr><td id="txt_title" class="main_ArticleTitle">主文标题</td></tr>'
                '<tr><td class="Article_tdbgall">作者:<a id="txt_info">作者名</a> 文章发于:来源 点击数: 更新时间:2010-12-1</td></tr>'
                '<tr><td id="fontzoom" class="main_tdbg_760">' + body + '</td></tr>{tail}</table></td></tr></table>')
        self.page.set_viewport_size({'width':390,'height':844})
        self.allow_clean_reading_fixture(html.format(tail=''), 'c5c214029407e94ccb2ecb4047285077ac01e5b39ef2ad65ef724724136e4749')
        for name, tail, mode in (('article', '', 'reading'), ('default', '', 'archive'),
                                 ('appendix','<tr><td><p>不能丢掉的附录</p></td></tr>', 'reading')):
            with self.subTest(kind=name):
                self.serve(html.format(tail=tail), 'text/html')
                self.open(self.reader_url('html', name=name, view=mode))
                frame = self.page.frame_locator('.html-frame')
                clean = mode == 'reading' and not tail
                self.assertEqual(frame.locator('.reader-clean-web').count(),int(clean))
                toggle = self.page.locator('#history-panel > header a.text-action')
                if tail:
                    self.assertEqual(toggle.filter(has_text='纯阅读').count(), 0)
                    self.assertEqual(toggle.filter(has_text='存档视图').count(), 0)
                else:
                    label = '存档视图' if clean else '纯阅读'
                    href = toggle.filter(has_text=label).get_attribute('href')
                    self.assertIsNotNone(href)
                    query = urllib.parse.parse_qs(urllib.parse.urlsplit(href).query)
                    self.assertEqual(query.get('view'), None if clean else ['reading'])
                if not clean:
                    self.assertEqual(frame.locator('nav').count(),1)
                    if tail:
                        self.assertEqual(frame.get_by_text('不能丢掉的附录').count(),1)
                    continue
                self.assertEqual(frame.locator('h1').inner_text(),'主文标题')
                self.assertEqual(frame.locator('nav').count(),0)
                self.assertEqual(frame.locator('figcaption').inner_text(),'照片题注')
                self.assertEqual(frame.locator('#data caption').inner_text(),'数据')
                self.assertEqual(frame.locator('a[href="#note"]').count(),1)
                self.assertTrue(frame.locator('#ArticleContent p').first.evaluate('p => p.offsetWidth <= p.ownerDocument.documentElement.clientWidth'))

    def test_legacy_word_article_reflows_without_flattening_data_tables(self):
        article = ('<div class="Section1"><p class="MsoNormal" style="white-space:nowrap">' + '这段文字必须在屏幕内换行。' * 20 +
                   '<br>原始换行</p><table id="data"><caption>数据</caption><tr><td><pre>' + '1234567890' * 30 +
                   '</pre></td></tr></table></div>')
        html = ('<!doctype html><meta charset="utf-8"><table class="center_tdbgall" width="960"><tr>'
                '<td class="main_tdbgall" width="720"><table class="tdbg_top_left_right" width="715">'
                f'<tr><td class="main_tdbg_760">{article}</td></tr></table></td><td>侧栏</td></tr></table>')
        self.page.set_viewport_size({'width':390,'height':844})
        self.serve(html, 'text/html')
        self.open(self.reader_url('html', name='legacy-article'))
        frame = self.page.frame_locator('.html-frame')
        p = frame.locator('p.MsoNormal')
        self.assertTrue(p.evaluate('p => p.getBoundingClientRect().width <= p.ownerDocument.documentElement.clientWidth'))
        self.assertTrue(p.evaluate('p => p.scrollWidth <= p.clientWidth + 1'))
        self.assertEqual(p.locator('br').count(),1)
        self.assertTrue(p.inner_text().endswith('原始换行'))
        self.assertEqual(frame.locator('#data').evaluate('n => getComputedStyle(n).display'), 'table')
        self.assertEqual(frame.locator('#data caption').inner_text(),'数据')
        self.assertTrue(frame.locator('#data').evaluate('t => t.parentElement.scrollWidth > t.parentElement.clientWidth'))
        nested = html.replace(article, '<table id="intervening"><tr><td>' + article + '</td></tr></table>')
        self.serve(nested, 'text/html')
        self.open(self.reader_url('html', name='legacy-intervening-table'))
        self.assertEqual(frame.locator('[data-reader-legacy-article]').count(), 0)
        self.assertEqual(frame.locator('#intervening').evaluate('t => getComputedStyle(t).display'), 'table')

    def test_discourse_probe_keeps_encoded_and_quirks_mode_class_names(self):
        for name, prefix, cls, extracted in [('decimal', '<!doctype html>', 'post&#45;stream', True),
                                             ('hex', '<!doctype html>', 'post&#x2D;stream', True),
                                             ('quirks', '', 'POST-STREAM', True),
                                             ('standards', '<!doctype html>', 'POST-STREAM', False)]:
            with self.subTest(kind=name):
                document = prefix + '<meta charset="gbk">' + f'<header>Forum chrome</header><div class="{cls}">' + (
                    '<article class="topic-post"><div class="cooked">论坛正文<script>/* removed */</script></div></article></div>')
                self.serve(document.encode('gb18030'), 'text/html')
                self.open(self.reader_url('html', name='forum-' + name))
                frame = self.page.frame_locator('.html-frame')
                self.assertEqual(frame.locator('.reader-forum-post' if extracted else '.cooked').inner_text(), '论坛正文')
                self.assertEqual(frame.locator('header').count(), 0 if extracted else 1)
                self.assertEqual(frame.locator('script').count(), 0)

    def test_discourse_html_extracts_posts_without_forum_shell(self):
        html = """<!doctype html><html><head><title>论坛标题</title></head><body>
        <header class="d-header">论坛顶部</header>
        <div id="topic-title"><a class="fancy-title">论坛标题</a></div>
        <div class="topic-timeline">时间线</div>
        <div class="post-stream">
          <article class="topic-post"><div class="cooked"><p>第一段正文</p><s>删除的文字</s></div></article>
          <article class="topic-post"><div class="cooked"><p>第二段正文</p></div></article>
        </div>
        <div class="suggested-topics">推荐主题</div>
        </body></html>"""
        self.serve(html, "text/html")
        self.open(self.reader_url("html", name="forum"))
        frame = self.page.frame_locator(".html-frame")
        self.assertEqual(frame.locator(".reader-forum-post").count(), 2)
        self.assertIn("第一段正文", frame.locator("body").inner_text())
        self.assertIn("第二段正文", frame.locator("body").inner_text())
        self.assertEqual(frame.locator("s").inner_text(), "删除的文字")
        self.assertEqual(frame.locator(".d-header, .topic-timeline, .suggested-topics").count(), 0)
        support.open_reader_panel(self.page)
        with self.page.expect_navigation(wait_until='commit'):
            self.page.get_by_role('link', name='存档视图').click()
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        self.assertEqual(frame.locator('.topic-post .cooked').count(), 2)
        self.assertEqual(frame.locator('.suggested-topics').inner_text(), '推荐主题')
        support.open_reader_panel(self.page)
        with self.page.expect_navigation(wait_until='commit'):
            self.page.get_by_role('link', name='纯帖子').click()
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        self.assertEqual(frame.locator('.reader-forum-post').count(), 2)
        self.assertEqual(frame.locator('.suggested-topics').count(), 0)

    def test_html_keyboard_turns_use_iframe_and_reduced_motion(self):
        self.context.clear_permissions()
        self.page.emulate_media(reduced_motion="reduce")
        self.serve("<p style='height:8000px'>Long document</p>", "text/html")
        self.open(self.reader_url("html"))
        self.page.locator(".html-frame").evaluate("""frame => {
          const original = frame.contentWindow.scrollBy.bind(frame.contentWindow);
          frame.contentWindow.scrollBy = options => { window.__turn = options; original(options); };
        }""")
        self.page.evaluate("document.body.dispatchEvent(new KeyboardEvent('keydown', {key:'PageDown', bubbles:true, cancelable:true}))")
        self.assertEqual(self.page.evaluate("window.__turn.behavior"), "instant")
        self.assertGreater(self.page.locator(".html-frame").evaluate("frame => frame.contentWindow.scrollY"), 100)
        self.page.frame_locator(".html-frame").locator("body").evaluate("node => node.dispatchEvent(new KeyboardEvent('keydown', {key:'PageUp', bubbles:true, cancelable:true}))")
        self.assertEqual(self.page.locator(".html-frame").evaluate("frame => frame.contentWindow.scrollY"), 0)

    def test_bookmark_dialog_focus_inert_and_invoker_restoration(self):
        self.serve("A document\n" * 200)
        self.open(self.reader_url())
        self.page.evaluate("document.querySelector('#download').inert = true")
        self.page.locator("#history").click()
        invoker = self.page.locator(".reader-progress-bookmark")
        invoker.click()
        self.assertEqual(self.page.locator("#bookmark-popover").get_attribute("aria-labelledby"), "bookmark-prompt")
        self.assertTrue(self.page.locator("#history-panel").evaluate("node => node.inert"))
        self.page.keyboard.press("Shift+Tab")
        self.assertEqual(self.page.evaluate("document.activeElement.id"), "bookmark-cancel")
        self.page.keyboard.press("Tab")
        self.assertEqual(self.page.evaluate("document.activeElement.id"), "bookmark-label")
        self.page.keyboard.press("Tab")
        self.assertEqual(self.page.evaluate("document.activeElement.id"), "bookmark-excerpt-input")
        self.page.keyboard.press("Escape")
        self.assertTrue(invoker.evaluate("node => node === document.activeElement"))
        self.assertEqual(invoker.get_attribute("aria-expanded"), "false")
        self.assertFalse(self.page.locator("#history-panel").evaluate("node => node.inert"))
        self.assertTrue(self.page.locator("#download").evaluate("node => node.inert"))

    def test_media_updates_percentage_and_saves_during_continuous_updates(self):
        self.serve(support.minimal_wav(), "audio/wav")
        self.open(self.reader_url("wav"))
        self.page.wait_for_function("() => document.querySelector('audio').readyState >= 1")
        self.page.evaluate("""() => {
          const media = document.querySelector('audio');
          Object.defineProperty(media, 'duration', {value:100});
          Object.defineProperty(media, 'currentTime', {value:45, writable:true});
          media.dispatchEvent(new Event('timeupdate'));
          window.__tick = setInterval(() => media.dispatchEvent(new Event('timeupdate')), 100);
        }""")
        self.page.locator("#history").click()
        self.page.wait_for_function("() => document.querySelector('.reader-progress-range').value === '45'")
        self.assertEqual(self.page.locator("#media-tab").get_attribute("aria-controls"), "media-panel")
        self.assertEqual(self.page.locator("#media-panel").get_attribute("role"), "tabpanel")
        self.assertTrue(self.page.locator("audio").get_attribute("aria-label"))
        self.wait_for_store("""async () => {
          const url = new URL(location.href).searchParams.get('url');
          return (await VoiceOfMLReaderStore.get(url))?.mediaTime === 45;
        }""")
        self.page.evaluate("clearInterval(window.__tick)")

    def test_image_disposal_removes_handlers_before_fallback(self):
        self.page.add_init_script("""(() => {
          const NativeImage = window.Image;
          window.Image = function(...args) { const image = new NativeImage(...args); window.__image = image; return image; };
        })()""")
        held = []
        self.page.route("**/api/reader-content**", lambda route: held.append(route))
        self.page.goto(self.reader_url("png"), wait_until="domcontentloaded")
        self.page.wait_for_function("() => window.__image?.getAttribute('src')")
        self.page.evaluate("window.dispatchEvent(new PageTransitionEvent('pagehide', {persisted:false}))")
        self.assertEqual(self.page.evaluate("[window.__image.onload, window.__image.onerror, window.__image.getAttribute('src')]"), [None, None, None])
        for route in held:
            route.abort()
        self.assertEqual(self.page.locator("html").get_attribute("data-reader-phase"), "disposed")

    def test_folder_navigation_has_one_handler_and_preserves_explicit_target(self):
        source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/folder.txt"
        folder = self.origin + "/Test?folder_self=explicit"
        self.page.add_init_script("sessionStorage.setItem('reader-resolve:folder-id', " + json.dumps(json.dumps({
            "url": source, "extension": "txt", "title": "Folder", "repo": "Test", "folder": ["metadata"]
        })) + ")")
        self.serve("Folder document")
        self.page.goto(self.origin + "/static/reader.html?" + urllib.parse.urlencode({
            "id": "folder-id", "ext": "txt", "path": "Test/explicit", "folder_url": folder
        }))
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        # With a top-level Reader, the explicit folder URL must win after metadata resolves.
        self.page.route("**/Test?**", lambda route: route.fulfill(content_type="text/html", body="Folder"))
        self.page.locator("#reader-path").click()
        self.page.wait_for_url(folder + "&path=explicit")
        self.assertEqual(self.page.url, folder + "&path=explicit")

    def test_folder_navigation_legacy_target_preserves_query_and_encoded_path(self):
        source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/folder.txt"
        folder_name = "a%2F &/#书?"
        query = urllib.parse.urlencode({"folder_self": folder_name, "q": "查询", "sort": "size", "sidebar": "0", "path": "stale"})
        folder = self.origin + "/Test?" + query
        self.page.add_init_script("sessionStorage.setItem('reader-resolve:legacy-folder', " + json.dumps(json.dumps({
            "url": source, "extension": "txt", "title": "Folder", "repo": "Test", "folder": ["different"]
        })) + ")")
        self.serve("Folder document")
        self.page.goto(self.origin + "/static/reader.html?" + urllib.parse.urlencode({
            "id": "legacy-folder", "ext": "txt", "folder_url": folder
        }))
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        self.page.route("**/Test?**", lambda route: route.fulfill(content_type="text/html", body="Folder"))
        self.page.locator("#reader-path").click()
        self.page.wait_for_url("**/Test?**")
        params = urllib.parse.parse_qs(urllib.parse.urlsplit(self.page.url).query)
        self.assertEqual(params, {"folder_self": [folder_name], "path": [folder_name],
                                  "q": ["查询"], "sort": ["size"], "sidebar": ["0"]})

    def test_folder_navigation_short_id_metadata_supplies_sidebar_path(self):
        source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/folder.txt"
        self.page.add_init_script("sessionStorage.setItem('reader-resolve:metadata-folder', " + json.dumps(json.dumps({
            "url": source, "extension": "txt", "title": "Folder", "repo": "Test", "folder": ["books", "with spaces"]
        })) + ")")
        self.serve("Folder document")
        self.open(self.origin + "/static/reader.html?id=metadata-folder&ext=txt")
        self.page.route("**/Test?**", lambda route: route.fulfill(content_type="text/html", body="Folder"))
        self.page.locator("#reader-path").click()
        self.page.wait_for_url("**/Test?**")
        params = urllib.parse.parse_qs(urllib.parse.urlsplit(self.page.url).query)
        self.assertEqual(params, {"folder_self": ["books/with spaces"], "path": ["books/with spaces"]})

    def test_mobile_folder_action_is_keyboard_reachable_and_navigates(self):
        self.page.set_viewport_size({'width': 320, 'height': 700})
        self.page.emulate_media(reduced_motion='reduce')
        source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/folder.txt"
        self.page.add_init_script("sessionStorage.setItem('reader-resolve:mobile-folder', " + json.dumps(json.dumps({
            "url": source, "extension": "txt", "repo": "Test", "folder": ["docs", "子"], "filename": "原件.txt.txt"
        })) + ")")
        self.serve("Folder document")
        self.open(self.origin + "/static/reader.html?id=mobile-folder&ext=txt")
        self.assertTrue(self.page.locator('#reader-path').is_hidden())
        self.assertEqual(self.page.locator('.reader-toolbar').bounding_box()['height'], 36)
        self.assertTrue(self.page.locator('#history-panel').evaluate('node=>node.inert'))
        self.page.locator('#reader-panel-path').evaluate('node=>node.focus()')
        self.assertNotEqual(self.page.evaluate('document.activeElement.id'), 'reader-panel-path')
        self.page.locator('#history').press('Enter')
        self.page.locator('#history-tab').click()
        self.assertEqual(self.page.get_by_role('button',name='文件信息',exact=True).count(), 0)
        action = self.page.locator('#reader-panel-path')
        action.wait_for(state='visible')
        self.assertIn('打开所在目录:Test/docs/子', action.get_attribute('aria-label'))
        self.assertEqual(self.page.locator('#title').text_content(), '原件.txt.txt')
        self.assertEqual(self.page.title(), '原件.txt.txt')
        self.page.keyboard.press('Tab')
        action.focus()
        self.assertNotEqual(action.evaluate('node=>getComputedStyle(node).outlineStyle'), 'none')
        self.page.keyboard.press('Escape')
        self.assertEqual(self.page.evaluate('document.activeElement.id'), 'history')
        self.page.locator('#history').press('Enter')
        self.assertTrue(action.is_visible())
        self.page.route('**/Test?**', lambda route: route.fulfill(content_type='text/html', body='Folder'))
        action.press('Enter')
        self.page.wait_for_url(self.origin + '/Test?folder_self=docs%2F%E5%AD%90&path=docs%2F%E5%AD%90')

    def test_reader_root_metadata_navigates_to_repository_root(self):
        source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/root.txt"
        self.page.add_init_script("sessionStorage.setItem('reader-resolve:root-folder', " + json.dumps(json.dumps({
            "url": source, "extension": "txt", "repo": "Test", "folder": []
        })) + ")")
        self.serve("Root document")
        self.open(self.origin + "/static/reader.html?id=root-folder&ext=txt")
        self.page.route(self.origin + "/Test", lambda route: route.fulfill(content_type="text/html", body="Folder"))
        self.page.locator("#reader-path").click()
        self.page.wait_for_url(self.origin + "/Test")

    def test_ambiguous_explicit_folder_targets_are_not_rewritten(self):
        source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/mixed.txt"
        self.page.add_init_script("sessionStorage.setItem('reader-resolve:mixed-folder', " + json.dumps(json.dumps({
            "url": source, "extension": "txt", "repo": "Test", "folder": ["metadata"]
        })) + ")")
        folder = self.origin + "/Test?folder_self=one&folder_self=two&path=kept"
        self.serve("Mixed document")
        self.page.goto(self.origin + "/static/reader.html?" + urllib.parse.urlencode({
            "id": "mixed-folder", "ext": "txt", "folder_url": folder
        }))
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        self.page.route("**/Test?**", lambda route: route.fulfill(content_type="text/html", body="Folder"))
        self.page.locator("#reader-path").click()
        self.page.wait_for_url(folder)

    def test_chapter_manifest_restores_structured_history_and_bookmark(self):
        source = "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=chapters/ebook/chm/" + "a" * 64 + "/1234567890abcdef/chapter-manifest.json"
        manifest = {"version": 1, "kind": "epub-chapters", "chapters": [
            {"index": i, "path": f"chapters/chapter-{i:04d}.xhtml", "title": f"Chapter {i}", "bytes": 100} for i in range(1, 5)
        ]}
        def serve(route):
            path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)["path"][0]
            if path.endswith("chapter-manifest.json"):
                route.fulfill(content_type="application/json", body=json.dumps(manifest))
            else:
                number = path.rsplit("chapter-", 1)[-1].split(".")[0]
                route.fulfill(content_type="text/html", body=f"<h1>Chapter {number}</h1><p style='height:2000px'>Body</p>")
        self.page.route("**/api/reader-bucket-resource**", serve)
        url = self.reader_url("epub-chapters", url=source)
        self.open(url)
        support.open_reader_panel(self.page)
        self.page.locator("#toc-list .panel-item-main").nth(2).click()
        self.page.locator('.reader-epub-chapter[data-chapter="3"]').evaluate("node => { const v=document.querySelector('#viewport'); v.scrollTop += node.getBoundingClientRect().top - v.getBoundingClientRect().top + 250; }")
        self.page.locator("#bookmark-ribbon").click()
        self.page.locator("#bookmark-add").click()
        self.wait_for_store("async source => (await VoiceOfMLReaderStore.listBookmarks(source)).length === 1", source)
        bookmark = self.page.evaluate("async source => (await VoiceOfMLReaderStore.listBookmarks(source))[0]", source)
        self.assertEqual(bookmark["chapterIndex"], 3)
        self.page.wait_for_timeout(700)
        self.open(url)
        self.page.wait_for_function("() => document.querySelector('.reader-epub-chapter[data-chapter=\"3\"]')")
        offset = self.page.locator('.reader-epub-chapter[data-chapter="3"]').evaluate("node => document.querySelector('#viewport').getBoundingClientRect().top + 8 - node.getBoundingClientRect().top")
        self.assertAlmostEqual(offset, bookmark["chapterOffset"], delta=3)
        self.open(url + "&" + urllib.parse.urlencode({"bookmark": bookmark["id"], "bookmark_source": source}))
        self.page.wait_for_function("() => document.querySelector('.reader-epub-chapter[data-chapter=\"3\"]')")

    def serve_chapter_search(self, index_failure=None, namespaced=False):
        base = "chapters/ebook/chm/" + "b" * 64 + "/1234567890abcdef/"
        source = "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + base + "chapter-manifest.json"
        chapters, texts, bodies = [], [], {}
        for index in range(1, 13):
            path = f"chapters/chapter-{index:04d}.xhtml"
            title = f"Chapter {index}"
            if index == 12:
                body = ("<h1>最后一章</h1><p>前言 &amp;amp; <span>独特</span><em>词语</em> 尾声</p>"
                        + "".join(f"<p>第{i}处needle结束</p>" for i in range(155))
                        + "<p>手机 手。机</p>")
                text = "最后一章 前言 & 独特 词语 尾声 " + " ".join(f"第{i}处needle结束" for i in range(155)) + " 手机 手。机"
                if namespaced:
                    body = ('<html:html xmlns:html="http://www.w3.org/1999/xhtml"><html:head>'
                            '<html:meta/><html:title>原始标题</html:title></html:head><html:body>'
                            + body + '</html:body></html:html>')
                    text = "原始标题 " + text
            else:
                body = f"<h1>{title}</h1><p style='height:12000px'>普通正文</p>"
                text = title + " 普通正文"
            bodies[base + path] = body
            chapters.append({"index": index, "path": path, "title": title, "bytes": len(body.encode())})
            texts.append({"index": index, "path": path, "title": title, "text": text})
        packed = gzip.compress(json.dumps({"version": 1, "kind": "epub-search-index", "chapters": texts}, ensure_ascii=False).encode(), mtime=0)
        manifest = {"version": 1, "kind": "epub-chapters", "chapters": chapters,
                    "search_index": {"path": "epub-search-index.json.gz", "bytes": len(packed), "sha256": hashlib.sha256(packed).hexdigest()}}
        requests = []
        def serve(route):
            path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)["path"][0]
            requests.append(path)
            if path.endswith("chapter-manifest.json"):
                route.fulfill(content_type="application/json", body=json.dumps(manifest),
                              headers={"Access-Control-Allow-Origin": "*"})
            elif path.endswith("epub-search-index.json.gz"):
                attempt = sum(item.endswith("epub-search-index.json.gz") for item in requests)
                if index_failure and index_failure(route, attempt, packed):
                    return
                route.fulfill(content_type="application/gzip", body=packed,
                              headers={"Access-Control-Allow-Origin": "*"})
            else:
                route.fulfill(content_type="text/html", body=bodies[path],
                              headers={"Access-Control-Allow-Origin": "*"})
        self.page.route("**/api/reader-bucket-resource**", serve)
        self.open(self.reader_url("epub-chapters", url=source))
        return requests, base

    def test_chapter_search_is_lazy_complete_paged_and_navigates_unloaded_repeated_hits(self):
        requests, base = self.serve_chapter_search()
        self.assertFalse(any(item.endswith("epub-search-index.json.gz") for item in requests))
        self.assertNotIn(base + "chapters/chapter-0012.xhtml", requests)
        self.search("needle")
        self.assertEqual(self.page.locator("#full-search-status").text_content(), "155 个结果")
        self.assertEqual(self.page.locator(".full-search-result").count(), 50)
        self.assertTrue(self.page.locator("#full-search-cancel").is_hidden())
        self.page.evaluate("""() => {
          window.__cancelPagingChanges = [];
          const cancel = document.querySelector('#full-search-cancel');
          new MutationObserver(() => {
            __cancelPagingChanges.push(cancel.hidden);
          }).observe(document.querySelector('#full-search-cancel'), {
            attributes: true, attributeFilter: ['hidden']
          });
        }""")
        self.assertNotIn(base + "chapters/chapter-0012.xhtml", requests)
        page_input = self.page.locator("#full-search-page")
        page_input.fill("4")
        page_input.press("Enter")
        page_input.blur()
        self.page.wait_for_function("() => document.querySelectorAll('.full-search-result').length === 5")
        self.assertTrue(self.page.locator("#full-search-cancel").is_hidden())
        self.assertNotIn(False, self.page.evaluate("__cancelPagingChanges"))
        self.page.locator(".full-search-result").last.click()
        self.page.wait_for_function("() => document.querySelector('.reader-epub-chapter[data-chapter=\"12\"] mark.full-search-highlight')")
        mark = self.page.locator(".reader-epub-chapter mark.full-search-highlight")
        self.assertEqual(mark.text_content(), "needle")
        self.assertEqual(mark.locator("..").text_content(), "第154处needle结束")
        # Reopening preserves the current result page and navigation position.
        support.open_reader_panel(self.page)
        self.assertFalse(self.page.locator("#full-search-view").is_hidden())
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '155 个结果'")
        self.assertEqual(self.page.locator("#full-search-page").input_value(), "4")
        self.page.locator("#full-search-prev").click()
        self.page.wait_for_function("() => document.querySelector('#full-search-page').value === '4'")
        self.page.locator("#full-search-next").click()
        self.page.wait_for_function("() => document.querySelector('.reader-epub-chapter mark')?.parentElement.textContent === '第154处needle结束'")
        self.assertEqual(self.page.locator("#full-search-page").input_value(), "4")
        self.assertEqual(sum(item.endswith("epub-search-index.json.gz") for item in requests), 1)

    def test_failed_chapter_page_restarts_worker_and_restores_target_page(self):
        def expose_worker_failure(route):
            response = route.fetch()
            needle = 'worker.postMessage({ type: "init", configuration });'
            script = response.text()
            self.assertIn(needle, script)
            route.fulfill(response=response, body=script.replace(needle,
                "window.__breakChapterWorker = () => worker.onerror({ preventDefault() {} }); " + needle))
        self.page.route("**/static/reader/search/reader-chapter-search.mjs*", expose_worker_failure)
        self.serve_chapter_search()
        self.search("needle")
        self.page.evaluate("window.__breakChapterWorker()")
        self.page.locator("#full-search-page").fill("3")
        self.page.locator("#full-search-page").dispatch_event("change")
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent.includes('全文搜索组件加载失败')")
        self.page.locator("#full-search-retry").click()
        self.page.wait_for_function("() => document.querySelector('.full-search-rank')?.textContent === '101.'")
        self.assertEqual(self.page.locator("#full-search-page").input_value(), "3")
        self.assertEqual(self.page.locator("#full-search-status").text_content(), "155 个结果")

    def test_chapter_search_emits_partial_results_before_exact_total(self):
        self.serve_chapter_search()
        support.open_reader_panel(self.page)
        self.page.locator("#full-search-toggle").click()
        self.page.evaluate("""() => {
          window.__chapterStatuses = [];
          new MutationObserver(() => __chapterStatuses.push(document.querySelector('#full-search-status').textContent))
            .observe(document.querySelector('#full-search-status'), { childList: true, subtree: true });
        }""")
        self.page.locator("#full-search-input").fill("needle")
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '155 个结果'")
        self.assertTrue(any("155 个结果(正在搜索" in status for status in
                            self.page.evaluate("window.__chapterStatuses")))

    def test_chapter_search_maps_inline_nodes_entities_and_repeated_searches(self):
        requests, _ = self.serve_chapter_search(namespaced=True)
        self.search("独特 词语")
        self.assertEqual(self.page.locator("#full-search-status").text_content(), "1 个结果")
        self.page.locator(".full-search-result").click()
        self.page.wait_for_function("() => document.querySelectorAll('.reader-epub-chapter mark.full-search-highlight').length === 2")
        self.assertEqual(self.page.locator(".reader-epub-chapter mark.full-search-highlight").all_text_contents(), ["独特", "词语"])
        support.open_reader_panel(self.page)
        self.assertFalse(self.page.locator("#full-search-view").is_hidden())
        self.page.locator("#full-search-input").fill("手机")
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果' && document.querySelector('.full-search-result')?.textContent.includes('手机')")
        self.page.locator(".full-search-result").click()
        self.page.wait_for_function("() => document.querySelector('.reader-epub-chapter mark.full-search-highlight')?.textContent === '手机'")
        self.assertEqual(sum(item.endswith("epub-search-index.json.gz") for item in requests), 1)

    def test_chapter_search_retries_a_failed_index_and_rejects_corrupt_bytes(self):
        def failure(route, attempt, packed):
            if attempt == 1:
                route.fulfill(status=503, body="temporarily unavailable")
                return True
            if attempt == 2:
                route.fulfill(content_type="application/gzip", body=packed[:-1] + bytes([packed[-1] ^ 1]))
                return True
        requests, _ = self.serve_chapter_search(failure)
        support.open_reader_panel(self.page)
        self.page.locator("#full-search-toggle").click()
        self.page.locator("#full-search-input").fill("needle")
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent.includes('503')")
        self.page.locator("#full-search-retry").click()
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent.includes('校验失败')")
        self.page.locator("#full-search-retry").click()
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '155 个结果'")
        self.assertEqual(sum(item.endswith("epub-search-index.json.gz") for item in requests), 3)

    def test_chapter_search_cancelled_download_cannot_publish_stale_results(self):
        held = []
        def hold(route, attempt, packed):
            if attempt == 1:
                held.append((route, packed))
                return True
        requests, _ = self.serve_chapter_search(hold)
        support.open_reader_panel(self.page)
        self.page.locator("#full-search-toggle").click()
        with self.context.expect_event("request", predicate=lambda request: "epub-search-index" in request.url):
            self.page.locator("#full-search-input").fill("needle")
        self.page.locator("#full-search-cancel").click()
        self.assertEqual(self.page.locator("#full-search-status").text_content(), "搜索已取消")
        self.page.locator("#full-search-input").fill("手机")
        self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")
        self.assertEqual(self.page.locator(".full-search-result").count(), 1)
        self.assertEqual(sum(item.endswith("epub-search-index.json.gz") for item in requests), 2)
        for route, packed in held:
            route.fulfill(content_type="application/gzip", body=packed)
        self.assertEqual(self.page.locator("#full-search-status").text_content(), "1 个结果")

    def test_chapter_resources_allow_siblings_within_manifest_family_only(self):
        for extension in ("epub", "chm"):
            with self.subTest(extension=extension):
                base = "chapters/ebook/" + extension + "/" + "a" * 64 + "/1234567890abcdef/"
                source = "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + base + "chapter-manifest.json"
                manifest = {"version": 1, "kind": "epub-chapters", "chapters": [
                    {"index": 1, "path": "chapters/chapter-0001.xhtml", "bytes": 100}
                ]}
                def serve(route):
                    path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)["path"][0]
                    if path.endswith("chapter-manifest.json"):
                        route.fulfill(content_type="application/json", body=json.dumps(manifest))
                    elif path.endswith(".svg"):
                        route.fulfill(content_type="image/svg+xml", body="<svg xmlns='http://www.w3.org/2000/svg'/>")
                    else:
                        route.fulfill(content_type="text/html", body="""
                          <h1>Chapter</h1><img id='cover' src='../resources/cover.svg'>
                          <img id='escape' src='../../resources/outside.svg'>
                          <img id='external' src='https://evil.test/cover.svg'>
                        """)
                self.page.route("**/api/reader-bucket-resource**", serve)
                self.open(self.reader_url("epub-chapters", url=source))
                resource = "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + urllib.parse.quote(base + "resources/cover.svg", safe="")
                self.assertEqual(self.page.locator("#cover").get_attribute("src"), resource)
                self.assertIsNone(self.page.locator("#escape").get_attribute("src"))
                self.assertIsNone(self.page.locator("#external").get_attribute("src"))
                self.page.unroute("**/api/reader-bucket-resource**", serve)

    def test_bucket_chapter_manifest_loads_before_reader_module_and_is_consumed_once(self):
        held, manifests = [], []
        root = 'chapters/ebook/epub/' + 'a' * 64 + '/' + 'b' * 16
        source = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?' + urllib.parse.urlencode({'path':root + '/chapter-manifest.json'})
        manifest = {'version':1, 'kind':'epub-chapters', 'chapters':[
            {'index':1, 'path':'chapters/chapter-0001.xhtml', 'bytes':100}]}
        def resource(route):
            path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)['path'][0]
            if path.endswith('/chapter-manifest.json'):
                manifests.append(route.request.url)
                route.fulfill(json=manifest)
            else:
                route.fulfill(content_type='text/html', body='<h1>Copyright</h1><p>Immediately readable text</p>')
        self.page.route('**/api/reader-bucket-resource?*', resource)
        self.page.route('**/static/reader.js*', lambda route: held.append((route, route.fetch())))
        self.page.goto(self.reader_url('epub-chapters', url=source), wait_until='commit')
        self.page.wait_for_function('() => !!window.__VOICE_READER_CHAPTER_PRELOAD__?.manifest')
        self.page.wait_for_function('async () => (await window.__VOICE_READER_CHAPTER_PRELOAD__.manifest).ok')
        self.assertEqual(len(manifests), 1)
        self.assertEqual(len(held), 1)
        route, response = held[0]
        route.fulfill(response=response)
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        self.assertEqual(len(manifests), 1)
        self.assertIsNone(self.page.evaluate('window.__VOICE_READER_CHAPTER_PRELOAD__.manifest'))
        self.assertTrue(self.page.locator('.reader-epub-chapter p').is_visible())

    def test_chapter_open_overlaps_first_page_and_prefetches_past_small_front_matter(self):
        root = "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=chapters/ebook/chm/" + "a" * 64 + "/1234567890abcdef"
        for width, chapter_bytes, last_expected in ((390, 100, 11), (1100, 1000000, 7)):
            with self.subTest(width=width, chapter_bytes=chapter_bytes):
                self.page.set_viewport_size(dict(width=width, height=800))
                requested, first = [], []
                manifest = {"version": 1, "kind": "epub-chapters", "chapters": [
                    {"index": i, "path": f"chapters/chapter-{i:04d}.xhtml", "bytes": chapter_bytes}
                    for i in range(1, 21)
                ]}
                def resource(route):
                    path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query).get("path", [""])[0]
                    if path.endswith("chapter-manifest.json"):
                        route.fulfill(json=manifest)
                        return
                    number = int(path.rsplit("chapter-", 1)[1].split(".", 1)[0])
                    requested.append(number)
                    if number == 1:
                        first.append(route)
                    else:
                        route.fulfill(content_type="text/html", body=f'<h1>Chapter {number}</h1><p style="height:1000px">Readable {number}</p><img src="picture.png"/>')
                self.page.route("**/api/reader-bucket-resource**", resource)
                self.page.goto(self.reader_url("epub-chapters", url=root + "/chapter-manifest.json"))
                self.page.locator('.reader-epub-chapter[data-chapter="3"]').wait_for(state="attached")
                self.assertEqual(requested[0], 1)
                self.assertEqual(len(first), 1)
                self.assertEqual(self.page.locator('.reader-epub-chapter[data-chapter="1"]').count(), 0)
                first[0].fulfill(content_type="text/html", body='<h1>Copyright</h1><p style="height:1000px">Opening page</p>')
                self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
                self.page.locator(f'.reader-epub-chapter[data-chapter="{last_expected}"]').wait_for(state="attached")
                self.page.wait_for_timeout(100)
                self.assertEqual(set(requested), set(range(1, last_expected + 1)), requested)
                self.assertEqual(self.page.locator('#viewport').evaluate('node => node.scrollTop'), 0)
                image = self.page.locator('.reader-epub-chapter[data-chapter="3"] img')
                self.assertEqual(image.evaluate('node => node.loading'), 'lazy')
                self.assertEqual(image.evaluate('node => node.fetchPriority'), 'low')
                self.page.unroute("**/api/reader-bucket-resource**", resource)

    def test_chapter_navigation_during_delayed_open_keeps_user_target(self):
        root = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=chapters/ebook/chm/' + 'a' * 64 + '/1234567890abcdef'
        manifest = {'version':1, 'kind':'epub-chapters', 'chapters':[
            {'index':i, 'path':f'chapters/chapter-{i:04d}.xhtml', 'bytes':100} for i in range(1,21)]}
        first = []
        def resource(route):
            path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query).get('path',[''])[0]
            if path.endswith('chapter-manifest.json'):
                route.fulfill(json=manifest)
                return
            number = int(path.rsplit('chapter-',1)[1].split('.',1)[0])
            if number == 1:
                first.append(route)
            else:
                route.fulfill(content_type='text/html', body=f'<h1>Chapter {number}</h1><p style="height:1600px">Readable {number}</p>')
        def instrument(route):
            response = route.fetch()
            route.fulfill(response=response, body=response.text() + '\nwindow.__earlyChapter = index => navigationState.tocEntries[index-1].activate(beginReaderNavigation());\n')
        self.page.route('**/api/reader-bucket-resource**',resource)
        self.page.route('**/static/reader.js*',instrument)
        self.page.goto(self.reader_url('epub-chapters',url=root+'/chapter-manifest.json'))
        self.page.locator('.reader-epub-chapter[data-chapter="3"]').wait_for(state='attached')
        self.assertTrue(self.page.evaluate('__earlyChapter(15)'))
        target = self.page.locator('.reader-epub-chapter[data-chapter="15"]')
        before = target.evaluate('node => node.getBoundingClientRect().top')
        first[0].fulfill(content_type='text/html',body='<h1>Copyright</h1><p style="height:1600px">Opening page</p>')
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        self.page.wait_for_function('top => Math.abs(document.querySelector(\'.reader-epub-chapter[data-chapter="15"]\').getBoundingClientRect().top-top)<3',arg=before)
        self.assertTrue(target.is_visible())

    def test_concurrent_chapter_open_keeps_order_when_third_chapter_arrives_first(self):
        root = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=chapters/ebook/chm/' + 'a' * 64 + '/1234567890abcdef'
        manifest = {'version':1, 'kind':'epub-chapters', 'chapters':[
            {'index':i, 'path':f'chapters/chapter-{i:04d}.xhtml', 'bytes':100} for i in range(1,5)]}
        held = {}
        def body(number):
            return f'<h1>Chapter {number}</h1><p style="height:1200px">Readable {number}</p>'
        def resource(route):
            path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query).get('path',[''])[0]
            if path.endswith('chapter-manifest.json'):
                route.fulfill(json=manifest)
                return
            number = int(path.rsplit('chapter-',1)[1].split('.',1)[0])
            if number in (1,2):
                held[number] = route
            else:
                route.fulfill(content_type='text/html',body=body(number))
        self.page.route('**/api/reader-bucket-resource**',resource)
        self.page.goto(self.reader_url('epub-chapters',url=root+'/chapter-manifest.json'))
        self.page.locator('.reader-epub-chapter[data-chapter="3"]').wait_for(state='attached')
        held[1].fulfill(content_type='text/html',body=body(1))
        self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
        self.assertEqual(self.page.locator('.epub-frame > [data-chapter]').evaluate_all(
            'nodes=>nodes.map(node=>Number(node.dataset.chapter))'),[1,2,3,4])
        held[2].fulfill(content_type='text/html',body=body(2))
        self.page.locator('.reader-epub-chapter[data-chapter="2"]').wait_for(state='attached')
        self.assertEqual(self.page.locator('.reader-epub-chapter').evaluate_all(
            'nodes=>nodes.map(node=>Number(node.dataset.chapter))'),[1,2,3,4])
        self.assertEqual(self.page.locator('#viewport').evaluate('node=>node.scrollTop'),0)


if __name__ == "__main__":
    unittest.main()