There are some tools that "buzz" you for losing focus. Something like RescueTime or the Pomodoro Technique might do the trick.
But I find the issue is usually lack of rest. I don't mean lack of non-work activities. The brain doesn't get to rest if you're doing things like gaming, social media, or watching anime. It ends up 'fragmented'. Sleep and meditation helps, or even things like focusing on the road while driving without turning on a podcast.