I can’t tell you exactly how the built-in harvesting behavior works, but abilities have things called Markers. These tell when a unit is targeting them with an ability.
Anyways, I created a custom harvesting ability. The unit has three abilities. A “Harvest” ability, a “Transfer” ability, and a “Return Cargo” ability.
With the Harvest ability, the unit channels on a target unit for a specified duration, then at the end of the channel, casts the Return Cargo ability.
Return Cargo is virtually a dummy ability. It’s an instant effect that searches the map for a valid Transfer target and orders the caster to Transfer to the discovered unit.
Transfer is a targeted ability that does whatever Return Cargo should do, e.g. granting resources and removing the resource-holding behavior.
When the Harvest ability finishes its channel, the unit automatically casts Return Cargo if the unit’s current action is to Harvest and it doesn’t have any additional orders queued so it can be interrupted at will.
It can probably be done better, but this is how I managed.
I did not make it automatically seek a new resource location because that’s not something relevant to my ability, but you should be able to use Markers to detect if another unit is harvesting when it’s about to channel and, if it is, perform a search area for a resource that doesn’t have a marker and order it to instead harvest from there. That or you could use behaviors which can be a little easier and more reliable to work with.