WASHINGTON — Less than two hours after Defense Secretary Jim Mattis went to the White House on Thursday to hand a resignation letter to President Trump, the president stood in the Oval Office and dictated a glowing tweet announcing that Mr. Mattis was retiring “with distinction” at the end of February.

But Mr. Trump had not read the letter. As became apparent to the president only after days of news coverage, a senior administration official said, Mr. Mattis had issued a stinging rebuke of Mr. Trump over his neglect of allies and tolerance of authoritarians. The president grew increasingly angry as he watched a parade of defense analysts go on television to extol Mr. Mattis’s bravery, another aide said, until he decided on Sunday that he had had enough.

In a tweet later that morning, the president announced that he was removing Mr. Mattis from his post by Jan. 1, two months before the defense secretary had planned to depart. Mr. Trump said that Patrick M. Shanahan, Mr. Mattis’s deputy and a former Boeing executive, would serve as the acting defense secretary, praising him as “very talented” and adding that “he will be great!”

Mr. Trump’s sudden announcement that he was firing a man who had already quit was the exclamation point to a tumultuous week at the Pentagon, where officials have been reeling from day after day of presidential tweets announcing changes in American military policy.