There have been cases of undercover cops getting shot, and even getting shot and killed, by uniformed officers.
For example:
https://abcnews.go.com/US/story?id=94403&page=1
“How does plainclothes cops survive encounters with uniformed cops they don’t know?”
If at all possible they try not to have gun in hand. They identify themselves immediately with whatever the local lingo is. And they live by the iron rule, the uniformed cop is the boss... they do exactly as they command with zero argument.
To do otherwise is to court disaster.
It’s akin to a recon patrol returning and making contact with a friendly perimeter. Very very deadly if done wrong.
I once knew a guy who was with DEA. He said that if they were undercover, it was coordinated with local cops with joint management. Any cops on the scene would know there were undercover agents around and how many. It isn't a 100% guarantee, I imagine.
Sometimes they don't. Those stories do not get published very often.
There is specific training and the equivalent of a "secret handshake" for that particular scenario (careful and slow presentation of credentials). It is still a risky situation. The basic minimum is to disarm immediately and submit to arrest once the uniforms show up.
That part is the same thing that civilians need to do if they are still hanging around when the uniforms show up.
Remember, "No good deed goes unpunished". Your weapon will most likely be confiscated as "evidence". You might be arrested, regardless of the circumstances. Do not argue with police; there is no point to that, and it can only make things worse. Call your lawyer right away and don't make any statements to the police.
The best plan is not to be there in the first place.
Can I shoot some random dude in a police uniform with a gun? No. Ok then. Why don’t they face the same punishment?