The decision of when to file a utility patent application requires weighing a number of different factors and is best made in consultation with a patent attorney.
Factors that impact this decision include whether patent protection is desired only in the United States or in the United States and in other countries with more stringent requirements for early filing of patent applications. Another factor is whether the invention can be maintained effectively as a trade secret.
The current rules in the United States are that an invention cannot be the subject of a United States patent application after a public sale, public use, or one year after a public disclosure. (As the revision to the law is recent, there is some debate on whether a private sale counts as well as a public sale).
On the other hand, one should not file patent applications before having an educated guess on how to solve a problem. A patent application is not intended to be a lottery ticket where one guesses that someday someone will figure out how to do X as X would be really nice to have. If an applicant has no idea how to make and use an invention that does X, then that is merely recognition of an unmet market need and not an invention. Once an inventor has worked out a proposed solution to how to make and use an invention to do X, it may be an appropriate time to file a patent application. In many areas of technology it is not necessary to actually build the invention that does X, it is ok to just document how one would do X.
Building a prototype of the invention that does X is often a good idea before filing a patent application as the process of building the prototype may take the understanding of the invention to a new plateau and allow for a more focused and stronger patent application.