Based on this answer, I implement two versions of \widetilde, which is wide enough to cover all the text I want:
\documentclass{article}
\usepackage{amsmath,amssymb,stackengine,scalerel}
\newlength\A
\ExplSyntaxOn
%first method, based on stackon
\newcommand{\wtildea}[1]{
\settowidth{\A}{#1}
\stackon[-7pt]{$#1$}{\hstretch{\fp_eval:n{\dim_to_fp:n{\A}/21}}{\widetilde{\phantom{#1}}}}
}
%second method, based on tikz
\usepackage{tikz,mathtools}
\newcommand{\wtildeb}[1]{
\settowidth{\A}{$#1$}
\ooalign{$\tikz{\node[xscale=\fp_eval:n{\dim_to_fp:n{\A}}/5.5]{$\widetilde{\phantom{x}}$}}$\cr\hidewidth$#1$\hidewidth\cr}
}
\ExplSyntaxOff
\begin{document}
$$xxAAAAAAAAAAAAxx$$
$$xx\wtildea{AAAAAAAAAAAA}xx$$
$$xx\wtildeb{AAAAAAAAAAAA}xx$$
\end{document}
However, they both have spacing issues, and the first solution causes the text with tilde shifts to right:

How can I fix that?

inner~sep=+0pt. – Qrrbrbirlbel Apr 14 '23 at 13:41