But Mr. Giuliani and his client had a serious problem, which they were slow to comprehend.

In April, the F.B.I. raided the Manhattan office and residences of Mr. Cohen — the president’s lawyer and fixer — walking off with business records, emails and other documents dating back years. At first, Mr. Trump was not concerned.

The president told advisers that Mr. Rosenstein assured him at the time that the Cohen investigation had nothing to do with him. In the president’s recounting, Mr. Rosenstein told him that the inquiry in New York was about Mr. Cohen’s business dealings, that it did not involve the president and that it was not about Russia. Since then, Mr. Trump has asked his advisers if Mr. Rosenstein was deliberately misleading him to keep him calm.

Mr. Giuliani initially portrayed Mr. Cohen as “honest,” and the president praised him publicly. But Mr. Cohen soon told prosecutors in New York how Mr. Trump had ordered him during the 2016 campaign to buy the silence of women who claimed they had sex with Mr. Trump. In a separate bid for leniency, Mr. Cohen told Mr. Mueller’s prosecutors about Mr. Trump’s participation in negotiations during the height of the presidential campaign to build a Trump Tower in Moscow.

Mr. Trump was now battling twin investigations that seemed to be moving ever close to him. And Mr. Cohen, once the president’s fiercest defender, was becoming his chief tormentor.

In a court appearance in August, Mr. Cohen pleaded guilty and told a judge that Mr. Trump had ordered him to arrange the payments to the women, Stormy Daniels and Karen McDougal. Mr. Cohen’s descriptions of Mr. Trump’s actions made the president, in effect, an unindicted co-conspirator and raised the prospect of the president being charged after he leaves office. Representative Jerrold Nadler, Democrat of New York, who in January became the chairman of the House Judiciary Committee, which has jurisdiction over the matter, said the implied offense was probably impeachable.

The president struck back, launching a volley of tweets that savaged Mr. Cohen and his family — insinuating that Mr. Cohen’s father-in-law had engaged in unexamined criminal activity. He called Mr. Cohen a “rat.” The messages infuriated Democratic lawmakers, who claimed the president was trying to threaten and intimidate a witness before testimony Mr. Cohen planned before Congress.

“He’s only been threatened by the truth,” the president responded.

Another attorney general takes office

As the prosecutors closed in, Mr. Trump felt a more urgent need to gain control of the investigation.