Patent law includes a provision for situations like this - it’s called “derivation,” meaning basically that someone stole another person’s work and tried to patent it. The rightful inventor can initiate a proceeding at the patent office to invalidate the patent and get control of the work.