Refactor the token manager into the background manager and add more tests