diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..32f231c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +release/Interview[[:space:]]Coder-1.0.0-arm64-mac.zip filter=lfs diff=lfs merge=lfs -text +release/Interview[[:space:]]Coder-1.0.0-arm64.dmg filter=lfs diff=lfs merge=lfs -text +release/mac-arm64/Interview[[:space:]]Coder.app/Contents/Frameworks/Electron[[:space:]]Framework.framework/Versions/A/Electron[[:space:]]Framework filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c32d9fa --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +node_modules +dist-electron +release +dist +.env +.env.* +**/.DS_Store +**/.vscode +**/.idea +**/package-lock.json +scripts/ +**/scripts/ +scripts/manual-notarize.js \ No newline at end of file diff --git a/CHANGES.md b/CHANGES.md new file mode 100644 index 0000000..d844b57 --- /dev/null +++ b/CHANGES.md @@ -0,0 +1,36 @@ +# Interview Coder - Unlocked Edition - Changes + +## Fixes and Improvements + +### UI Improvements +1. **Fixed Language Dropdown Functionality**: + - Enabled the language dropdown in the settings panel + - Added proper language change handling + - Made language selection persist across sessions + +2. **Implemented Working Logout Button**: + - Added proper API key clearing functionality to the logout button + - Added success feedback via toast message + - Implemented app reload after logout to reset state + +3. **Fixed Window Size Issues**: + - Added explicit window dimensions in main.ts (width: 800px, height: 600px) + - Added minimum window size constraints to prevent UI issues + - Improved dimension handling with fallback sizes + +4. **Improved Settings Dialog Positioning**: + - Made settings dialog responsive with min/max constraints + - Added z-index to ensure dialog appears above other content + - Improved positioning to center properly regardless of window size + +5. **Enhanced Dropdown Initialization**: + - Improved dropdown initialization timing + - Reduced initialization delay for better responsiveness + +### Maintaining Original UI Design +- Preserved the original UI design and interaction patterns +- Fixed functionality within the existing UI rather than adding new elements +- Kept the settings accessible through the gear icon menu + +These changes fix the issues while preserving the original app's look and feel, just removing the payment restrictions and making everything work properly. + diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..43d44ae --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,57 @@ +# Contributing to Interview Coder - Unlocked Edition + +First off, thank you for considering contributing to Interview Coder! We created this tool to help the community, and we welcome improvements that make it better for everyone. + +## Our Community Values + +- **Collaborative Development**: We believe in building together rather than fragmenting our efforts +- **Open Access**: We want to keep this tool accessible to everyone who needs it +- **Continuous Improvement**: The tool should get better with each contribution + +## How to Contribute + +### 1. Fork the Repository + +- Click the "Fork" button at the top of the repository page +- Clone your fork locally: `git clone https://github.com/YOUR-USERNAME/interview-coder-unlocked.git` + +### 2. Create a Branch + +- Create a branch for your feature: `git checkout -b feature/your-feature-name` + +### 3. Make Your Changes + +- Implement your changes, improvements, or bug fixes +- Make sure to test your changes thoroughly +- Ensure your code follows the existing style + +### 4. Submit a Pull Request + +- Push your changes to your fork: `git push origin feature/your-feature-name` +- Go to the original repository and create a Pull Request +- Describe your changes in detail +- Reference any related issues + +## Guidelines for Modifications + +Under the AGPL-3.0 license, you are free to modify the code, but we strongly encourage you to: + +1. **Contribute Back**: Submit your improvements as Pull Requests to the main repository +2. **Share Openly**: Make your modifications available to the public, especially if you deploy a modified version +3. **Maintain Attribution**: Keep the original copyright notices and license information + +## License Compliance + +Remember that this project is licensed under the GNU Affero General Public License v3.0 (AGPL-3.0). This means: + +- You must disclose your source code when you distribute the software +- If you modify the software and run it on a server that users interact with, you must make the source code of your modified version available to those users +- Any modifications you make must also be licensed under the AGPL-3.0 + +## Community Guidelines + +- Be respectful and constructive in your comments and feedback +- Help review other contributors' pull requests +- Report bugs and issues clearly with steps to reproduce + +Thank you for helping make Interview Coder better for everyone! diff --git a/LICENSE b/LICENSE index 0ad25db..f707826 100644 --- a/LICENSE +++ b/LICENSE @@ -7,655 +7,34 @@ Preamble - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -. + The GNU Affero General Public License is a free, copyleft license for + software and other kinds of works, specifically designed to ensure + cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed + to take away your freedom to share and change the works. By contrast, + our General Public Licenses are intended to guarantee your freedom to + share and change all versions of a program--to make sure it remains free + software for all its users. + + When we speak of free software, we are referring to freedom, not + price. Our General Public Licenses are designed to make sure that you + have the freedom to distribute copies of free software (and charge for + them if you wish), that you receive source code or can get it if you + want it, that you can change the software or use pieces of it in new + free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights + with two steps: (1) assert copyright on the software, and (2) offer + you this License which gives you legal permission to copy, distribute + and/or modify the software. + + A secondary benefit of defending all users' freedom is that + improvements made in alternate versions of the program, if they + receive widespread use, become available for other developers to + incorporate. Many developers of free software are heartened and + encouraged by the resulting cooperation. However, in the case of + software used on network servers, this result may fail to come about. + The GNU General Public License permits making a modified version and + letting the public access it on a server without ever releasing its + source code to \ No newline at end of file diff --git a/LICENSE-SHORT b/LICENSE-SHORT new file mode 100644 index 0000000..548fd0d --- /dev/null +++ b/LICENSE-SHORT @@ -0,0 +1,23 @@ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 2007 + +Copyright (C) 2025 Interview Coder - Unlocked Edition + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published +by the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +The full text of the license can be found at: https://www.gnu.org/licenses/agpl-3.0.html + +ADDITIONAL TERMS: +- Any modifications made to this software should be contributed back to the main project repository. +- If you deploy this software on a network server, you must make the complete source code of your modifications available to all users of that server. diff --git a/README.md b/README.md new file mode 100644 index 0000000..33643bb --- /dev/null +++ b/README.md @@ -0,0 +1,167 @@ +# Interview Coder - Unlocked Edition + +An invisible desktop application that helps you pass your technical interviews. + +## Features + +- 🎯 99% Invisibility: Undetectable window that bypasses most screen capture methods +- 📸 Smart Screenshot Capture: Capture both question text and code separately for better analysis +- 🤖 AI-Powered Analysis: Automatically extracts and analyzes coding problems using GPT-4o +- 💡 Solution Generation: Get detailed explanations and solutions with time/space complexity analysis +- 🔧 Real-time Debugging: Debug your code with AI assistance and structured feedback +- 🎨 Advanced Window Management: Freely move, resize, change opacity, and zoom the window +- 🔄 Model Selection: Choose between GPT-4o and GPT-4o-mini for different processing stages +- 🔒 Privacy-Focused: Your API key and data never leave your computer except for OpenAI API calls + +## Global Commands + +The application uses unidentifiable global keyboard shortcuts that won't be detected by browsers or other applications: + +- Toggle Window Visibility: [Control or Cmd + B] +- Move Window: [Control or Cmd + Arrow keys] +- Take Screenshot: [Control or Cmd + H] +- Delete Last Screenshot: [Control or Cmd + L] +- Process Screenshots: [Control or Cmd + Enter] +- Reset View: [Control or Cmd + R] +- Quit: [Control or Cmd + Q] +- Decrease Opacity: [Control or Cmd + [] +- Increase Opacity: [Control or Cmd + ]] +- Zoom Out: [Control or Cmd + -] +- Reset Zoom: [Control or Cmd + 0] +- Zoom In: [Control or Cmd + =] + +## Invisibility Compatibility + +The application is invisible to: + +- Zoom versions below 6.1.6 (inclusive) +- All browser-based screen recording software +- All versions of Discord +- Mac OS _screenshot_ functionality (Command + Shift + 3/4) + +Note: The application is **NOT** invisible to: + +- Zoom versions 6.1.6 and above + - https://zoom.en.uptodown.com/mac/versions (link to downgrade Zoom if needed) +- Mac OS native screen _recording_ (Command + Shift + 5) + +## Prerequisites + +- Node.js (v16 or higher) +- npm or bun package manager +- OpenAI API Key +- Screen Recording Permission for Terminal/IDE + - On macOS: + 1. Go to System Preferences > Security & Privacy > Privacy > Screen Recording + 2. Ensure that Interview Coder has screen recording permission enabled + 3. Restart Interview Coder after enabling permissions + - On Windows: + - No additional permissions needed + - On Linux: + - May require `xhost` access depending on your distribution + +## Installation + +1. Clone the repository: + +```bash +git clone https://github.com/yourusername/interview-coder-unlocked.git +cd interview-coder-unlocked +``` + +2. Install dependencies: + +```bash +npm install +# or if using bun +bun install +``` + +3. Start the application: + +```bash +npm run dev +``` + +4. Enter your OpenAI API key in the settings dialog when prompted. + +## Running in Production + +1. Build the application: + +```bash +npm run build +``` + +2. The built application will be in the `dist` directory. + +3. Alternatively, you can use the provided `stealth-run.bat` to quickly build and launch the application. + +## Tech Stack + +- Electron +- React +- TypeScript +- Vite +- Tailwind CSS +- Radix UI Components +- OpenAI API + +## How It Works + +1. **Initial Setup** + - Launch the invisible window + - Enter your OpenAI API key in the settings + - Choose your preferred model for extraction, solution generation, and debugging + +2. **Capturing Problem** + - Use global shortcut [Control or Cmd + H] to take screenshots of code problems + - Screenshots are automatically added to the queue of up to 2 + - If needed, remove the last screenshot with [Control or Cmd + L] + +3. **Processing** + - Press [Control or Cmd + Enter] to analyze the screenshots + - AI extracts problem requirements from the screenshots using GPT-4 Vision API + - The model generates an optimal solution based on the extracted information + - All analysis is done using your personal OpenAI API key + +4. **Solution & Debugging** + - View the generated solutions with detailed explanations + - Use debugging feature by taking more screenshots of error messages or code + - Get structured analysis with identified issues, corrections, and optimizations + - Toggle between solutions and queue views as needed + +5. **Window Management** + - Move window using [Control or Cmd + Arrow keys] + - Toggle visibility with [Control or Cmd + B] + - Adjust opacity with [Control or Cmd + [] and [Control or Cmd + ]] + - Window remains invisible to specified screen sharing applications + - Reset view using [Control or Cmd + R] + +## Configuration + +- **OpenAI API Key**: Your personal API key is stored locally and only used for API calls to OpenAI +- **Model Selection**: You can choose between GPT-4o and GPT-4o-mini for each stage of processing: + - Problem Extraction: Analyzes screenshots to understand the coding problem + - Solution Generation: Creates optimized solutions with explanations + - Debugging: Provides detailed analysis of errors and improvement suggestions +- **Language**: Select your preferred programming language for solutions +- **Window Controls**: Adjust opacity, position, and zoom level using keyboard shortcuts +- **All settings are stored locally** in your user data directory and persist between sessions + +## License + +This project is licensed under the GNU Affero General Public License v3.0 (AGPL-3.0). + +### What This Means + +- You are free to use, modify, and distribute this software +- If you modify the code, you must make your changes available under the same license +- If you run a modified version on a network server, you must make the source code available to users +- We strongly encourage you to contribute improvements back to the main project + +See the [LICENSE-SHORT](LICENSE-SHORT) file for a summary of terms or visit [GNU AGPL-3.0](https://www.gnu.org/licenses/agpl-3.0.html) for the full license text. + +### Contributing + +We welcome contributions! Please see our [Contributing Guidelines](CONTRIBUTING.md) for more information. diff --git a/assets/icons/mac/icon.icns b/assets/icons/mac/icon.icns new file mode 100644 index 0000000..9259728 Binary files /dev/null and b/assets/icons/mac/icon.icns differ diff --git a/assets/icons/win/icon.ico b/assets/icons/win/icon.ico new file mode 100644 index 0000000..842b66e Binary files /dev/null and b/assets/icons/win/icon.ico differ diff --git a/build/entitlements.mac.plist b/build/entitlements.mac.plist new file mode 100644 index 0000000..baa7baf --- /dev/null +++ b/build/entitlements.mac.plist @@ -0,0 +1,20 @@ + + + + + com.apple.security.cs.allow-jit + + com.apple.security.cs.allow-unsigned-executable-memory + + com.apple.security.cs.debugger + + com.apple.security.device.camera + + com.apple.security.device.microphone + + com.apple.security.files.user-selected.read-write + + com.apple.security.network.client + + + \ No newline at end of file diff --git a/bun.lockb b/bun.lockb new file mode 100644 index 0000000..7f7a2d4 Binary files /dev/null and b/bun.lockb differ diff --git a/cleanup-for-github.bat b/cleanup-for-github.bat new file mode 100644 index 0000000..fcf0cee --- /dev/null +++ b/cleanup-for-github.bat @@ -0,0 +1,28 @@ +@echo off +echo Cleaning up project for GitHub... + +echo Removing node_modules directory... +if exist node_modules rmdir /s /q node_modules + +echo Removing dist directory... +if exist dist rmdir /s /q dist + +echo Removing dist-electron directory... +if exist dist-electron rmdir /s /q dist-electron + +echo Removing release directory... +if exist release rmdir /s /q release + +echo Removing package-lock.json... +if exist package-lock.json del package-lock.json + +echo Removing any .env files... +if exist .env del .env +if exist .env.local del .env.local +if exist .env.development del .env.development +if exist .env.production del .env.production + +echo Cleanup complete! +echo Ready to commit to GitHub. +echo Run 'npm install' after cloning to install dependencies. +pause diff --git a/electron/ConfigHelper.ts b/electron/ConfigHelper.ts new file mode 100644 index 0000000..ba0d67c --- /dev/null +++ b/electron/ConfigHelper.ts @@ -0,0 +1,237 @@ +// ConfigHelper.ts +import fs from "node:fs" +import path from "node:path" +import { app } from "electron" +import { EventEmitter } from "events" +import { OpenAI } from "openai" + +interface Config { + apiKey: string; + extractionModel: string; + solutionModel: string; + debuggingModel: string; + language: string; + opacity: number; +} + +export class ConfigHelper extends EventEmitter { + private configPath: string; + private defaultConfig: Config = { + apiKey: "", + extractionModel: "gpt-4o", + solutionModel: "gpt-4o", + debuggingModel: "gpt-4o", + language: "python", + opacity: 1.0 + }; + + constructor() { + super(); + // Use the app's user data directory to store the config + try { + this.configPath = path.join(app.getPath('userData'), 'config.json'); + console.log('Config path:', this.configPath); + } catch (err) { + console.warn('Could not access user data path, using fallback'); + this.configPath = path.join(process.cwd(), 'config.json'); + } + + // Ensure the initial config file exists + this.ensureConfigExists(); + } + + /** + * Ensure config file exists + */ + private ensureConfigExists(): void { + try { + if (!fs.existsSync(this.configPath)) { + this.saveConfig(this.defaultConfig); + } + } catch (err) { + console.error("Error ensuring config exists:", err); + } + } + + /** + * Load the configuration from disk + */ + /** + * Validate and sanitize model selection to ensure only allowed models are used + */ + private sanitizeModelSelection(model: string): string { + // Only allow gpt-4o and gpt-4o-mini + const allowedModels = ['gpt-4o', 'gpt-4o-mini']; + if (!allowedModels.includes(model)) { + // Default to gpt-4o if an invalid model is specified + console.warn(`Invalid model specified: ${model}. Using default model: gpt-4o`); + return 'gpt-4o'; + } + return model; + } + + public loadConfig(): Config { + try { + if (fs.existsSync(this.configPath)) { + const configData = fs.readFileSync(this.configPath, 'utf8'); + const config = JSON.parse(configData); + + // Sanitize model selections to ensure only allowed models are used + if (config.extractionModel) { + config.extractionModel = this.sanitizeModelSelection(config.extractionModel); + } + if (config.solutionModel) { + config.solutionModel = this.sanitizeModelSelection(config.solutionModel); + } + if (config.debuggingModel) { + config.debuggingModel = this.sanitizeModelSelection(config.debuggingModel); + } + + return { + ...this.defaultConfig, + ...config + }; + } + + // If no config exists, create a default one + this.saveConfig(this.defaultConfig); + return this.defaultConfig; + } catch (err) { + console.error("Error loading config:", err); + return this.defaultConfig; + } + } + + /** + * Save configuration to disk + */ + public saveConfig(config: Config): void { + try { + // Ensure the directory exists + const configDir = path.dirname(this.configPath); + if (!fs.existsSync(configDir)) { + fs.mkdirSync(configDir, { recursive: true }); + } + // Write the config file + fs.writeFileSync(this.configPath, JSON.stringify(config, null, 2)); + } catch (err) { + console.error("Error saving config:", err); + } + } + + /** + * Update specific configuration values + */ + public updateConfig(updates: Partial): Config { + try { + const currentConfig = this.loadConfig(); + + // Sanitize model selections in the updates + if (updates.extractionModel) { + updates.extractionModel = this.sanitizeModelSelection(updates.extractionModel); + } + if (updates.solutionModel) { + updates.solutionModel = this.sanitizeModelSelection(updates.solutionModel); + } + if (updates.debuggingModel) { + updates.debuggingModel = this.sanitizeModelSelection(updates.debuggingModel); + } + + const newConfig = { ...currentConfig, ...updates }; + this.saveConfig(newConfig); + + // Only emit update event for changes other than opacity + // This prevents re-initializing the OpenAI client when only opacity changes + if (updates.apiKey !== undefined || updates.extractionModel !== undefined || + updates.solutionModel !== undefined || updates.debuggingModel !== undefined || + updates.language !== undefined) { + this.emit('config-updated', newConfig); + } + + return newConfig; + } catch (error) { + console.error('Error updating config:', error); + return this.defaultConfig; + } + } + + /** + * Check if the API key is configured + */ + public hasApiKey(): boolean { + const config = this.loadConfig(); + return !!config.apiKey && config.apiKey.trim().length > 0; + } + + /** + * Validate the API key format + */ + public isValidApiKeyFormat(apiKey: string): boolean { + // Basic format validation for OpenAI API keys + return /^sk-[a-zA-Z0-9]{32,}$/.test(apiKey.trim()); + } + + /** + * Get the stored opacity value + */ + public getOpacity(): number { + const config = this.loadConfig(); + return config.opacity !== undefined ? config.opacity : 1.0; + } + + /** + * Set the window opacity value + */ + public setOpacity(opacity: number): void { + // Ensure opacity is between 0.1 and 1.0 + const validOpacity = Math.min(1.0, Math.max(0.1, opacity)); + this.updateConfig({ opacity: validOpacity }); + } + + /** + * Get the preferred programming language + */ + public getLanguage(): string { + const config = this.loadConfig(); + return config.language || "python"; + } + + /** + * Set the preferred programming language + */ + public setLanguage(language: string): void { + this.updateConfig({ language }); + } + + /** + * Test API key with OpenAI + */ + public async testApiKey(apiKey: string): Promise<{valid: boolean, error?: string}> { + try { + const openai = new OpenAI({ apiKey }); + // Make a simple API call to test the key + await openai.models.list(); + return { valid: true }; + } catch (error: any) { + console.error('API key test failed:', error); + + // Determine the specific error type for better error messages + let errorMessage = 'Unknown error validating API key'; + + if (error.status === 401) { + errorMessage = 'Invalid API key. Please check your key and try again.'; + } else if (error.status === 429) { + errorMessage = 'Rate limit exceeded. Your API key has reached its request limit or has insufficient quota.'; + } else if (error.status === 500) { + errorMessage = 'OpenAI server error. Please try again later.'; + } else if (error.message) { + errorMessage = `Error: ${error.message}`; + } + + return { valid: false, error: errorMessage }; + } + } +} + +// Export a singleton instance +export const configHelper = new ConfigHelper(); \ No newline at end of file diff --git a/electron/ProcessingHelper.ts b/electron/ProcessingHelper.ts new file mode 100644 index 0000000..dd6e3b6 --- /dev/null +++ b/electron/ProcessingHelper.ts @@ -0,0 +1,780 @@ +// ProcessingHelper.ts +import fs from "node:fs" +import path from "node:path" +import { ScreenshotHelper } from "./ScreenshotHelper" +import { IProcessingHelperDeps } from "./main" +import * as axios from "axios" +import { app, BrowserWindow } from "electron" +import { OpenAI } from "openai" +import { configHelper } from "./ConfigHelper" + +export class ProcessingHelper { + private deps: IProcessingHelperDeps + private screenshotHelper: ScreenshotHelper + private openaiClient: OpenAI | null = null + + // AbortControllers for API requests + private currentProcessingAbortController: AbortController | null = null + private currentExtraProcessingAbortController: AbortController | null = null + + constructor(deps: IProcessingHelperDeps) { + this.deps = deps + this.screenshotHelper = deps.getScreenshotHelper() + + // Initialize OpenAI client + this.initializeOpenAIClient(); + + // Listen for config changes to re-initialize the OpenAI client + configHelper.on('config-updated', () => { + this.initializeOpenAIClient(); + }); + } + + /** + * Initialize or reinitialize the OpenAI client with current config + */ + private initializeOpenAIClient(): void { + try { + const config = configHelper.loadConfig(); + if (config.apiKey) { + this.openaiClient = new OpenAI({ + apiKey: config.apiKey, + timeout: 60000, // 60 second timeout + maxRetries: 2 // Retry up to 2 times + }); + console.log("OpenAI client initialized successfully"); + } else { + this.openaiClient = null; + console.warn("No API key available, OpenAI client not initialized"); + } + } catch (error) { + console.error("Failed to initialize OpenAI client:", error); + this.openaiClient = null; + } + } + + private async waitForInitialization( + mainWindow: BrowserWindow + ): Promise { + let attempts = 0 + const maxAttempts = 50 // 5 seconds total + + while (attempts < maxAttempts) { + const isInitialized = await mainWindow.webContents.executeJavaScript( + "window.__IS_INITIALIZED__" + ) + if (isInitialized) return + await new Promise((resolve) => setTimeout(resolve, 100)) + attempts++ + } + throw new Error("App failed to initialize after 5 seconds") + } + + private async getCredits(): Promise { + const mainWindow = this.deps.getMainWindow() + if (!mainWindow) return 999 // Unlimited credits in this version + + try { + await this.waitForInitialization(mainWindow) + return 999 // Always return sufficient credits to work + } catch (error) { + console.error("Error getting credits:", error) + return 999 // Unlimited credits as fallback + } + } + + private async getLanguage(): Promise { + try { + // Get language from config + const config = configHelper.loadConfig(); + if (config.language) { + return config.language; + } + + // Fallback to window variable if config doesn't have language + const mainWindow = this.deps.getMainWindow() + if (mainWindow) { + try { + await this.waitForInitialization(mainWindow) + const language = await mainWindow.webContents.executeJavaScript( + "window.__LANGUAGE__" + ) + + if ( + typeof language === "string" && + language !== undefined && + language !== null + ) { + return language; + } + } catch (err) { + console.warn("Could not get language from window", err); + } + } + + // Default fallback + return "python"; + } catch (error) { + console.error("Error getting language:", error) + return "python" + } + } + + public async processScreenshots(): Promise { + const mainWindow = this.deps.getMainWindow() + if (!mainWindow) return + + // First verify we have a valid OpenAI client + if (!this.openaiClient) { + this.initializeOpenAIClient(); + + if (!this.openaiClient) { + console.error("OpenAI client not initialized"); + mainWindow.webContents.send( + this.deps.PROCESSING_EVENTS.API_KEY_INVALID + ); + return; + } + } + + const view = this.deps.getView() + console.log("Processing screenshots in view:", view) + + if (view === "queue") { + mainWindow.webContents.send(this.deps.PROCESSING_EVENTS.INITIAL_START) + const screenshotQueue = this.screenshotHelper.getScreenshotQueue() + console.log("Processing main queue screenshots:", screenshotQueue) + if (screenshotQueue.length === 0) { + mainWindow.webContents.send(this.deps.PROCESSING_EVENTS.NO_SCREENSHOTS) + return + } + + try { + // Initialize AbortController + this.currentProcessingAbortController = new AbortController() + const { signal } = this.currentProcessingAbortController + + const screenshots = await Promise.all( + screenshotQueue.map(async (path) => ({ + path, + preview: await this.screenshotHelper.getImagePreview(path), + data: fs.readFileSync(path).toString('base64') + })) + ) + + const result = await this.processScreenshotsHelper(screenshots, signal) + + if (!result.success) { + console.log("Processing failed:", result.error) + if (result.error?.includes("API Key") || result.error?.includes("OpenAI")) { + mainWindow.webContents.send( + this.deps.PROCESSING_EVENTS.API_KEY_INVALID + ) + } else { + mainWindow.webContents.send( + this.deps.PROCESSING_EVENTS.INITIAL_SOLUTION_ERROR, + result.error + ) + } + // Reset view back to queue on error + console.log("Resetting view to queue due to error") + this.deps.setView("queue") + return + } + + // Only set view to solutions if processing succeeded + console.log("Setting view to solutions after successful processing") + mainWindow.webContents.send( + this.deps.PROCESSING_EVENTS.SOLUTION_SUCCESS, + result.data + ) + this.deps.setView("solutions") + } catch (error: any) { + mainWindow.webContents.send( + this.deps.PROCESSING_EVENTS.INITIAL_SOLUTION_ERROR, + error + ) + console.error("Processing error:", error) + if (axios.isCancel(error)) { + mainWindow.webContents.send( + this.deps.PROCESSING_EVENTS.INITIAL_SOLUTION_ERROR, + "Processing was canceled by the user." + ) + } else { + mainWindow.webContents.send( + this.deps.PROCESSING_EVENTS.INITIAL_SOLUTION_ERROR, + error.message || "Server error. Please try again." + ) + } + // Reset view back to queue on error + console.log("Resetting view to queue due to error") + this.deps.setView("queue") + } finally { + this.currentProcessingAbortController = null + } + } else { + // view == 'solutions' + const extraScreenshotQueue = + this.screenshotHelper.getExtraScreenshotQueue() + console.log("Processing extra queue screenshots:", extraScreenshotQueue) + if (extraScreenshotQueue.length === 0) { + mainWindow.webContents.send(this.deps.PROCESSING_EVENTS.NO_SCREENSHOTS) + return + } + mainWindow.webContents.send(this.deps.PROCESSING_EVENTS.DEBUG_START) + + // Initialize AbortController + this.currentExtraProcessingAbortController = new AbortController() + const { signal } = this.currentExtraProcessingAbortController + + try { + const screenshots = await Promise.all( + [ + ...this.screenshotHelper.getScreenshotQueue(), + ...extraScreenshotQueue + ].map(async (path) => ({ + path, + preview: await this.screenshotHelper.getImagePreview(path), + data: fs.readFileSync(path).toString('base64') + })) + ) + console.log( + "Combined screenshots for processing:", + screenshots.map((s) => s.path) + ) + + const result = await this.processExtraScreenshotsHelper( + screenshots, + signal + ) + + if (result.success) { + this.deps.setHasDebugged(true) + mainWindow.webContents.send( + this.deps.PROCESSING_EVENTS.DEBUG_SUCCESS, + result.data + ) + } else { + mainWindow.webContents.send( + this.deps.PROCESSING_EVENTS.DEBUG_ERROR, + result.error + ) + } + } catch (error: any) { + if (axios.isCancel(error)) { + mainWindow.webContents.send( + this.deps.PROCESSING_EVENTS.DEBUG_ERROR, + "Extra processing was canceled by the user." + ) + } else { + mainWindow.webContents.send( + this.deps.PROCESSING_EVENTS.DEBUG_ERROR, + error.message + ) + } + } finally { + this.currentExtraProcessingAbortController = null + } + } + } + + private async processScreenshotsHelper( + screenshots: Array<{ path: string; data: string }>, + signal: AbortSignal + ) { + try { + const config = configHelper.loadConfig(); + const language = await this.getLanguage(); + const mainWindow = this.deps.getMainWindow(); + + // Verify OpenAI client + if (!this.openaiClient) { + this.initializeOpenAIClient(); // Try to reinitialize + + if (!this.openaiClient) { + return { + success: false, + error: "OpenAI API key not configured or invalid. Please check your settings." + }; + } + } + + // Step 1: Extract problem info using OpenAI Vision API + const imageDataList = screenshots.map(screenshot => screenshot.data); + + // Update the user on progress + if (mainWindow) { + mainWindow.webContents.send("processing-status", { + message: "Analyzing problem from screenshots...", + progress: 20 + }); + } + + const messages = [ + { + role: "system" as const, + content: "You are a coding challenge interpreter. Analyze the screenshot of the coding problem and extract all relevant information. Return the information in JSON format with these fields: problem_statement, constraints, example_input, example_output. Just return the structured JSON without any other text." + }, + { + role: "user" as const, + content: [ + { + type: "text" as const, + text: `Extract the coding problem details from these screenshots. Return in JSON format. Preferred coding language we gonna use for this problem is ${language}.` + }, + ...imageDataList.map(data => ({ + type: "image_url" as const, + image_url: { url: `data:image/png;base64,${data}` } + })) + ] + } + ]; + + // Send to OpenAI Vision API + const extractionResponse = await this.openaiClient.chat.completions.create({ + model: config.extractionModel || "gpt-4o", + messages: messages, + max_tokens: 4000, + temperature: 0.2 + }); + + // Parse the response to get structured problem info + let problemInfo; + try { + const responseText = extractionResponse.choices[0].message.content; + // Handle when OpenAI might wrap the JSON in markdown code blocks + const jsonText = responseText.replace(/```json|```/g, '').trim(); + problemInfo = JSON.parse(jsonText); + + // Update the user on progress + if (mainWindow) { + mainWindow.webContents.send("processing-status", { + message: "Problem analyzed successfully. Preparing to generate solution...", + progress: 40 + }); + } + } catch (error) { + console.error("Error parsing problem extraction response:", error); + console.log("Raw response:", extractionResponse.choices[0].message.content); + return { + success: false, + error: "Failed to parse problem information. Please try again or use clearer screenshots." + }; + } + + // Store problem info in AppState + this.deps.setProblemInfo(problemInfo); + + // Send first success event + if (mainWindow) { + mainWindow.webContents.send( + this.deps.PROCESSING_EVENTS.PROBLEM_EXTRACTED, + problemInfo + ); + + // Generate solutions after successful extraction + const solutionsResult = await this.generateSolutionsHelper(signal); + if (solutionsResult.success) { + // Clear any existing extra screenshots before transitioning to solutions view + this.screenshotHelper.clearExtraScreenshotQueue(); + + // Final progress update + mainWindow.webContents.send("processing-status", { + message: "Solution generated successfully", + progress: 100 + }); + + mainWindow.webContents.send( + this.deps.PROCESSING_EVENTS.SOLUTION_SUCCESS, + solutionsResult.data + ); + return { success: true, data: solutionsResult.data }; + } else { + throw new Error( + solutionsResult.error || "Failed to generate solutions" + ); + } + } + + return { success: false, error: "Failed to process screenshots" }; + } catch (error: any) { + // If the request was cancelled, don't retry + if (axios.isCancel(error)) { + return { + success: false, + error: "Processing was canceled by the user." + }; + } + + // Handle OpenAI API errors specifically + if (error?.response?.status === 401) { + return { + success: false, + error: "Invalid OpenAI API key. Please check your settings." + }; + } else if (error?.response?.status === 429) { + return { + success: false, + error: "OpenAI API rate limit exceeded or insufficient credits. Please try again later." + }; + } else if (error?.response?.status === 500) { + return { + success: false, + error: "OpenAI server error. Please try again later." + }; + } + + console.error("API Error Details:", error); + return { + success: false, + error: error.message || "Failed to process screenshots. Please try again." + }; + } + } + + private async generateSolutionsHelper(signal: AbortSignal) { + try { + const problemInfo = this.deps.getProblemInfo(); + const language = await this.getLanguage(); + const config = configHelper.loadConfig(); + const mainWindow = this.deps.getMainWindow(); + + if (!problemInfo) { + throw new Error("No problem info available"); + } + + if (!this.openaiClient) { + return { + success: false, + error: "OpenAI API key not configured. Please check your settings." + }; + } + + // Update progress status + if (mainWindow) { + mainWindow.webContents.send("processing-status", { + message: "Creating optimal solution with detailed explanations...", + progress: 60 + }); + } + + // Create prompt for solution generation + const promptText = ` +Generate a detailed solution for the following coding problem: + +PROBLEM STATEMENT: +${problemInfo.problem_statement} + +CONSTRAINTS: +${problemInfo.constraints || "No specific constraints provided."} + +EXAMPLE INPUT: +${problemInfo.example_input || "No example input provided."} + +EXAMPLE OUTPUT: +${problemInfo.example_output || "No example output provided."} + +LANGUAGE: ${language} + +I need the response in the following format: +1. Code: A clean, optimized implementation in ${language} +2. Your Thoughts: A list of key insights and reasoning behind your approach +3. Time complexity: O(X) with a detailed explanation (at least 2 sentences) +4. Space complexity: O(X) with a detailed explanation (at least 2 sentences) + +For complexity explanations, please be thorough. For example: "Time complexity: O(n) because we iterate through the array only once. This is optimal as we need to examine each element at least once to find the solution." or "Space complexity: O(n) because in the worst case, we store all elements in the hashmap. The additional space scales linearly with the input size." + +Your solution should be efficient, well-commented, and handle edge cases. +`; + + // Send to OpenAI API + const solutionResponse = await this.openaiClient.chat.completions.create({ + model: config.solutionModel || "gpt-4o", // Using selected model for code generation + messages: [ + { role: "system", content: "You are an expert coding interview assistant. Provide clear, optimal solutions with detailed explanations." }, + { role: "user", content: promptText } + ], + max_tokens: 4000, + temperature: 0.2 + }); + + const responseContent = solutionResponse.choices[0].message.content; + + // Extract parts from the response + const codeMatch = responseContent.match(/```(?:\w+)?\s*([\s\S]*?)```/); + const code = codeMatch ? codeMatch[1].trim() : responseContent; + + // Extract thoughts, looking for bullet points or numbered lists + const thoughtsRegex = /(?:Thoughts:|Key Insights:|Reasoning:|Approach:)([\s\S]*?)(?:Time complexity:|$)/i; + const thoughtsMatch = responseContent.match(thoughtsRegex); + let thoughts: string[] = []; + + if (thoughtsMatch && thoughtsMatch[1]) { + // Extract bullet points or numbered items + const bulletPoints = thoughtsMatch[1].match(/(?:^|\n)\s*(?:[-*•]|\d+\.)\s*(.*)/g); + if (bulletPoints) { + thoughts = bulletPoints.map(point => + point.replace(/^\s*(?:[-*•]|\d+\.)\s*/, '').trim() + ).filter(Boolean); + } else { + // If no bullet points found, split by newlines and filter empty lines + thoughts = thoughtsMatch[1].split('\n') + .map(line => line.trim()) + .filter(Boolean); + } + } + + // Extract complexity information + // Use more flexible patterns to find complexity sections + const timeComplexityPattern = /Time complexity:?\s*([^\n]+(?:\n[^\n]+)*?)(?=\n\s*(?:Space complexity|$))/i; + const spaceComplexityPattern = /Space complexity:?\s*([^\n]+(?:\n[^\n]+)*?)(?=\n\s*(?:[A-Z]|$))/i; + + let timeComplexity = "O(n) - Linear time complexity because we only iterate through the array once. Each element is processed exactly one time, and the hashmap lookups are O(1) operations."; + let spaceComplexity = "O(n) - Linear space complexity because we store elements in the hashmap. In the worst case, we might need to store all elements before finding the solution pair."; + + // Extract time complexity with better matching + const timeMatch = responseContent.match(timeComplexityPattern); + if (timeMatch && timeMatch[1]) { + timeComplexity = timeMatch[1].trim(); + // Ensure the response includes actual Big O notation and a dash + if (!timeComplexity.match(/O\([^)]+\)/i)) { + timeComplexity = `O(n) - ${timeComplexity}`; + } else if (!timeComplexity.includes('-') && !timeComplexity.includes('because')) { + // Add a dash if there isn't one and no 'because' + const notationMatch = timeComplexity.match(/O\([^)]+\)/i); + if (notationMatch) { + const notation = notationMatch[0]; + const rest = timeComplexity.replace(notation, '').trim(); + timeComplexity = `${notation} - ${rest}`; + } + } + } + + // Extract space complexity with better matching + const spaceMatch = responseContent.match(spaceComplexityPattern); + if (spaceMatch && spaceMatch[1]) { + spaceComplexity = spaceMatch[1].trim(); + // Ensure the response includes actual Big O notation and a dash + if (!spaceComplexity.match(/O\([^)]+\)/i)) { + spaceComplexity = `O(n) - ${spaceComplexity}`; + } else if (!spaceComplexity.includes('-') && !spaceComplexity.includes('because')) { + // Add a dash if there isn't one and no 'because' + const notationMatch = spaceComplexity.match(/O\([^)]+\)/i); + if (notationMatch) { + const notation = notationMatch[0]; + const rest = spaceComplexity.replace(notation, '').trim(); + spaceComplexity = `${notation} - ${rest}`; + } + } + } + + // Construct the formatted response + const formattedResponse = { + code: code, + thoughts: thoughts.length > 0 ? thoughts : ["Solution approach based on efficiency and readability"], + time_complexity: timeComplexity, + space_complexity: spaceComplexity + }; + + return { success: true, data: formattedResponse }; + } catch (error: any) { + // Handle OpenAI API errors specifically + if (error?.response?.status === 401) { + return { + success: false, + error: "Invalid OpenAI API key. Please check your settings." + }; + } else if (error?.response?.status === 429) { + return { + success: false, + error: "OpenAI API rate limit exceeded or insufficient credits. Please try again later." + }; + } + + console.error("Solution generation error:", error); + return { success: false, error: error.message || "Failed to generate solution" }; + } + } + + private async processExtraScreenshotsHelper( + screenshots: Array<{ path: string; data: string }>, + signal: AbortSignal + ) { + try { + const problemInfo = this.deps.getProblemInfo(); + const language = await this.getLanguage(); + const config = configHelper.loadConfig(); + const mainWindow = this.deps.getMainWindow(); + + if (!problemInfo) { + throw new Error("No problem info available"); + } + + if (!this.openaiClient) { + return { + success: false, + error: "OpenAI API key not configured. Please check your settings." + }; + } + + // Update progress status + if (mainWindow) { + mainWindow.webContents.send("processing-status", { + message: "Processing debug screenshots...", + progress: 30 + }); + } + + // Prepare the images for the API call + const imageDataList = screenshots.map(screenshot => screenshot.data); + const messages = [ + { + role: "system" as const, + content: `You are a coding interview assistant helping debug and improve solutions. Analyze these screenshots which include either error messages, incorrect outputs, or test cases, and provide detailed debugging help. + +Your response MUST follow this exact structure with these section headers (use ### for headers): +### Issues Identified +- List each issue as a bullet point with clear explanation + +### Specific Improvements and Corrections +- List specific code changes needed as bullet points + +### Optimizations +- List any performance optimizations if applicable + +### Explanation of Changes Needed +Here provide a clear explanation of why the changes are needed + +### Key Points +- Summary bullet points of the most important takeaways + +If you include code examples, use proper markdown code blocks with language specification (e.g. \`\`\`java).` + }, + { + role: "user" as const, + content: [ + { + type: "text" as const, + text: `I'm solving this coding problem: "${problemInfo.problem_statement}" in ${language}. I need help with debugging or improving my solution. Here are screenshots of my code, the errors or test cases. Please provide a detailed analysis with: +1. What issues you found in my code +2. Specific improvements and corrections +3. Any optimizations that would make the solution better +4. A clear explanation of the changes needed` + }, + ...imageDataList.map(data => ({ + type: "image_url" as const, + image_url: { url: `data:image/png;base64,${data}` } + })) + ] + } + ]; + + // Update progress + if (mainWindow) { + mainWindow.webContents.send("processing-status", { + message: "Analyzing code and generating debug feedback...", + progress: 60 + }); + } + + // Send to OpenAI Vision API + const debugResponse = await this.openaiClient.chat.completions.create({ + model: config.debuggingModel || "gpt-4o", + messages: messages, + max_tokens: 4000, + temperature: 0.2 + }); + + // Update final progress + if (mainWindow) { + mainWindow.webContents.send("processing-status", { + message: "Debug analysis complete", + progress: 100 + }); + } + + // Extract and format the debug response + const debugContent = debugResponse.choices[0].message.content; + + // Extract code if there's code block in the response + let extractedCode = "// Debug mode - see analysis below"; + const codeMatch = debugContent.match(/```(?:[a-zA-Z]+)?([\s\S]*?)```/); + if (codeMatch && codeMatch[1]) { + extractedCode = codeMatch[1].trim(); + } + + // Format the debug content for better display - add clear section headings + let formattedDebugContent = debugContent; + + // Ensure proper section formatting + if (!debugContent.includes('# ') && !debugContent.includes('## ')) { + formattedDebugContent = debugContent + .replace(/issues identified|problems found|bugs found/i, '## Issues Identified') + .replace(/code improvements|improvements|suggested changes/i, '## Code Improvements') + .replace(/optimizations|performance improvements/i, '## Optimizations') + .replace(/explanation|detailed analysis/i, '## Explanation'); + } + + // Try to extract bullet points for "thoughts" + const bulletPoints = formattedDebugContent.match(/(?:^|\n)[ ]*(?:[-*•]|\d+\.)[ ]+([^\n]+)/g); + const thoughts = bulletPoints + ? bulletPoints.map(point => point.replace(/^[ ]*(?:[-*•]|\d+\.)[ ]+/, '').trim()).slice(0, 5) + : ["Debug analysis based on your screenshots"]; + + // Return the debug assistance in the format expected by the app + const response = { + code: extractedCode, + debug_analysis: formattedDebugContent, + thoughts: thoughts, + time_complexity: "N/A - Debug mode", + space_complexity: "N/A - Debug mode" + }; + + return { success: true, data: response }; + } catch (error: any) { + // Handle OpenAI API errors specifically + if (error?.response?.status === 401) { + return { + success: false, + error: "Invalid OpenAI API key. Please check your settings." + }; + } else if (error?.response?.status === 429) { + return { + success: false, + error: "OpenAI API rate limit exceeded or insufficient credits. Please try again later." + }; + } + + console.error("Debug processing error:", error); + return { success: false, error: error.message || "Failed to process debug request" }; + } + } + + public cancelOngoingRequests(): void { + let wasCancelled = false + + if (this.currentProcessingAbortController) { + this.currentProcessingAbortController.abort() + this.currentProcessingAbortController = null + wasCancelled = true + } + + if (this.currentExtraProcessingAbortController) { + this.currentExtraProcessingAbortController.abort() + this.currentExtraProcessingAbortController = null + wasCancelled = true + } + + // Reset hasDebugged flag + this.deps.setHasDebugged(false) + + // Clear any pending state + this.deps.setProblemInfo(null) + + const mainWindow = this.deps.getMainWindow() + if (wasCancelled && mainWindow && !mainWindow.isDestroyed()) { + // Send a clear message that processing was cancelled + mainWindow.webContents.send(this.deps.PROCESSING_EVENTS.NO_SCREENSHOTS) + } + } +} \ No newline at end of file diff --git a/electron/ScreenshotHelper.ts b/electron/ScreenshotHelper.ts new file mode 100644 index 0000000..aee6818 --- /dev/null +++ b/electron/ScreenshotHelper.ts @@ -0,0 +1,221 @@ +// ScreenshotHelper.ts + +import path from "node:path" +import fs from "node:fs" +import { app } from "electron" +import { v4 as uuidv4 } from "uuid" +import { execFile } from "child_process" +import { promisify } from "util" +import screenshot from "screenshot-desktop" + +const execFileAsync = promisify(execFile) + +export class ScreenshotHelper { + private screenshotQueue: string[] = [] + private extraScreenshotQueue: string[] = [] + private readonly MAX_SCREENSHOTS = 5 + + private readonly screenshotDir: string + private readonly extraScreenshotDir: string + + private view: "queue" | "solutions" | "debug" = "queue" + + constructor(view: "queue" | "solutions" | "debug" = "queue") { + this.view = view + + // Initialize directories + this.screenshotDir = path.join(app.getPath("userData"), "screenshots") + this.extraScreenshotDir = path.join( + app.getPath("userData"), + "extra_screenshots" + ) + + // Create directories if they don't exist + if (!fs.existsSync(this.screenshotDir)) { + fs.mkdirSync(this.screenshotDir, { recursive: true }) + } + if (!fs.existsSync(this.extraScreenshotDir)) { + fs.mkdirSync(this.extraScreenshotDir, { recursive: true }) + } + + // Ensure temp directory exists + const tempDir = app.getPath("temp") + if (!fs.existsSync(tempDir)) { + fs.mkdirSync(tempDir, { recursive: true }) + } + } + + public getView(): "queue" | "solutions" | "debug" { + return this.view + } + + public setView(view: "queue" | "solutions" | "debug"): void { + console.log("Setting view in ScreenshotHelper:", view) + console.log( + "Current queues - Main:", + this.screenshotQueue, + "Extra:", + this.extraScreenshotQueue + ) + this.view = view + } + + public getScreenshotQueue(): string[] { + return this.screenshotQueue + } + + public getExtraScreenshotQueue(): string[] { + console.log("Getting extra screenshot queue:", this.extraScreenshotQueue) + return this.extraScreenshotQueue + } + + public clearQueues(): void { + // Clear screenshotQueue + this.screenshotQueue.forEach((screenshotPath) => { + fs.unlink(screenshotPath, (err) => { + if (err) + console.error(`Error deleting screenshot at ${screenshotPath}:`, err) + }) + }) + this.screenshotQueue = [] + + // Clear extraScreenshotQueue + this.extraScreenshotQueue.forEach((screenshotPath) => { + fs.unlink(screenshotPath, (err) => { + if (err) + console.error( + `Error deleting extra screenshot at ${screenshotPath}:`, + err + ) + }) + }) + this.extraScreenshotQueue = [] + } + + private async captureScreenshot(): Promise { + try { + // Ensure temp directory exists + const tempDir = app.getPath("temp") + if (!fs.existsSync(tempDir)) { + fs.mkdirSync(tempDir, { recursive: true }) + } + + // Use screenshot-desktop for cross-platform support + const buffer = await screenshot({ format: 'png' }); + return buffer; + } catch (error) { + console.error("Error capturing screenshot:", error); + throw error; + } + } + + public async takeScreenshot( + hideMainWindow: () => void, + showMainWindow: () => void + ): Promise { + console.log("Taking screenshot in view:", this.view) + hideMainWindow() + await new Promise((resolve) => setTimeout(resolve, 100)) + + let screenshotPath = "" + try { + // Get screenshot buffer using cross-platform method + const screenshotBuffer = await this.captureScreenshot(); + + // Save and manage the screenshot based on current view + if (this.view === "queue") { + screenshotPath = path.join(this.screenshotDir, `${uuidv4()}.png`) + await fs.promises.writeFile(screenshotPath, screenshotBuffer) + console.log("Adding screenshot to main queue:", screenshotPath) + this.screenshotQueue.push(screenshotPath) + if (this.screenshotQueue.length > this.MAX_SCREENSHOTS) { + const removedPath = this.screenshotQueue.shift() + if (removedPath) { + try { + await fs.promises.unlink(removedPath) + console.log( + "Removed old screenshot from main queue:", + removedPath + ) + } catch (error) { + console.error("Error removing old screenshot:", error) + } + } + } + } else { + // In solutions view, only add to extra queue + screenshotPath = path.join(this.extraScreenshotDir, `${uuidv4()}.png`) + await fs.promises.writeFile(screenshotPath, screenshotBuffer) + console.log("Adding screenshot to extra queue:", screenshotPath) + this.extraScreenshotQueue.push(screenshotPath) + if (this.extraScreenshotQueue.length > this.MAX_SCREENSHOTS) { + const removedPath = this.extraScreenshotQueue.shift() + if (removedPath) { + try { + await fs.promises.unlink(removedPath) + console.log( + "Removed old screenshot from extra queue:", + removedPath + ) + } catch (error) { + console.error("Error removing old screenshot:", error) + } + } + } + } + } catch (error) { + console.error("Screenshot error:", error) + throw error + } finally { + await new Promise((resolve) => setTimeout(resolve, 50)) + showMainWindow() + } + + return screenshotPath + } + + public async getImagePreview(filepath: string): Promise { + try { + const data = await fs.promises.readFile(filepath) + return `data:image/png;base64,${data.toString("base64")}` + } catch (error) { + console.error("Error reading image:", error) + throw error + } + } + + public async deleteScreenshot( + path: string + ): Promise<{ success: boolean; error?: string }> { + try { + await fs.promises.unlink(path) + if (this.view === "queue") { + this.screenshotQueue = this.screenshotQueue.filter( + (filePath) => filePath !== path + ) + } else { + this.extraScreenshotQueue = this.extraScreenshotQueue.filter( + (filePath) => filePath !== path + ) + } + return { success: true } + } catch (error) { + console.error("Error deleting file:", error) + return { success: false, error: error.message } + } + } + + public clearExtraScreenshotQueue(): void { + // Clear extraScreenshotQueue + this.extraScreenshotQueue.forEach((screenshotPath) => { + fs.unlink(screenshotPath, (err) => { + if (err) + console.error( + `Error deleting extra screenshot at ${screenshotPath}:`, + err + ) + }) + }) + this.extraScreenshotQueue = [] + } +} diff --git a/electron/autoUpdater.ts b/electron/autoUpdater.ts new file mode 100644 index 0000000..d71fde3 --- /dev/null +++ b/electron/autoUpdater.ts @@ -0,0 +1,109 @@ +import { autoUpdater } from "electron-updater" +import { BrowserWindow, ipcMain, app } from "electron" +import log from "electron-log" + +export function initAutoUpdater() { + console.log("Initializing auto-updater...") + + // Skip update checks in development + if (!app.isPackaged) { + console.log("Skipping auto-updater in development mode") + return + } + + if (!process.env.GH_TOKEN) { + console.error("GH_TOKEN environment variable is not set") + return + } + + // Configure auto updater + autoUpdater.autoDownload = true + autoUpdater.autoInstallOnAppQuit = true + autoUpdater.allowDowngrade = true + autoUpdater.allowPrerelease = true + + // Enable more verbose logging + autoUpdater.logger = log + log.transports.file.level = "debug" + console.log( + "Auto-updater logger configured with level:", + log.transports.file.level + ) + + // Log all update events + autoUpdater.on("checking-for-update", () => { + console.log("Checking for updates...") + }) + + autoUpdater.on("update-available", (info) => { + console.log("Update available:", info) + // Notify renderer process about available update + BrowserWindow.getAllWindows().forEach((window) => { + console.log("Sending update-available to window") + window.webContents.send("update-available", info) + }) + }) + + autoUpdater.on("update-not-available", (info) => { + console.log("Update not available:", info) + }) + + autoUpdater.on("download-progress", (progressObj) => { + console.log("Download progress:", progressObj) + }) + + autoUpdater.on("update-downloaded", (info) => { + console.log("Update downloaded:", info) + // Notify renderer process that update is ready to install + BrowserWindow.getAllWindows().forEach((window) => { + console.log("Sending update-downloaded to window") + window.webContents.send("update-downloaded", info) + }) + }) + + autoUpdater.on("error", (err) => { + console.error("Auto updater error:", err) + }) + + // Check for updates immediately + console.log("Checking for updates...") + autoUpdater + .checkForUpdates() + .then((result) => { + console.log("Update check result:", result) + }) + .catch((err) => { + console.error("Error checking for updates:", err) + }) + + // Set up update checking interval (every 1 hour) + setInterval(() => { + console.log("Checking for updates (interval)...") + autoUpdater + .checkForUpdates() + .then((result) => { + console.log("Update check result (interval):", result) + }) + .catch((err) => { + console.error("Error checking for updates (interval):", err) + }) + }, 60 * 60 * 1000) + + // Handle IPC messages from renderer + ipcMain.handle("start-update", async () => { + console.log("Start update requested") + try { + await autoUpdater.downloadUpdate() + console.log("Update download completed") + return { success: true } + } catch (error) { + console.error("Failed to start update:", error) + return { success: false, error: error.message } + } + }) + + ipcMain.handle("install-update", () => { + console.log("Install update requested") + autoUpdater.quitAndInstall() + }) +} diff --git a/electron/ipcHandlers.ts b/electron/ipcHandlers.ts new file mode 100644 index 0000000..f05a9ae --- /dev/null +++ b/electron/ipcHandlers.ts @@ -0,0 +1,351 @@ +// ipcHandlers.ts + +import { ipcMain, shell, dialog } from "electron" +import { randomBytes } from "crypto" +import { IIpcHandlerDeps } from "./main" +import { configHelper } from "./ConfigHelper" + +export function initializeIpcHandlers(deps: IIpcHandlerDeps): void { + console.log("Initializing IPC handlers") + + // Configuration handlers + ipcMain.handle("get-config", () => { + return configHelper.loadConfig(); + }) + + ipcMain.handle("update-config", (_event, updates) => { + return configHelper.updateConfig(updates); + }) + + ipcMain.handle("check-api-key", () => { + return configHelper.hasApiKey(); + }) + + ipcMain.handle("validate-api-key", async (_event, apiKey) => { + // First check the format + if (!configHelper.isValidApiKeyFormat(apiKey)) { + return { + valid: false, + error: "Invalid API key format. OpenAI API keys start with 'sk-'" + }; + } + + // Then test the API key with OpenAI + const result = await configHelper.testApiKey(apiKey); + return result; + }) + + // Credits handlers + ipcMain.handle("set-initial-credits", async (_event, credits: number) => { + const mainWindow = deps.getMainWindow() + if (!mainWindow) return + + try { + // Set the credits in a way that ensures atomicity + await mainWindow.webContents.executeJavaScript( + `window.__CREDITS__ = ${credits}` + ) + mainWindow.webContents.send("credits-updated", credits) + } catch (error) { + console.error("Error setting initial credits:", error) + throw error + } + }) + + ipcMain.handle("decrement-credits", async () => { + const mainWindow = deps.getMainWindow() + if (!mainWindow) return + + try { + const currentCredits = await mainWindow.webContents.executeJavaScript( + "window.__CREDITS__" + ) + if (currentCredits > 0) { + const newCredits = currentCredits - 1 + await mainWindow.webContents.executeJavaScript( + `window.__CREDITS__ = ${newCredits}` + ) + mainWindow.webContents.send("credits-updated", newCredits) + } + } catch (error) { + console.error("Error decrementing credits:", error) + } + }) + + // Screenshot queue handlers + ipcMain.handle("get-screenshot-queue", () => { + return deps.getScreenshotQueue() + }) + + ipcMain.handle("get-extra-screenshot-queue", () => { + return deps.getExtraScreenshotQueue() + }) + + ipcMain.handle("delete-screenshot", async (event, path: string) => { + return deps.deleteScreenshot(path) + }) + + ipcMain.handle("get-image-preview", async (event, path: string) => { + return deps.getImagePreview(path) + }) + + // Screenshot processing handlers + ipcMain.handle("process-screenshots", async () => { + // Check for API key before processing + if (!configHelper.hasApiKey()) { + const mainWindow = deps.getMainWindow(); + if (mainWindow) { + mainWindow.webContents.send(deps.PROCESSING_EVENTS.API_KEY_INVALID); + } + return; + } + + await deps.processingHelper?.processScreenshots() + }) + + // Window dimension handlers + ipcMain.handle( + "update-content-dimensions", + async (event, { width, height }: { width: number; height: number }) => { + if (width && height) { + deps.setWindowDimensions(width, height) + } + } + ) + + ipcMain.handle( + "set-window-dimensions", + (event, width: number, height: number) => { + deps.setWindowDimensions(width, height) + } + ) + + // Screenshot management handlers + ipcMain.handle("get-screenshots", async () => { + try { + let previews = [] + const currentView = deps.getView() + + if (currentView === "queue") { + const queue = deps.getScreenshotQueue() + previews = await Promise.all( + queue.map(async (path) => ({ + path, + preview: await deps.getImagePreview(path) + })) + ) + } else { + const extraQueue = deps.getExtraScreenshotQueue() + previews = await Promise.all( + extraQueue.map(async (path) => ({ + path, + preview: await deps.getImagePreview(path) + })) + ) + } + + return previews + } catch (error) { + console.error("Error getting screenshots:", error) + throw error + } + }) + + // Screenshot trigger handlers + ipcMain.handle("trigger-screenshot", async () => { + const mainWindow = deps.getMainWindow() + if (mainWindow) { + try { + const screenshotPath = await deps.takeScreenshot() + const preview = await deps.getImagePreview(screenshotPath) + mainWindow.webContents.send("screenshot-taken", { + path: screenshotPath, + preview + }) + return { success: true } + } catch (error) { + console.error("Error triggering screenshot:", error) + return { error: "Failed to trigger screenshot" } + } + } + return { error: "No main window available" } + }) + + ipcMain.handle("take-screenshot", async () => { + try { + const screenshotPath = await deps.takeScreenshot() + const preview = await deps.getImagePreview(screenshotPath) + return { path: screenshotPath, preview } + } catch (error) { + console.error("Error taking screenshot:", error) + return { error: "Failed to take screenshot" } + } + }) + + // Auth-related handlers removed + + ipcMain.handle("open-external-url", (event, url: string) => { + shell.openExternal(url) + }) + + // Open external URL handler + ipcMain.handle("openLink", (event, url: string) => { + try { + console.log(`Opening external URL: ${url}`); + shell.openExternal(url); + return { success: true }; + } catch (error) { + console.error(`Error opening URL ${url}:`, error); + return { success: false, error: `Failed to open URL: ${error}` }; + } + }) + + // Settings portal handler + ipcMain.handle("open-settings-portal", () => { + const mainWindow = deps.getMainWindow(); + if (mainWindow) { + mainWindow.webContents.send("show-settings-dialog"); + return { success: true }; + } + return { success: false, error: "Main window not available" }; + }) + + // Window management handlers + ipcMain.handle("toggle-window", () => { + try { + deps.toggleMainWindow() + return { success: true } + } catch (error) { + console.error("Error toggling window:", error) + return { error: "Failed to toggle window" } + } + }) + + ipcMain.handle("reset-queues", async () => { + try { + deps.clearQueues() + return { success: true } + } catch (error) { + console.error("Error resetting queues:", error) + return { error: "Failed to reset queues" } + } + }) + + // Process screenshot handlers + ipcMain.handle("trigger-process-screenshots", async () => { + try { + // Check for API key before processing + if (!configHelper.hasApiKey()) { + const mainWindow = deps.getMainWindow(); + if (mainWindow) { + mainWindow.webContents.send(deps.PROCESSING_EVENTS.API_KEY_INVALID); + } + return { success: false, error: "API key required" }; + } + + await deps.processingHelper?.processScreenshots() + return { success: true } + } catch (error) { + console.error("Error processing screenshots:", error) + return { error: "Failed to process screenshots" } + } + }) + + // Reset handlers + ipcMain.handle("trigger-reset", () => { + try { + // First cancel any ongoing requests + deps.processingHelper?.cancelOngoingRequests() + + // Clear all queues immediately + deps.clearQueues() + + // Reset view to queue + deps.setView("queue") + + // Get main window and send reset events + const mainWindow = deps.getMainWindow() + if (mainWindow && !mainWindow.isDestroyed()) { + // Send reset events in sequence + mainWindow.webContents.send("reset-view") + mainWindow.webContents.send("reset") + } + + return { success: true } + } catch (error) { + console.error("Error triggering reset:", error) + return { error: "Failed to trigger reset" } + } + }) + + // Window movement handlers + ipcMain.handle("trigger-move-left", () => { + try { + deps.moveWindowLeft() + return { success: true } + } catch (error) { + console.error("Error moving window left:", error) + return { error: "Failed to move window left" } + } + }) + + ipcMain.handle("trigger-move-right", () => { + try { + deps.moveWindowRight() + return { success: true } + } catch (error) { + console.error("Error moving window right:", error) + return { error: "Failed to move window right" } + } + }) + + ipcMain.handle("trigger-move-up", () => { + try { + deps.moveWindowUp() + return { success: true } + } catch (error) { + console.error("Error moving window up:", error) + return { error: "Failed to move window up" } + } + }) + + ipcMain.handle("trigger-move-down", () => { + try { + deps.moveWindowDown() + return { success: true } + } catch (error) { + console.error("Error moving window down:", error) + return { error: "Failed to move window down" } + } + }) + + // Delete last screenshot handler + ipcMain.handle("delete-last-screenshot", async () => { + try { + const queue = deps.getView() === "queue" + ? deps.getScreenshotQueue() + : deps.getExtraScreenshotQueue() + + if (queue.length === 0) { + return { success: false, error: "No screenshots to delete" } + } + + // Get the last screenshot in the queue + const lastScreenshot = queue[queue.length - 1] + + // Delete it + const result = await deps.deleteScreenshot(lastScreenshot) + + // Notify the renderer about the change + const mainWindow = deps.getMainWindow() + if (mainWindow && !mainWindow.isDestroyed()) { + mainWindow.webContents.send("screenshot-deleted", { path: lastScreenshot }) + } + + return result + } catch (error) { + console.error("Error deleting last screenshot:", error) + return { success: false, error: "Failed to delete last screenshot" } + } + }) +} diff --git a/electron/main.ts b/electron/main.ts new file mode 100644 index 0000000..38603f2 --- /dev/null +++ b/electron/main.ts @@ -0,0 +1,712 @@ +import { app, BrowserWindow, screen, shell, ipcMain } from "electron" +import path from "path" +import fs from "fs" +import { initializeIpcHandlers } from "./ipcHandlers" +import { ProcessingHelper } from "./ProcessingHelper" +import { ScreenshotHelper } from "./ScreenshotHelper" +import { ShortcutsHelper } from "./shortcuts" +import { initAutoUpdater } from "./autoUpdater" +import { configHelper } from "./ConfigHelper" +import * as dotenv from "dotenv" + +// Constants +const isDev = process.env.NODE_ENV === "development" + +// Application State +const state = { + // Window management properties + mainWindow: null as BrowserWindow | null, + isWindowVisible: false, + windowPosition: null as { x: number; y: number } | null, + windowSize: null as { width: number; height: number } | null, + screenWidth: 0, + screenHeight: 0, + step: 0, + currentX: 0, + currentY: 0, + + // Application helpers + screenshotHelper: null as ScreenshotHelper | null, + shortcutsHelper: null as ShortcutsHelper | null, + processingHelper: null as ProcessingHelper | null, + + // View and state management + view: "queue" as "queue" | "solutions" | "debug", + problemInfo: null as any, + hasDebugged: false, + + // Processing events + PROCESSING_EVENTS: { + UNAUTHORIZED: "processing-unauthorized", + NO_SCREENSHOTS: "processing-no-screenshots", + OUT_OF_CREDITS: "out-of-credits", + API_KEY_INVALID: "api-key-invalid", + INITIAL_START: "initial-start", + PROBLEM_EXTRACTED: "problem-extracted", + SOLUTION_SUCCESS: "solution-success", + INITIAL_SOLUTION_ERROR: "solution-error", + DEBUG_START: "debug-start", + DEBUG_SUCCESS: "debug-success", + DEBUG_ERROR: "debug-error" + } as const +} + +// Add interfaces for helper classes +export interface IProcessingHelperDeps { + getScreenshotHelper: () => ScreenshotHelper | null + getMainWindow: () => BrowserWindow | null + getView: () => "queue" | "solutions" | "debug" + setView: (view: "queue" | "solutions" | "debug") => void + getProblemInfo: () => any + setProblemInfo: (info: any) => void + getScreenshotQueue: () => string[] + getExtraScreenshotQueue: () => string[] + clearQueues: () => void + takeScreenshot: () => Promise + getImagePreview: (filepath: string) => Promise + deleteScreenshot: ( + path: string + ) => Promise<{ success: boolean; error?: string }> + setHasDebugged: (value: boolean) => void + getHasDebugged: () => boolean + PROCESSING_EVENTS: typeof state.PROCESSING_EVENTS +} + +export interface IShortcutsHelperDeps { + getMainWindow: () => BrowserWindow | null + takeScreenshot: () => Promise + getImagePreview: (filepath: string) => Promise + processingHelper: ProcessingHelper | null + clearQueues: () => void + setView: (view: "queue" | "solutions" | "debug") => void + isVisible: () => boolean + toggleMainWindow: () => void + moveWindowLeft: () => void + moveWindowRight: () => void + moveWindowUp: () => void + moveWindowDown: () => void +} + +export interface IIpcHandlerDeps { + getMainWindow: () => BrowserWindow | null + setWindowDimensions: (width: number, height: number) => void + getScreenshotQueue: () => string[] + getExtraScreenshotQueue: () => string[] + deleteScreenshot: ( + path: string + ) => Promise<{ success: boolean; error?: string }> + getImagePreview: (filepath: string) => Promise + processingHelper: ProcessingHelper | null + PROCESSING_EVENTS: typeof state.PROCESSING_EVENTS + takeScreenshot: () => Promise + getView: () => "queue" | "solutions" | "debug" + toggleMainWindow: () => void + clearQueues: () => void + setView: (view: "queue" | "solutions" | "debug") => void + moveWindowLeft: () => void + moveWindowRight: () => void + moveWindowUp: () => void + moveWindowDown: () => void +} + +// Initialize helpers +function initializeHelpers() { + state.screenshotHelper = new ScreenshotHelper(state.view) + state.processingHelper = new ProcessingHelper({ + getScreenshotHelper, + getMainWindow, + getView, + setView, + getProblemInfo, + setProblemInfo, + getScreenshotQueue, + getExtraScreenshotQueue, + clearQueues, + takeScreenshot, + getImagePreview, + deleteScreenshot, + setHasDebugged, + getHasDebugged, + PROCESSING_EVENTS: state.PROCESSING_EVENTS + } as IProcessingHelperDeps) + state.shortcutsHelper = new ShortcutsHelper({ + getMainWindow, + takeScreenshot, + getImagePreview, + processingHelper: state.processingHelper, + clearQueues, + setView, + isVisible: () => state.isWindowVisible, + toggleMainWindow, + moveWindowLeft: () => + moveWindowHorizontal((x) => + Math.max(-(state.windowSize?.width || 0) / 2, x - state.step) + ), + moveWindowRight: () => + moveWindowHorizontal((x) => + Math.min( + state.screenWidth - (state.windowSize?.width || 0) / 2, + x + state.step + ) + ), + moveWindowUp: () => moveWindowVertical((y) => y - state.step), + moveWindowDown: () => moveWindowVertical((y) => y + state.step) + } as IShortcutsHelperDeps) +} + +// Auth callback handler + +// Register the interview-coder protocol +if (process.platform === "darwin") { + app.setAsDefaultProtocolClient("interview-coder") +} else { + app.setAsDefaultProtocolClient("interview-coder", process.execPath, [ + path.resolve(process.argv[1] || "") + ]) +} + +// Handle the protocol. In this case, we choose to show an Error Box. +if (process.defaultApp && process.argv.length >= 2) { + app.setAsDefaultProtocolClient("interview-coder", process.execPath, [ + path.resolve(process.argv[1]) + ]) +} + +// Force Single Instance Lock +const gotTheLock = app.requestSingleInstanceLock() + +if (!gotTheLock) { + app.quit() +} else { + app.on("second-instance", (event, commandLine) => { + // Someone tried to run a second instance, we should focus our window. + if (state.mainWindow) { + if (state.mainWindow.isMinimized()) state.mainWindow.restore() + state.mainWindow.focus() + + // Protocol handler removed - no longer using auth callbacks + } + }) +} + +// Auth callback removed as we no longer use Supabase authentication + +// Window management functions +async function createWindow(): Promise { + if (state.mainWindow) { + if (state.mainWindow.isMinimized()) state.mainWindow.restore() + state.mainWindow.focus() + return + } + + const primaryDisplay = screen.getPrimaryDisplay() + const workArea = primaryDisplay.workAreaSize + state.screenWidth = workArea.width + state.screenHeight = workArea.height + state.step = 60 + state.currentY = 50 + + const windowSettings: Electron.BrowserWindowConstructorOptions = { + width: 800, + height: 600, + minWidth: 750, + minHeight: 550, + x: state.currentX, + y: 50, + alwaysOnTop: true, + webPreferences: { + nodeIntegration: false, + contextIsolation: true, + preload: isDev + ? path.join(__dirname, "../dist-electron/preload.js") + : path.join(__dirname, "preload.js"), + scrollBounce: true + }, + show: true, + frame: false, + transparent: true, + fullscreenable: false, + hasShadow: false, + opacity: 1.0, // Start with full opacity + backgroundColor: "#00000000", + focusable: true, + skipTaskbar: true, + type: "panel", + paintWhenInitiallyHidden: true, + titleBarStyle: "hidden", + enableLargerThanScreen: true, + movable: true + } + + state.mainWindow = new BrowserWindow(windowSettings) + + // Add more detailed logging for window events + state.mainWindow.webContents.on("did-finish-load", () => { + console.log("Window finished loading") + }) + state.mainWindow.webContents.on( + "did-fail-load", + async (event, errorCode, errorDescription) => { + console.error("Window failed to load:", errorCode, errorDescription) + if (isDev) { + // In development, retry loading after a short delay + console.log("Retrying to load development server...") + setTimeout(() => { + state.mainWindow?.loadURL("http://localhost:54321").catch((error) => { + console.error("Failed to load dev server on retry:", error) + }) + }, 1000) + } + } + ) + + if (isDev) { + // In development, load from the dev server + console.log("Loading from development server: http://localhost:54321") + state.mainWindow.loadURL("http://localhost:54321").catch((error) => { + console.error("Failed to load dev server, falling back to local file:", error) + // Fallback to local file if dev server is not available + const indexPath = path.join(__dirname, "../dist/index.html") + console.log("Falling back to:", indexPath) + if (fs.existsSync(indexPath)) { + state.mainWindow.loadFile(indexPath) + } else { + console.error("Could not find index.html in dist folder") + } + }) + } else { + // In production, load from the built files + const indexPath = path.join(__dirname, "../dist/index.html") + console.log("Loading production build:", indexPath) + + if (fs.existsSync(indexPath)) { + state.mainWindow.loadFile(indexPath) + } else { + console.error("Could not find index.html in dist folder") + } + } + + // Configure window behavior + state.mainWindow.webContents.setZoomFactor(1) + if (isDev) { + state.mainWindow.webContents.openDevTools() + } + state.mainWindow.webContents.setWindowOpenHandler(({ url }) => { + console.log("Attempting to open URL:", url) + if (url.includes("google.com") || url.includes("supabase.co")) { + shell.openExternal(url) + return { action: "deny" } + } + return { action: "allow" } + }) + + // Enhanced screen capture resistance + state.mainWindow.setContentProtection(true) + + state.mainWindow.setVisibleOnAllWorkspaces(true, { + visibleOnFullScreen: true + }) + state.mainWindow.setAlwaysOnTop(true, "screen-saver", 1) + + // Additional screen capture resistance settings + if (process.platform === "darwin") { + // Prevent window from being captured in screenshots + state.mainWindow.setHiddenInMissionControl(true) + state.mainWindow.setWindowButtonVisibility(false) + state.mainWindow.setBackgroundColor("#00000000") + + // Prevent window from being included in window switcher + state.mainWindow.setSkipTaskbar(true) + + // Disable window shadow + state.mainWindow.setHasShadow(false) + } + + // Prevent the window from being captured by screen recording + state.mainWindow.webContents.setBackgroundThrottling(false) + state.mainWindow.webContents.setFrameRate(60) + + // Set up window listeners + state.mainWindow.on("move", handleWindowMove) + state.mainWindow.on("resize", handleWindowResize) + state.mainWindow.on("closed", handleWindowClosed) + + // Initialize window state + const bounds = state.mainWindow.getBounds() + state.windowPosition = { x: bounds.x, y: bounds.y } + state.windowSize = { width: bounds.width, height: bounds.height } + state.currentX = bounds.x + state.currentY = bounds.y + state.isWindowVisible = true + + // Set opacity based on user preferences or hide initially + // Ensure the window is visible for the first launch or if opacity > 0.1 + const savedOpacity = configHelper.getOpacity(); + console.log(`Initial opacity from config: ${savedOpacity}`); + + // Always make sure window is shown first + state.mainWindow.show(); + state.mainWindow.focus(); + + if (savedOpacity <= 0.1) { + console.log('Initial opacity too low, setting to 0 and hiding window'); + state.mainWindow.setOpacity(0); + state.isWindowVisible = false; + } else { + console.log(`Setting initial opacity to ${savedOpacity}`); + state.mainWindow.setOpacity(savedOpacity); + state.isWindowVisible = true; + } +} + +function handleWindowMove(): void { + if (!state.mainWindow) return + const bounds = state.mainWindow.getBounds() + state.windowPosition = { x: bounds.x, y: bounds.y } + state.currentX = bounds.x + state.currentY = bounds.y +} + +function handleWindowResize(): void { + if (!state.mainWindow) return + const bounds = state.mainWindow.getBounds() + state.windowSize = { width: bounds.width, height: bounds.height } +} + +function handleWindowClosed(): void { + state.mainWindow = null + state.isWindowVisible = false + state.windowPosition = null + state.windowSize = null +} + +// Window visibility functions +function hideMainWindow(): void { + if (!state.mainWindow?.isDestroyed()) { + const bounds = state.mainWindow.getBounds(); + state.windowPosition = { x: bounds.x, y: bounds.y }; + state.windowSize = { width: bounds.width, height: bounds.height }; + state.mainWindow.setIgnoreMouseEvents(true, { forward: true }); + state.mainWindow.setOpacity(0); + state.isWindowVisible = false; + console.log('Window hidden, opacity set to 0'); + } +} + +function showMainWindow(): void { + if (!state.mainWindow?.isDestroyed()) { + if (state.windowPosition && state.windowSize) { + state.mainWindow.setBounds({ + ...state.windowPosition, + ...state.windowSize + }); + } + state.mainWindow.setIgnoreMouseEvents(false); + state.mainWindow.setAlwaysOnTop(true, "screen-saver", 1); + state.mainWindow.setVisibleOnAllWorkspaces(true, { + visibleOnFullScreen: true + }); + state.mainWindow.setContentProtection(true); + state.mainWindow.show(); + state.mainWindow.focus(); + state.mainWindow.setOpacity(1); + state.isWindowVisible = true; + console.log('Window shown, opacity set to 1'); + } +} + +function toggleMainWindow(): void { + console.log(`Toggling window. Current state: ${state.isWindowVisible ? 'visible' : 'hidden'}`); + if (state.isWindowVisible) { + hideMainWindow(); + } else { + showMainWindow(); + } +} + +// Window movement functions +function moveWindowHorizontal(updateFn: (x: number) => number): void { + if (!state.mainWindow) return + state.currentX = updateFn(state.currentX) + state.mainWindow.setPosition( + Math.round(state.currentX), + Math.round(state.currentY) + ) +} + +function moveWindowVertical(updateFn: (y: number) => number): void { + if (!state.mainWindow) return + + const newY = updateFn(state.currentY) + // Allow window to go 2/3 off screen in either direction + const maxUpLimit = (-(state.windowSize?.height || 0) * 2) / 3 + const maxDownLimit = + state.screenHeight + ((state.windowSize?.height || 0) * 2) / 3 + + // Log the current state and limits + console.log({ + newY, + maxUpLimit, + maxDownLimit, + screenHeight: state.screenHeight, + windowHeight: state.windowSize?.height, + currentY: state.currentY + }) + + // Only update if within bounds + if (newY >= maxUpLimit && newY <= maxDownLimit) { + state.currentY = newY + state.mainWindow.setPosition( + Math.round(state.currentX), + Math.round(state.currentY) + ) + } +} + +// Window dimension functions +function setWindowDimensions(width: number, height: number): void { + if (!state.mainWindow?.isDestroyed()) { + const [currentX, currentY] = state.mainWindow.getPosition() + const primaryDisplay = screen.getPrimaryDisplay() + const workArea = primaryDisplay.workAreaSize + const maxWidth = Math.floor(workArea.width * 0.5) + + state.mainWindow.setBounds({ + x: Math.min(currentX, workArea.width - maxWidth), + y: currentY, + width: Math.min(width + 32, maxWidth), + height: Math.ceil(height) + }) + } +} + +// Environment setup +function loadEnvVariables() { + if (isDev) { + console.log("Loading env variables from:", path.join(process.cwd(), ".env")) + dotenv.config({ path: path.join(process.cwd(), ".env") }) + } else { + console.log( + "Loading env variables from:", + path.join(process.resourcesPath, ".env") + ) + dotenv.config({ path: path.join(process.resourcesPath, ".env") }) + } + console.log("Loaded environment variables:", { + VITE_SUPABASE_URL: process.env.VITE_SUPABASE_URL ? "exists" : "missing", + VITE_SUPABASE_ANON_KEY: process.env.VITE_SUPABASE_ANON_KEY + ? "exists" + : "missing" + }) +} + +// Initialize application +async function initializeApp() { + try { + // Set custom cache directory to prevent permission issues + const appDataPath = path.join(app.getPath('appData'), 'interview-coder-v1') + const sessionPath = path.join(appDataPath, 'session') + const tempPath = path.join(appDataPath, 'temp') + const cachePath = path.join(appDataPath, 'cache') + + // Create directories if they don't exist + for (const dir of [appDataPath, sessionPath, tempPath, cachePath]) { + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }) + } + } + + app.setPath('userData', appDataPath) + app.setPath('sessionData', sessionPath) + app.setPath('temp', tempPath) + app.setPath('cache', cachePath) + + loadEnvVariables() + + // Ensure a configuration file exists + if (!configHelper.hasApiKey()) { + console.log("No API key found in configuration. User will need to set up.") + } + + initializeHelpers() + initializeIpcHandlers({ + getMainWindow, + setWindowDimensions, + getScreenshotQueue, + getExtraScreenshotQueue, + deleteScreenshot, + getImagePreview, + processingHelper: state.processingHelper, + PROCESSING_EVENTS: state.PROCESSING_EVENTS, + takeScreenshot, + getView, + toggleMainWindow, + clearQueues, + setView, + moveWindowLeft: () => + moveWindowHorizontal((x) => + Math.max(-(state.windowSize?.width || 0) / 2, x - state.step) + ), + moveWindowRight: () => + moveWindowHorizontal((x) => + Math.min( + state.screenWidth - (state.windowSize?.width || 0) / 2, + x + state.step + ) + ), + moveWindowUp: () => moveWindowVertical((y) => y - state.step), + moveWindowDown: () => moveWindowVertical((y) => y + state.step) + }) + await createWindow() + state.shortcutsHelper?.registerGlobalShortcuts() + + // Initialize auto-updater regardless of environment + initAutoUpdater() + console.log( + "Auto-updater initialized in", + isDev ? "development" : "production", + "mode" + ) + } catch (error) { + console.error("Failed to initialize application:", error) + app.quit() + } +} + +// Auth callback handling removed - no longer needed +app.on("open-url", (event, url) => { + console.log("open-url event received:", url) + event.preventDefault() +}) + +// Handle second instance (removed auth callback handling) +app.on("second-instance", (event, commandLine) => { + console.log("second-instance event received:", commandLine) + + // Focus or create the main window + if (!state.mainWindow) { + createWindow() + } else { + if (state.mainWindow.isMinimized()) state.mainWindow.restore() + state.mainWindow.focus() + } +}) + +// Prevent multiple instances of the app +if (!app.requestSingleInstanceLock()) { + app.quit() +} else { + app.on("window-all-closed", () => { + if (process.platform !== "darwin") { + app.quit() + state.mainWindow = null + } + }) +} + +app.on("activate", () => { + if (BrowserWindow.getAllWindows().length === 0) { + createWindow() + } +}) + +// State getter/setter functions +function getMainWindow(): BrowserWindow | null { + return state.mainWindow +} + +function getView(): "queue" | "solutions" | "debug" { + return state.view +} + +function setView(view: "queue" | "solutions" | "debug"): void { + state.view = view + state.screenshotHelper?.setView(view) +} + +function getScreenshotHelper(): ScreenshotHelper | null { + return state.screenshotHelper +} + +function getProblemInfo(): any { + return state.problemInfo +} + +function setProblemInfo(problemInfo: any): void { + state.problemInfo = problemInfo +} + +function getScreenshotQueue(): string[] { + return state.screenshotHelper?.getScreenshotQueue() || [] +} + +function getExtraScreenshotQueue(): string[] { + return state.screenshotHelper?.getExtraScreenshotQueue() || [] +} + +function clearQueues(): void { + state.screenshotHelper?.clearQueues() + state.problemInfo = null + setView("queue") +} + +async function takeScreenshot(): Promise { + if (!state.mainWindow) throw new Error("No main window available") + return ( + state.screenshotHelper?.takeScreenshot( + () => hideMainWindow(), + () => showMainWindow() + ) || "" + ) +} + +async function getImagePreview(filepath: string): Promise { + return state.screenshotHelper?.getImagePreview(filepath) || "" +} + +async function deleteScreenshot( + path: string +): Promise<{ success: boolean; error?: string }> { + return ( + state.screenshotHelper?.deleteScreenshot(path) || { + success: false, + error: "Screenshot helper not initialized" + } + ) +} + +function setHasDebugged(value: boolean): void { + state.hasDebugged = value +} + +function getHasDebugged(): boolean { + return state.hasDebugged +} + +// Export state and functions for other modules +export { + state, + createWindow, + hideMainWindow, + showMainWindow, + toggleMainWindow, + setWindowDimensions, + moveWindowHorizontal, + moveWindowVertical, + getMainWindow, + getView, + setView, + getScreenshotHelper, + getProblemInfo, + setProblemInfo, + getScreenshotQueue, + getExtraScreenshotQueue, + clearQueues, + takeScreenshot, + getImagePreview, + deleteScreenshot, + setHasDebugged, + getHasDebugged +} + +app.whenReady().then(initializeApp) diff --git a/electron/preload.ts b/electron/preload.ts new file mode 100644 index 0000000..85f3215 --- /dev/null +++ b/electron/preload.ts @@ -0,0 +1,262 @@ +console.log("Preload script starting...") +import { contextBridge, ipcRenderer } from "electron" +const { shell } = require("electron") + +export const PROCESSING_EVENTS = { + //global states + UNAUTHORIZED: "procesing-unauthorized", + NO_SCREENSHOTS: "processing-no-screenshots", + OUT_OF_CREDITS: "out-of-credits", + API_KEY_INVALID: "api-key-invalid", + + //states for generating the initial solution + INITIAL_START: "initial-start", + PROBLEM_EXTRACTED: "problem-extracted", + SOLUTION_SUCCESS: "solution-success", + INITIAL_SOLUTION_ERROR: "solution-error", + RESET: "reset", + + //states for processing the debugging + DEBUG_START: "debug-start", + DEBUG_SUCCESS: "debug-success", + DEBUG_ERROR: "debug-error" +} as const + +// At the top of the file +console.log("Preload script is running") + +const electronAPI = { + // Original methods + openSubscriptionPortal: async (authData: { id: string; email: string }) => { + return ipcRenderer.invoke("open-subscription-portal", authData) + }, + openSettingsPortal: () => ipcRenderer.invoke("open-settings-portal"), + updateContentDimensions: (dimensions: { width: number; height: number }) => + ipcRenderer.invoke("update-content-dimensions", dimensions), + clearStore: () => ipcRenderer.invoke("clear-store"), + getScreenshots: () => ipcRenderer.invoke("get-screenshots"), + deleteScreenshot: (path: string) => + ipcRenderer.invoke("delete-screenshot", path), + toggleMainWindow: async () => { + console.log("toggleMainWindow called from preload") + try { + const result = await ipcRenderer.invoke("toggle-window") + console.log("toggle-window result:", result) + return result + } catch (error) { + console.error("Error in toggleMainWindow:", error) + throw error + } + }, + // Event listeners + onScreenshotTaken: ( + callback: (data: { path: string; preview: string }) => void + ) => { + const subscription = (_: any, data: { path: string; preview: string }) => + callback(data) + ipcRenderer.on("screenshot-taken", subscription) + return () => { + ipcRenderer.removeListener("screenshot-taken", subscription) + } + }, + onResetView: (callback: () => void) => { + const subscription = () => callback() + ipcRenderer.on("reset-view", subscription) + return () => { + ipcRenderer.removeListener("reset-view", subscription) + } + }, + onSolutionStart: (callback: () => void) => { + const subscription = () => callback() + ipcRenderer.on(PROCESSING_EVENTS.INITIAL_START, subscription) + return () => { + ipcRenderer.removeListener(PROCESSING_EVENTS.INITIAL_START, subscription) + } + }, + onDebugStart: (callback: () => void) => { + const subscription = () => callback() + ipcRenderer.on(PROCESSING_EVENTS.DEBUG_START, subscription) + return () => { + ipcRenderer.removeListener(PROCESSING_EVENTS.DEBUG_START, subscription) + } + }, + onDebugSuccess: (callback: (data: any) => void) => { + ipcRenderer.on("debug-success", (_event, data) => callback(data)) + return () => { + ipcRenderer.removeListener("debug-success", (_event, data) => + callback(data) + ) + } + }, + onDebugError: (callback: (error: string) => void) => { + const subscription = (_: any, error: string) => callback(error) + ipcRenderer.on(PROCESSING_EVENTS.DEBUG_ERROR, subscription) + return () => { + ipcRenderer.removeListener(PROCESSING_EVENTS.DEBUG_ERROR, subscription) + } + }, + onSolutionError: (callback: (error: string) => void) => { + const subscription = (_: any, error: string) => callback(error) + ipcRenderer.on(PROCESSING_EVENTS.INITIAL_SOLUTION_ERROR, subscription) + return () => { + ipcRenderer.removeListener( + PROCESSING_EVENTS.INITIAL_SOLUTION_ERROR, + subscription + ) + } + }, + onProcessingNoScreenshots: (callback: () => void) => { + const subscription = () => callback() + ipcRenderer.on(PROCESSING_EVENTS.NO_SCREENSHOTS, subscription) + return () => { + ipcRenderer.removeListener(PROCESSING_EVENTS.NO_SCREENSHOTS, subscription) + } + }, + onOutOfCredits: (callback: () => void) => { + const subscription = () => callback() + ipcRenderer.on(PROCESSING_EVENTS.OUT_OF_CREDITS, subscription) + return () => { + ipcRenderer.removeListener(PROCESSING_EVENTS.OUT_OF_CREDITS, subscription) + } + }, + onProblemExtracted: (callback: (data: any) => void) => { + const subscription = (_: any, data: any) => callback(data) + ipcRenderer.on(PROCESSING_EVENTS.PROBLEM_EXTRACTED, subscription) + return () => { + ipcRenderer.removeListener( + PROCESSING_EVENTS.PROBLEM_EXTRACTED, + subscription + ) + } + }, + onSolutionSuccess: (callback: (data: any) => void) => { + const subscription = (_: any, data: any) => callback(data) + ipcRenderer.on(PROCESSING_EVENTS.SOLUTION_SUCCESS, subscription) + return () => { + ipcRenderer.removeListener( + PROCESSING_EVENTS.SOLUTION_SUCCESS, + subscription + ) + } + }, + onUnauthorized: (callback: () => void) => { + const subscription = () => callback() + ipcRenderer.on(PROCESSING_EVENTS.UNAUTHORIZED, subscription) + return () => { + ipcRenderer.removeListener(PROCESSING_EVENTS.UNAUTHORIZED, subscription) + } + }, + // External URL handler + openLink: (url: string) => shell.openExternal(url), + triggerScreenshot: () => ipcRenderer.invoke("trigger-screenshot"), + triggerProcessScreenshots: () => + ipcRenderer.invoke("trigger-process-screenshots"), + triggerReset: () => ipcRenderer.invoke("trigger-reset"), + triggerMoveLeft: () => ipcRenderer.invoke("trigger-move-left"), + triggerMoveRight: () => ipcRenderer.invoke("trigger-move-right"), + triggerMoveUp: () => ipcRenderer.invoke("trigger-move-up"), + triggerMoveDown: () => ipcRenderer.invoke("trigger-move-down"), + onSubscriptionUpdated: (callback: () => void) => { + const subscription = () => callback() + ipcRenderer.on("subscription-updated", subscription) + return () => { + ipcRenderer.removeListener("subscription-updated", subscription) + } + }, + onSubscriptionPortalClosed: (callback: () => void) => { + const subscription = () => callback() + ipcRenderer.on("subscription-portal-closed", subscription) + return () => { + ipcRenderer.removeListener("subscription-portal-closed", subscription) + } + }, + onReset: (callback: () => void) => { + const subscription = () => callback() + ipcRenderer.on(PROCESSING_EVENTS.RESET, subscription) + return () => { + ipcRenderer.removeListener(PROCESSING_EVENTS.RESET, subscription) + } + }, + startUpdate: () => ipcRenderer.invoke("start-update"), + installUpdate: () => ipcRenderer.invoke("install-update"), + onUpdateAvailable: (callback: (info: any) => void) => { + const subscription = (_: any, info: any) => callback(info) + ipcRenderer.on("update-available", subscription) + return () => { + ipcRenderer.removeListener("update-available", subscription) + } + }, + onUpdateDownloaded: (callback: (info: any) => void) => { + const subscription = (_: any, info: any) => callback(info) + ipcRenderer.on("update-downloaded", subscription) + return () => { + ipcRenderer.removeListener("update-downloaded", subscription) + } + }, + decrementCredits: () => ipcRenderer.invoke("decrement-credits"), + onCreditsUpdated: (callback: (credits: number) => void) => { + const subscription = (_event: any, credits: number) => callback(credits) + ipcRenderer.on("credits-updated", subscription) + return () => { + ipcRenderer.removeListener("credits-updated", subscription) + } + }, + getPlatform: () => process.platform, + + // New methods for OpenAI API integration + getConfig: () => ipcRenderer.invoke("get-config"), + updateConfig: (config: { apiKey?: string; model?: string; language?: string; opacity?: number }) => + ipcRenderer.invoke("update-config", config), + onShowSettings: (callback: () => void) => { + const subscription = () => callback() + ipcRenderer.on("show-settings-dialog", subscription) + return () => { + ipcRenderer.removeListener("show-settings-dialog", subscription) + } + }, + checkApiKey: () => ipcRenderer.invoke("check-api-key"), + validateApiKey: (apiKey: string) => + ipcRenderer.invoke("validate-api-key", apiKey), + openExternal: (url: string) => + ipcRenderer.invoke("openExternal", url), + onApiKeyInvalid: (callback: () => void) => { + const subscription = () => callback() + ipcRenderer.on(PROCESSING_EVENTS.API_KEY_INVALID, subscription) + return () => { + ipcRenderer.removeListener(PROCESSING_EVENTS.API_KEY_INVALID, subscription) + } + }, + removeListener: (eventName: string, callback: (...args: any[]) => void) => { + ipcRenderer.removeListener(eventName, callback) + }, + onDeleteLastScreenshot: (callback: () => void) => { + const subscription = () => callback() + ipcRenderer.on("delete-last-screenshot", subscription) + return () => { + ipcRenderer.removeListener("delete-last-screenshot", subscription) + } + }, + deleteLastScreenshot: () => ipcRenderer.invoke("delete-last-screenshot") +} + +// Before exposing the API +console.log( + "About to expose electronAPI with methods:", + Object.keys(electronAPI) +) + +// Expose the API +contextBridge.exposeInMainWorld("electronAPI", electronAPI) + +console.log("electronAPI exposed to window") + +// Add this focus restoration handler +ipcRenderer.on("restore-focus", () => { + // Try to focus the active element if it exists + const activeElement = document.activeElement as HTMLElement + if (activeElement && typeof activeElement.focus === "function") { + activeElement.focus() + } +}) + +// Remove auth-callback handling - no longer needed diff --git a/electron/shortcuts.ts b/electron/shortcuts.ts new file mode 100644 index 0000000..a6fa5eb --- /dev/null +++ b/electron/shortcuts.ts @@ -0,0 +1,167 @@ +import { globalShortcut, app } from "electron" +import { IShortcutsHelperDeps } from "./main" +import { configHelper } from "./ConfigHelper" + +export class ShortcutsHelper { + private deps: IShortcutsHelperDeps + + constructor(deps: IShortcutsHelperDeps) { + this.deps = deps + } + + private adjustOpacity(delta: number): void { + const mainWindow = this.deps.getMainWindow(); + if (!mainWindow) return; + + let currentOpacity = mainWindow.getOpacity(); + let newOpacity = Math.max(0.1, Math.min(1.0, currentOpacity + delta)); + console.log(`Adjusting opacity from ${currentOpacity} to ${newOpacity}`); + + mainWindow.setOpacity(newOpacity); + + // Save the opacity setting to config without re-initializing the client + try { + const config = configHelper.loadConfig(); + config.opacity = newOpacity; + configHelper.saveConfig(config); + } catch (error) { + console.error('Error saving opacity to config:', error); + } + + // If we're making the window visible, also make sure it's shown and interaction is enabled + if (newOpacity > 0.1 && !this.deps.isVisible()) { + this.deps.toggleMainWindow(); + } + } + + public registerGlobalShortcuts(): void { + globalShortcut.register("CommandOrControl+H", async () => { + const mainWindow = this.deps.getMainWindow() + if (mainWindow) { + console.log("Taking screenshot...") + try { + const screenshotPath = await this.deps.takeScreenshot() + const preview = await this.deps.getImagePreview(screenshotPath) + mainWindow.webContents.send("screenshot-taken", { + path: screenshotPath, + preview + }) + } catch (error) { + console.error("Error capturing screenshot:", error) + } + } + }) + + globalShortcut.register("CommandOrControl+Enter", async () => { + await this.deps.processingHelper?.processScreenshots() + }) + + globalShortcut.register("CommandOrControl+R", () => { + console.log( + "Command + R pressed. Canceling requests and resetting queues..." + ) + + // Cancel ongoing API requests + this.deps.processingHelper?.cancelOngoingRequests() + + // Clear both screenshot queues + this.deps.clearQueues() + + console.log("Cleared queues.") + + // Update the view state to 'queue' + this.deps.setView("queue") + + // Notify renderer process to switch view to 'queue' + const mainWindow = this.deps.getMainWindow() + if (mainWindow && !mainWindow.isDestroyed()) { + mainWindow.webContents.send("reset-view") + mainWindow.webContents.send("reset") + } + }) + + // New shortcuts for moving the window + globalShortcut.register("CommandOrControl+Left", () => { + console.log("Command/Ctrl + Left pressed. Moving window left.") + this.deps.moveWindowLeft() + }) + + globalShortcut.register("CommandOrControl+Right", () => { + console.log("Command/Ctrl + Right pressed. Moving window right.") + this.deps.moveWindowRight() + }) + + globalShortcut.register("CommandOrControl+Down", () => { + console.log("Command/Ctrl + down pressed. Moving window down.") + this.deps.moveWindowDown() + }) + + globalShortcut.register("CommandOrControl+Up", () => { + console.log("Command/Ctrl + Up pressed. Moving window Up.") + this.deps.moveWindowUp() + }) + + globalShortcut.register("CommandOrControl+B", () => { + console.log("Command/Ctrl + B pressed. Toggling window visibility.") + this.deps.toggleMainWindow() + }) + + globalShortcut.register("CommandOrControl+Q", () => { + console.log("Command/Ctrl + Q pressed. Quitting application.") + app.quit() + }) + + // Adjust opacity shortcuts + globalShortcut.register("CommandOrControl+[", () => { + console.log("Command/Ctrl + [ pressed. Decreasing opacity.") + this.adjustOpacity(-0.1) + }) + + globalShortcut.register("CommandOrControl+]", () => { + console.log("Command/Ctrl + ] pressed. Increasing opacity.") + this.adjustOpacity(0.1) + }) + + // Zoom controls + globalShortcut.register("CommandOrControl+-", () => { + console.log("Command/Ctrl + - pressed. Zooming out.") + const mainWindow = this.deps.getMainWindow() + if (mainWindow) { + const currentZoom = mainWindow.webContents.getZoomLevel() + mainWindow.webContents.setZoomLevel(currentZoom - 0.5) + } + }) + + globalShortcut.register("CommandOrControl+0", () => { + console.log("Command/Ctrl + 0 pressed. Resetting zoom.") + const mainWindow = this.deps.getMainWindow() + if (mainWindow) { + mainWindow.webContents.setZoomLevel(0) + } + }) + + globalShortcut.register("CommandOrControl+=", () => { + console.log("Command/Ctrl + = pressed. Zooming in.") + const mainWindow = this.deps.getMainWindow() + if (mainWindow) { + const currentZoom = mainWindow.webContents.getZoomLevel() + mainWindow.webContents.setZoomLevel(currentZoom + 0.5) + } + }) + + // Delete last screenshot shortcut + globalShortcut.register("CommandOrControl+L", () => { + console.log("Command/Ctrl + L pressed. Deleting last screenshot.") + const mainWindow = this.deps.getMainWindow() + if (mainWindow) { + // Send an event to the renderer to delete the last screenshot + mainWindow.webContents.send("delete-last-screenshot") + } + }) + + // Unregister shortcuts when quitting + app.on("will-quit", () => { + globalShortcut.unregisterAll() + }) + } +} diff --git a/electron/store.ts b/electron/store.ts new file mode 100644 index 0000000..4fe485b --- /dev/null +++ b/electron/store.ts @@ -0,0 +1,16 @@ +import Store from "electron-store" + +interface StoreSchema { + // Empty for now, we can add other store items here later +} + +const store = new Store({ + defaults: {}, + encryptionKey: "your-encryption-key" +}) as Store & { + store: StoreSchema + get: (key: K) => StoreSchema[K] + set: (key: K, value: StoreSchema[K]) => void +} + +export { store } diff --git a/electron/tsconfig.json b/electron/tsconfig.json new file mode 100644 index 0000000..98fa172 --- /dev/null +++ b/electron/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "CommonJS", + "allowJs": true, + "skipLibCheck": true, + "esModuleInterop": true, + "noImplicitAny": true, + "sourceMap": true, + "jsx": "react-jsx", + "baseUrl": ".", + "outDir": "../dist-electron", + "moduleResolution": "node", + "resolveJsonModule": true, + "allowSyntheticDefaultImports": true + }, + "include": ["*.ts", "ConfigHelper.ts", "../src/types/electron.d.ts"] +} diff --git a/env.d.ts b/env.d.ts new file mode 100644 index 0000000..377b9ec --- /dev/null +++ b/env.d.ts @@ -0,0 +1,10 @@ +/// + +interface ImportMetaEnv { + readonly VITE_SUPABASE_URL: string + readonly VITE_SUPABASE_ANON_KEY: string +} + +interface ImportMeta { + readonly env: ImportMetaEnv +} diff --git a/index.html b/index.html new file mode 100644 index 0000000..abe6e88 --- /dev/null +++ b/index.html @@ -0,0 +1,16 @@ + + + + + + Interview Coder + + + +
+ + + diff --git a/package.json b/package.json new file mode 100644 index 0000000..6036c2b --- /dev/null +++ b/package.json @@ -0,0 +1,187 @@ +{ + "name": "interview-coder-v1", + "version": "1.0.19", + "main": "./dist-electron/main.js", + "scripts": { + "clean": "rimraf dist dist-electron", + "dev": "cross-env NODE_ENV=development npm run clean && concurrently \"tsc -w -p tsconfig.electron.json\" \"vite\" \"wait-on -t 30000 http://localhost:54321 && electron ./dist-electron/main.js\"", + "start": "cross-env NODE_ENV=development concurrently \"tsc -p tsconfig.electron.json\" \"vite\" \"wait-on -t 30000 http://localhost:54321 && electron ./dist-electron/main.js\"", + "build": "cross-env NODE_ENV=production rimraf dist dist-electron && vite build && tsc -p tsconfig.electron.json", + "run-prod": "cross-env NODE_ENV=production electron ./dist-electron/main.js" + }, + "build": { + "appId": "com.chunginlee.interviewcoder", + "productName": "Interview Coder", + "files": [ + "dist/**/*", + "dist-electron/**/*", + "package.json", + "electron/**/*" + ], + "directories": { + "output": "release", + "buildResources": "assets" + }, + "asar": true, + "compression": "maximum", + "generateUpdatesFilesForAllChannels": true, + "mac": { + "category": "public.app-category.developer-tools", + "target": [ + { + "target": "dmg", + "arch": [ + "x64", + "arm64" + ] + }, + { + "target": "zip", + "arch": [ + "x64", + "arm64" + ] + } + ], + "artifactName": "Interview-Coder-${arch}.${ext}", + "icon": "assets/icons/mac/icon.icns", + "hardenedRuntime": true, + "gatekeeperAssess": false, + "entitlements": "build/entitlements.mac.plist", + "entitlementsInherit": "build/entitlements.mac.plist", + "identity": "Developer ID Application", + "notarize": true, + "protocols": { + "name": "interview-coder-protocol", + "schemes": [ + "interview-coder" + ] + } + }, + "win": { + "target": [ + "nsis" + ], + "icon": "assets/icons/win/icon.ico", + "artifactName": "${productName}-Windows-${version}.${ext}", + "protocols": { + "name": "interview-coder-protocol", + "schemes": [ + "interview-coder" + ] + } + }, + "linux": { + "target": [ + "AppImage" + ], + "icon": "assets/icons/png/icon-256x256.png", + "artifactName": "${productName}-Linux-${version}.${ext}", + "protocols": { + "name": "interview-coder-protocol", + "schemes": [ + "interview-coder" + ] + } + }, + "publish": [ + { + "provider": "github", + "owner": "ibttf", + "repo": "interview-coder", + "private": false, + "releaseType": "release" + } + ], + "extraResources": [ + { + "from": ".env", + "to": ".env", + "filter": [ + "**/*" + ] + } + ], + "extraMetadata": { + "main": "dist-electron/main.js" + } + }, + "keywords": ["interview", "coding", "interview prep", "technical interview", "tool"], + "author": "Interview Coder Contributors", + "license": "AGPL-3.0-or-later", + "description": "An invisible desktop application to help you pass your technical interviews.", + "dependencies": { + "@electron/notarize": "^2.3.0", + "@emotion/react": "^11.11.0", + "@emotion/styled": "^11.11.0", + "@radix-ui/react-dialog": "^1.1.2", + "@radix-ui/react-label": "^2.1.0", + "@radix-ui/react-slot": "^1.1.0", + "@radix-ui/react-toast": "^1.2.2", + "@supabase/supabase-js": "^2.39.0", + "@tanstack/react-query": "^5.64.0", + "axios": "^1.7.7", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "diff": "^7.0.0", + "dotenv": "^16.4.7", + "electron-log": "^5.2.4", + "electron-store": "^10.0.0", + "electron-updater": "^6.3.9", + "form-data": "^4.0.1", + "lucide-react": "^0.460.0", + "openai": "^4.28.4", + "react": "^18.2.0", + "react-code-blocks": "^0.1.6", + "react-dom": "^18.2.0", + "react-router-dom": "^6.28.1", + "react-syntax-highlighter": "^15.6.1", + "screenshot-desktop": "^1.15.0", + "tailwind-merge": "^2.5.5", + "uuid": "^11.0.3" + }, + "devDependencies": { + "@electron/typescript-definitions": "^8.14.0", + "@types/color": "^4.2.0", + "@types/diff": "^6.0.0", + "@types/electron-store": "^1.3.1", + "@types/node": "^20.11.30", + "@types/react": "^18.2.67", + "@types/react-dom": "^18.2.22", + "@types/react-syntax-highlighter": "^15.5.13", + "@types/screenshot-desktop": "^1.12.3", + "@types/uuid": "^9.0.8", + "@typescript-eslint/eslint-plugin": "^7.3.1", + "@typescript-eslint/parser": "^7.3.1", + "@vitejs/plugin-react": "^4.2.1", + "autoprefixer": "^10.4.20", + "concurrently": "^8.2.2", + "cross-env": "^7.0.3", + "electron": "^29.1.4", + "electron-builder": "^24.13.3", + "electron-is-dev": "^3.0.1", + "eslint": "^8.57.0", + "eslint-plugin-react-hooks": "^4.6.0", + "eslint-plugin-react-refresh": "^0.4.6", + "postcss": "^8.4.49", + "rimraf": "^6.0.1", + "tailwindcss": "^3.4.15", + "typescript": "^5.4.2", + "vite": "^5.1.6", + "vite-plugin-electron": "^0.28.4", + "vite-plugin-electron-renderer": "^0.14.6", + "wait-on": "^7.2.0" + }, + "browserslist": { + "production": [ + ">0.2%", + "not dead", + "not op_mini all" + ], + "development": [ + "last 1 chrome version", + "last 1 firefox version", + "last 1 safari version" + ] + } +} diff --git a/postcss.config.js b/postcss.config.js new file mode 100644 index 0000000..33ad091 --- /dev/null +++ b/postcss.config.js @@ -0,0 +1,6 @@ +module.exports = { + plugins: { + tailwindcss: {}, + autoprefixer: {}, + }, +} diff --git a/renderer/.gitignore b/renderer/.gitignore new file mode 100644 index 0000000..4d29575 --- /dev/null +++ b/renderer/.gitignore @@ -0,0 +1,23 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# production +/build + +# misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* diff --git a/renderer/README.md b/renderer/README.md new file mode 100644 index 0000000..b87cb00 --- /dev/null +++ b/renderer/README.md @@ -0,0 +1,46 @@ +# Getting Started with Create React App + +This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). + +## Available Scripts + +In the project directory, you can run: + +### `npm start` + +Runs the app in the development mode.\ +Open [http://localhost:3000](http://localhost:3000) to view it in the browser. + +The page will reload if you make edits.\ +You will also see any lint errors in the console. + +### `npm test` + +Launches the test runner in the interactive watch mode.\ +See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. + +### `npm run build` + +Builds the app for production to the `build` folder.\ +It correctly bundles React in production mode and optimizes the build for the best performance. + +The build is minified and the filenames include the hashes.\ +Your app is ready to be deployed! + +See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. + +### `npm run eject` + +**Note: this is a one-way operation. Once you `eject`, you can’t go back!** + +If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. + +Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. + +You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. + +## Learn More + +You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). + +To learn React, check out the [React documentation](https://reactjs.org/). diff --git a/renderer/package.json b/renderer/package.json new file mode 100644 index 0000000..adc4d12 --- /dev/null +++ b/renderer/package.json @@ -0,0 +1,43 @@ +{ + "name": "renderer", + "version": "0.1.0", + "private": true, + "dependencies": { + "@testing-library/jest-dom": "^5.17.0", + "@testing-library/react": "^13.4.0", + "@testing-library/user-event": "^13.5.0", + "@types/jest": "^27.5.2", + "@types/node": "^16.18.119", + "@types/react": "^18.3.12", + "@types/react-dom": "^18.3.1", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "react-scripts": "5.0.1", + "typescript": "^4.9.5", + "web-vitals": "^2.1.4" + }, + "scripts": { + "start": "react-scripts start", + "build": "react-scripts build", + "test": "react-scripts test", + "eject": "react-scripts eject" + }, + "eslintConfig": { + "extends": [ + "react-app", + "react-app/jest" + ] + }, + "browserslist": { + "production": [ + ">0.2%", + "not dead", + "not op_mini all" + ], + "development": [ + "last 1 chrome version", + "last 1 firefox version", + "last 1 safari version" + ] + } +} diff --git a/renderer/public/favicon.ico b/renderer/public/favicon.ico new file mode 100644 index 0000000..a11777c Binary files /dev/null and b/renderer/public/favicon.ico differ diff --git a/renderer/public/index.html b/renderer/public/index.html new file mode 100644 index 0000000..aa069f2 --- /dev/null +++ b/renderer/public/index.html @@ -0,0 +1,43 @@ + + + + + + + + + + + + + React App + + + +
+ + + diff --git a/renderer/public/logo192.png b/renderer/public/logo192.png new file mode 100644 index 0000000..fc44b0a Binary files /dev/null and b/renderer/public/logo192.png differ diff --git a/renderer/public/logo512.png b/renderer/public/logo512.png new file mode 100644 index 0000000..a4e47a6 Binary files /dev/null and b/renderer/public/logo512.png differ diff --git a/renderer/public/manifest.json b/renderer/public/manifest.json new file mode 100644 index 0000000..b9a7ae2 --- /dev/null +++ b/renderer/public/manifest.json @@ -0,0 +1,25 @@ +{ + "short_name": "Interview Coder", + "name": "Interview Coder", + "icons": [ + { + "src": "favicon.ico", + "sizes": "64x64 32x32 24x24 16x16", + "type": "image/x-icon" + }, + { + "src": "logo192.png", + "type": "image/png", + "sizes": "192x192" + }, + { + "src": "logo512.png", + "type": "image/png", + "sizes": "512x512" + } + ], + "start_url": ".", + "display": "standalone", + "theme_color": "#000000", + "background_color": "#ffffff" +} diff --git a/renderer/public/robots.txt b/renderer/public/robots.txt new file mode 100644 index 0000000..e9e57dc --- /dev/null +++ b/renderer/public/robots.txt @@ -0,0 +1,3 @@ +# https://www.robotstxt.org/robotstxt.html +User-agent: * +Disallow: diff --git a/renderer/src/App.css b/renderer/src/App.css new file mode 100644 index 0000000..74b5e05 --- /dev/null +++ b/renderer/src/App.css @@ -0,0 +1,38 @@ +.App { + text-align: center; +} + +.App-logo { + height: 40vmin; + pointer-events: none; +} + +@media (prefers-reduced-motion: no-preference) { + .App-logo { + animation: App-logo-spin infinite 20s linear; + } +} + +.App-header { + background-color: #282c34; + min-height: 100vh; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + font-size: calc(10px + 2vmin); + color: white; +} + +.App-link { + color: #61dafb; +} + +@keyframes App-logo-spin { + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } +} diff --git a/renderer/src/App.test.tsx b/renderer/src/App.test.tsx new file mode 100644 index 0000000..2a68616 --- /dev/null +++ b/renderer/src/App.test.tsx @@ -0,0 +1,9 @@ +import React from 'react'; +import { render, screen } from '@testing-library/react'; +import App from './App'; + +test('renders learn react link', () => { + render(); + const linkElement = screen.getByText(/learn react/i); + expect(linkElement).toBeInTheDocument(); +}); diff --git a/renderer/src/App.tsx b/renderer/src/App.tsx new file mode 100644 index 0000000..a53698a --- /dev/null +++ b/renderer/src/App.tsx @@ -0,0 +1,26 @@ +import React from 'react'; +import logo from './logo.svg'; +import './App.css'; + +function App() { + return ( +
+
+ logo +

+ Edit src/App.tsx and save to reload. +

+ + Learn React + +
+
+ ); +} + +export default App; diff --git a/renderer/src/index.css b/renderer/src/index.css new file mode 100644 index 0000000..ec2585e --- /dev/null +++ b/renderer/src/index.css @@ -0,0 +1,13 @@ +body { + margin: 0; + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', + 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', + sans-serif; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +code { + font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', + monospace; +} diff --git a/renderer/src/index.tsx b/renderer/src/index.tsx new file mode 100644 index 0000000..032464f --- /dev/null +++ b/renderer/src/index.tsx @@ -0,0 +1,19 @@ +import React from 'react'; +import ReactDOM from 'react-dom/client'; +import './index.css'; +import App from './App'; +import reportWebVitals from './reportWebVitals'; + +const root = ReactDOM.createRoot( + document.getElementById('root') as HTMLElement +); +root.render( + + + +); + +// If you want to start measuring performance in your app, pass a function +// to log results (for example: reportWebVitals(console.log)) +// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals +reportWebVitals(); diff --git a/renderer/src/logo.svg b/renderer/src/logo.svg new file mode 100644 index 0000000..9dfc1c0 --- /dev/null +++ b/renderer/src/logo.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/renderer/src/react-app-env.d.ts b/renderer/src/react-app-env.d.ts new file mode 100644 index 0000000..6431bc5 --- /dev/null +++ b/renderer/src/react-app-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/renderer/src/reportWebVitals.ts b/renderer/src/reportWebVitals.ts new file mode 100644 index 0000000..49a2a16 --- /dev/null +++ b/renderer/src/reportWebVitals.ts @@ -0,0 +1,15 @@ +import { ReportHandler } from 'web-vitals'; + +const reportWebVitals = (onPerfEntry?: ReportHandler) => { + if (onPerfEntry && onPerfEntry instanceof Function) { + import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { + getCLS(onPerfEntry); + getFID(onPerfEntry); + getFCP(onPerfEntry); + getLCP(onPerfEntry); + getTTFB(onPerfEntry); + }); + } +}; + +export default reportWebVitals; diff --git a/renderer/src/setupTests.ts b/renderer/src/setupTests.ts new file mode 100644 index 0000000..8f2609b --- /dev/null +++ b/renderer/src/setupTests.ts @@ -0,0 +1,5 @@ +// jest-dom adds custom jest matchers for asserting on DOM nodes. +// allows you to do things like: +// expect(element).toHaveTextContent(/react/i) +// learn more: https://github.com/testing-library/jest-dom +import '@testing-library/jest-dom'; diff --git a/renderer/tsconfig.json b/renderer/tsconfig.json new file mode 100644 index 0000000..9d379a3 --- /dev/null +++ b/renderer/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "target": "es5", + "lib": ["dom", "dom.iterable", "esnext"], + "allowJs": true, + "skipLibCheck": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "strict": true, + "forceConsistentCasingInFileNames": true, + "noFallthroughCasesInSwitch": true, + "module": "esnext", + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx" + }, + "include": ["src"] +} diff --git a/src/App.tsx b/src/App.tsx new file mode 100644 index 0000000..a448082 --- /dev/null +++ b/src/App.tsx @@ -0,0 +1,291 @@ +import SubscribedApp from "./_pages/SubscribedApp" +import { UpdateNotification } from "./components/UpdateNotification" +import { + QueryClient, + QueryClientProvider +} from "@tanstack/react-query" +import { useEffect, useState, useCallback } from "react" +import { + Toast, + ToastDescription, + ToastProvider, + ToastTitle, + ToastViewport +} from "./components/ui/toast" +import { ToastContext } from "./contexts/toast" +import { WelcomeScreen } from "./components/WelcomeScreen" +import { SettingsDialog } from "./components/Settings/SettingsDialog" + +// Create a React Query client +const queryClient = new QueryClient({ + defaultOptions: { + queries: { + staleTime: 0, + gcTime: Infinity, + retry: 1, + refetchOnWindowFocus: false + }, + mutations: { + retry: 1 + } + } +}) + +// Root component that provides the QueryClient +function App() { + const [toastState, setToastState] = useState({ + open: false, + title: "", + description: "", + variant: "neutral" as const + }) + const [credits, setCredits] = useState(999) // Unlimited credits + const [currentLanguage, setCurrentLanguage] = useState("python") + const [isInitialized, setIsInitialized] = useState(false) + const [hasApiKey, setHasApiKey] = useState(false) + const [apiKeyDialogOpen, setApiKeyDialogOpen] = useState(false) + // Note: Model selection is now handled via separate extraction/solution/debugging model settings + + const [isSettingsOpen, setIsSettingsOpen] = useState(false) + + // Set unlimited credits + const updateCredits = useCallback(() => { + setCredits(999) // No credit limit in this version + window.__CREDITS__ = 999 + }, []) + + // Helper function to safely update language + const updateLanguage = useCallback((newLanguage: string) => { + setCurrentLanguage(newLanguage) + window.__LANGUAGE__ = newLanguage + }, []) + + // Helper function to mark initialization complete + const markInitialized = useCallback(() => { + setIsInitialized(true) + window.__IS_INITIALIZED__ = true + }, []) + + // Show toast method + const showToast = useCallback( + ( + title: string, + description: string, + variant: "neutral" | "success" | "error" + ) => { + setToastState({ + open: true, + title, + description, + variant + }) + }, + [] + ) + + // Check for OpenAI API key and prompt if not found + useEffect(() => { + const checkApiKey = async () => { + try { + const hasKey = await window.electronAPI.checkApiKey() + setHasApiKey(hasKey) + + // If no API key is found, show the settings dialog after a short delay + if (!hasKey) { + setTimeout(() => { + setIsSettingsOpen(true) + }, 1000) + } + } catch (error) { + console.error("Failed to check API key:", error) + } + } + + if (isInitialized) { + checkApiKey() + } + }, [isInitialized]) + + // Initialize dropdown handler + useEffect(() => { + if (isInitialized) { + // Process all types of dropdown elements with a shorter delay + const timer = setTimeout(() => { + // Find both native select elements and custom dropdowns + const selectElements = document.querySelectorAll('select'); + const customDropdowns = document.querySelectorAll('.dropdown-trigger, [role="combobox"], button:has(.dropdown)'); + + // Enable native selects + selectElements.forEach(dropdown => { + dropdown.disabled = false; + }); + + // Enable custom dropdowns by removing any disabled attributes + customDropdowns.forEach(dropdown => { + if (dropdown instanceof HTMLElement) { + dropdown.removeAttribute('disabled'); + dropdown.setAttribute('aria-disabled', 'false'); + } + }); + + console.log(`Enabled ${selectElements.length} select elements and ${customDropdowns.length} custom dropdowns`); + }, 1000); + + return () => clearTimeout(timer); + } + }, [isInitialized]); + + // Listen for settings dialog open requests + useEffect(() => { + const unsubscribeSettings = window.electronAPI.onShowSettings(() => { + console.log("Show settings dialog requested"); + setIsSettingsOpen(true); + }); + + return () => { + unsubscribeSettings(); + }; + }, []); + + // Initialize basic app state + useEffect(() => { + // Load config and set values + const initializeApp = async () => { + try { + // Set unlimited credits + updateCredits() + + // Load config including language and model settings + const config = await window.electronAPI.getConfig() + + // Load language preference + if (config && config.language) { + updateLanguage(config.language) + } else { + updateLanguage("python") + } + + // Model settings are now managed through the settings dialog + // and stored in config as extractionModel, solutionModel, and debuggingModel + + markInitialized() + } catch (error) { + console.error("Failed to initialize app:", error) + // Fallback to defaults + updateLanguage("python") + markInitialized() + } + } + + initializeApp() + + // Event listeners for process events + const onApiKeyInvalid = () => { + showToast( + "API Key Invalid", + "Your OpenAI API key appears to be invalid or has insufficient credits", + "error" + ) + setApiKeyDialogOpen(true) + } + + // Setup API key invalid listener + window.electronAPI.onApiKeyInvalid(onApiKeyInvalid) + + // Define a no-op handler for solution success + const unsubscribeSolutionSuccess = window.electronAPI.onSolutionSuccess( + () => { + console.log("Solution success - no credits deducted in this version") + // No credit deduction in this version + } + ) + + // Cleanup function + return () => { + window.electronAPI.removeListener("API_KEY_INVALID", onApiKeyInvalid) + unsubscribeSolutionSuccess() + window.__IS_INITIALIZED__ = false + setIsInitialized(false) + } + }, [updateCredits, updateLanguage, markInitialized, showToast]) + + // API Key dialog management + const handleOpenSettings = useCallback(() => { + console.log('Opening settings dialog'); + setIsSettingsOpen(true); + }, []); + + const handleCloseSettings = useCallback((open: boolean) => { + console.log('Settings dialog state changed:', open); + setIsSettingsOpen(open); + }, []); + + const handleApiKeySave = useCallback(async (apiKey: string) => { + try { + await window.electronAPI.updateConfig({ apiKey }) + setHasApiKey(true) + showToast("Success", "API key saved successfully", "success") + + // Reload app after a short delay to reinitialize with the new API key + setTimeout(() => { + window.location.reload() + }, 1500) + } catch (error) { + console.error("Failed to save API key:", error) + showToast("Error", "Failed to save API key", "error") + } + }, [showToast]) + + return ( + + + +
+ {isInitialized ? ( + hasApiKey ? ( + + ) : ( + + ) + ) : ( +
+
+
+

+ Initializing... +

+
+
+ )} + +
+ + {/* Settings Dialog */} + + + + setToastState((prev) => ({ ...prev, open })) + } + variant={toastState.variant} + duration={1500} + > + {toastState.title} + {toastState.description} + + +
+
+
+ ) +} + +export default App \ No newline at end of file diff --git a/src/_pages/Debug.tsx b/src/_pages/Debug.tsx new file mode 100644 index 0000000..1060872 --- /dev/null +++ b/src/_pages/Debug.tsx @@ -0,0 +1,466 @@ +// Debug.tsx +import { useQuery, useQueryClient } from "@tanstack/react-query" +import React, { useEffect, useRef, useState } from "react" +import { Prism as SyntaxHighlighter } from "react-syntax-highlighter" +import { dracula } from "react-syntax-highlighter/dist/esm/styles/prism" +import ScreenshotQueue from "../components/Queue/ScreenshotQueue" +import SolutionCommands from "../components/Solutions/SolutionCommands" +import { Screenshot } from "../types/screenshots" +import { ComplexitySection, ContentSection } from "./Solutions" +import { useToast } from "../contexts/toast" + +const CodeSection = ({ + title, + code, + isLoading, + currentLanguage +}: { + title: string + code: React.ReactNode + isLoading: boolean + currentLanguage: string +}) => ( +
+

+ {isLoading ? ( +
+
+

+ Loading solutions... +

+
+
+ ) : ( +
+ + {code as string} + +
+ )} +
+) + +async function fetchScreenshots(): Promise { + try { + const existing = await window.electronAPI.getScreenshots() + console.log("Raw screenshot data in Debug:", existing) + return (Array.isArray(existing) ? existing : []).map((p) => ({ + id: p.path, + path: p.path, + preview: p.preview, + timestamp: Date.now() + })) + } catch (error) { + console.error("Error loading screenshots:", error) + throw error + } +} + +interface DebugProps { + isProcessing: boolean + setIsProcessing: (isProcessing: boolean) => void + currentLanguage: string + setLanguage: (language: string) => void +} + +const Debug: React.FC = ({ + isProcessing, + setIsProcessing, + currentLanguage, + setLanguage +}) => { + const [tooltipVisible, setTooltipVisible] = useState(false) + const [tooltipHeight, setTooltipHeight] = useState(0) + const { showToast } = useToast() + + const { data: screenshots = [], refetch } = useQuery({ + queryKey: ["screenshots"], + queryFn: fetchScreenshots, + staleTime: Infinity, + gcTime: Infinity, + refetchOnWindowFocus: false + }) + + const [newCode, setNewCode] = useState(null) + const [thoughtsData, setThoughtsData] = useState(null) + const [timeComplexityData, setTimeComplexityData] = useState( + null + ) + const [spaceComplexityData, setSpaceComplexityData] = useState( + null + ) + const [debugAnalysis, setDebugAnalysis] = useState(null) + + const queryClient = useQueryClient() + const contentRef = useRef(null) + + useEffect(() => { + // Try to get the new solution data from cache first + const newSolution = queryClient.getQueryData(["new_solution"]) as { + code: string + debug_analysis: string + thoughts: string[] + time_complexity: string + space_complexity: string + } | null + + // If we have cached data, set all state variables to the cached data + if (newSolution) { + console.log("Found cached debug solution:", newSolution); + + if (newSolution.debug_analysis) { + // Store the debug analysis in its own state variable + setDebugAnalysis(newSolution.debug_analysis); + // Set code separately for the code section + setNewCode(newSolution.code || "// Debug mode - see analysis below"); + + // Process thoughts/analysis points + if (newSolution.debug_analysis.includes('\n\n')) { + const sections = newSolution.debug_analysis.split('\n\n').filter(Boolean); + // Pick first few sections as thoughts + setThoughtsData(sections.slice(0, 3)); + } else { + setThoughtsData(["Debug analysis based on your screenshots"]); + } + } else { + // Fallback to code or default + setNewCode(newSolution.code || "// No analysis available"); + setThoughtsData(newSolution.thoughts || ["Debug analysis based on your screenshots"]); + } + setTimeComplexityData(newSolution.time_complexity || "N/A - Debug mode") + setSpaceComplexityData(newSolution.space_complexity || "N/A - Debug mode") + setIsProcessing(false) + } + + // Set up event listeners + const cleanupFunctions = [ + window.electronAPI.onScreenshotTaken(() => refetch()), + window.electronAPI.onResetView(() => refetch()), + window.electronAPI.onDebugSuccess((data) => { + console.log("Debug success event received with data:", data); + queryClient.setQueryData(["new_solution"], data); + + // Also update local state for immediate rendering + if (data.debug_analysis) { + // Store the debug analysis in its own state variable + setDebugAnalysis(data.debug_analysis); + // Set code separately for the code section + setNewCode(data.code || "// Debug mode - see analysis below"); + + // Process thoughts/analysis points + if (data.debug_analysis.includes('\n\n')) { + const sections = data.debug_analysis.split('\n\n').filter(Boolean); + // Pick first few sections as thoughts + setThoughtsData(sections.slice(0, 3)); + } else if (data.debug_analysis.includes('\n')) { + // Try to find bullet points or numbered lists + const lines = data.debug_analysis.split('\n'); + const bulletPoints = lines.filter(line => + line.trim().match(/^[\d*\-•]+\s/) || + line.trim().match(/^[A-Z][\d\.\)\:]/) || + line.includes(':') && line.length < 100 + ); + + if (bulletPoints.length > 0) { + setThoughtsData(bulletPoints.slice(0, 5)); + } else { + setThoughtsData(["Debug analysis based on your screenshots"]); + } + } else { + setThoughtsData(["Debug analysis based on your screenshots"]); + } + } else { + // Fallback to code or default + setNewCode(data.code || "// No analysis available"); + setThoughtsData(data.thoughts || ["Debug analysis based on your screenshots"]); + setDebugAnalysis(null); + } + setTimeComplexityData(data.time_complexity || "N/A - Debug mode"); + setSpaceComplexityData(data.space_complexity || "N/A - Debug mode"); + + setIsProcessing(false); + }), + + window.electronAPI.onDebugStart(() => { + setIsProcessing(true) + }), + window.electronAPI.onDebugError((error: string) => { + showToast( + "Processing Failed", + "There was an error debugging your code.", + "error" + ) + setIsProcessing(false) + console.error("Processing error:", error) + }) + ] + + // Set up resize observer + const updateDimensions = () => { + if (contentRef.current) { + let contentHeight = contentRef.current.scrollHeight + const contentWidth = contentRef.current.scrollWidth + if (tooltipVisible) { + contentHeight += tooltipHeight + } + window.electronAPI.updateContentDimensions({ + width: contentWidth, + height: contentHeight + }) + } + } + + const resizeObserver = new ResizeObserver(updateDimensions) + if (contentRef.current) { + resizeObserver.observe(contentRef.current) + } + updateDimensions() + + return () => { + resizeObserver.disconnect() + cleanupFunctions.forEach((cleanup) => cleanup()) + } + }, [queryClient, setIsProcessing]) + + const handleTooltipVisibilityChange = (visible: boolean, height: number) => { + setTooltipVisible(visible) + setTooltipHeight(height) + } + + const handleDeleteExtraScreenshot = async (index: number) => { + const screenshotToDelete = screenshots[index] + + try { + const response = await window.electronAPI.deleteScreenshot( + screenshotToDelete.path + ) + + if (response.success) { + refetch() + } else { + console.error("Failed to delete extra screenshot:", response.error) + } + } catch (error) { + console.error("Error deleting extra screenshot:", error) + } + } + + return ( +
+
+ {/* Conditionally render the screenshot queue */} +
+
+
+ +
+
+
+ + {/* Navbar of commands with the tooltip */} + + + {/* Main Content */} +
+
+
+ {/* Thoughts Section */} + +
+ {thoughtsData.map((thought, index) => ( +
+
+
{thought}
+
+ ))} +
+
+ ) + } + isLoading={!thoughtsData} + /> + + {/* Code Section */} + + + {/* Debug Analysis Section */} +
+

Analysis & Improvements

+ {!debugAnalysis ? ( +
+
+

+ Loading debug analysis... +

+
+
+ ) : ( +
+ {/* Process the debug analysis text by sections and lines */} + {(() => { + // First identify key sections based on common patterns in the debug output + const sections = []; + let currentSection = { title: '', content: [] }; + + // Split by possible section headers (### or ##) + const mainSections = debugAnalysis.split(/(?=^#{1,3}\s|^\*\*\*|^\s*[A-Z][\w\s]+\s*$)/m); + + // Filter out empty sections and process each one + mainSections.filter(Boolean).forEach(sectionText => { + // First line might be a header + const lines = sectionText.split('\n'); + let title = ''; + let startLineIndex = 0; + + // Check if first line is a header + if (lines[0] && (lines[0].startsWith('#') || lines[0].startsWith('**') || + lines[0].match(/^[A-Z][\w\s]+$/) || lines[0].includes('Issues') || + lines[0].includes('Improvements') || lines[0].includes('Optimizations'))) { + title = lines[0].replace(/^#+\s*|\*\*/g, ''); + startLineIndex = 1; + } + + // Add the section + sections.push({ + title, + content: lines.slice(startLineIndex).filter(Boolean) + }); + }); + + // Render the processed sections + return sections.map((section, sectionIndex) => ( +
+ {section.title && ( +
+ {section.title} +
+ )} +
+ {section.content.map((line, lineIndex) => { + // Handle code blocks - detect full code blocks + if (line.trim().startsWith('```')) { + // If we find the start of a code block, collect all lines until the end + if (line.trim() === '```' || line.trim().startsWith('```')) { + // Find end of this code block + const codeBlockEndIndex = section.content.findIndex( + (l, i) => i > lineIndex && l.trim() === '```' + ); + + if (codeBlockEndIndex > lineIndex) { + // Extract language if specified + const langMatch = line.trim().match(/```(\w+)/); + const language = langMatch ? langMatch[1] : ''; + + // Get the code content + const codeContent = section.content + .slice(lineIndex + 1, codeBlockEndIndex) + .join('\n'); + + // Skip ahead in our loop + lineIndex = codeBlockEndIndex; + + return ( +
+ {codeContent} +
+ ); + } + } + } + + // Handle bullet points + if (line.trim().match(/^[\-*•]\s/) || line.trim().match(/^\d+\.\s/)) { + return ( +
+
+
+ {line.replace(/^[\-*•]\s|^\d+\.\s/, '')} +
+
+ ); + } + + // Handle inline code + if (line.includes('`')) { + const parts = line.split(/(`[^`]+`)/g); + return ( +
+ {parts.map((part, partIndex) => { + if (part.startsWith('`') && part.endsWith('`')) { + return {part.slice(1, -1)}; + } + return {part}; + })} +
+ ); + } + + // Handle sub-headers + if (line.trim().match(/^#+\s/) || (line.trim().match(/^[A-Z][\w\s]+:/) && line.length < 60)) { + return ( +
+ {line.replace(/^#+\s+/, '')} +
+ ); + } + + // Regular text + return
{line}
; + })} +
+
+ )); + })()} +
+ )} +
+ + {/* Complexity Section */} + +
+
+
+
+
+ ) +} + +export default Debug diff --git a/src/_pages/Queue.tsx b/src/_pages/Queue.tsx new file mode 100644 index 0000000..c9194d5 --- /dev/null +++ b/src/_pages/Queue.tsx @@ -0,0 +1,162 @@ +import React, { useState, useEffect, useRef } from "react" +import { useQuery } from "@tanstack/react-query" +import ScreenshotQueue from "../components/Queue/ScreenshotQueue" +import QueueCommands from "../components/Queue/QueueCommands" + +import { useToast } from "../contexts/toast" +import { Screenshot } from "../types/screenshots" + +async function fetchScreenshots(): Promise { + try { + const existing = await window.electronAPI.getScreenshots() + return existing + } catch (error) { + console.error("Error loading screenshots:", error) + throw error + } +} + +interface QueueProps { + setView: (view: "queue" | "solutions" | "debug") => void + credits: number + currentLanguage: string + setLanguage: (language: string) => void +} + +const Queue: React.FC = ({ + setView, + credits, + currentLanguage, + setLanguage +}) => { + const { showToast } = useToast() + + const [isTooltipVisible, setIsTooltipVisible] = useState(false) + const [tooltipHeight, setTooltipHeight] = useState(0) + const contentRef = useRef(null) + + const { + data: screenshots = [], + isLoading, + refetch + } = useQuery({ + queryKey: ["screenshots"], + queryFn: fetchScreenshots, + staleTime: Infinity, + gcTime: Infinity, + refetchOnWindowFocus: false + }) + + const handleDeleteScreenshot = async (index: number) => { + const screenshotToDelete = screenshots[index] + + try { + const response = await window.electronAPI.deleteScreenshot( + screenshotToDelete.path + ) + + if (response.success) { + refetch() // Refetch screenshots instead of managing state directly + } else { + console.error("Failed to delete screenshot:", response.error) + showToast("Error", "Failed to delete the screenshot file", "error") + } + } catch (error) { + console.error("Error deleting screenshot:", error) + } + } + + useEffect(() => { + // Height update logic + const updateDimensions = () => { + if (contentRef.current) { + let contentHeight = contentRef.current.scrollHeight + const contentWidth = contentRef.current.scrollWidth + if (isTooltipVisible) { + contentHeight += tooltipHeight + } + window.electronAPI.updateContentDimensions({ + width: contentWidth, + height: contentHeight + }) + } + } + + // Initialize resize observer + const resizeObserver = new ResizeObserver(updateDimensions) + if (contentRef.current) { + resizeObserver.observe(contentRef.current) + } + updateDimensions() + + // Set up event listeners + const cleanupFunctions = [ + window.electronAPI.onScreenshotTaken(() => refetch()), + window.electronAPI.onResetView(() => refetch()), + window.electronAPI.onDeleteLastScreenshot(async () => { + if (screenshots.length > 0) { + const lastScreenshot = screenshots[screenshots.length - 1]; + await handleDeleteScreenshot(screenshots.length - 1); + // Toast removed as requested + } else { + showToast("No Screenshots", "There are no screenshots to delete", "neutral"); + } + }), + window.electronAPI.onSolutionError((error: string) => { + showToast( + "Processing Failed", + "There was an error processing your screenshots.", + "error" + ) + setView("queue") // Revert to queue if processing fails + console.error("Processing error:", error) + }), + window.electronAPI.onProcessingNoScreenshots(() => { + showToast( + "No Screenshots", + "There are no screenshots to process.", + "neutral" + ) + }), + // Removed out of credits handler - unlimited credits in this version + ] + + return () => { + resizeObserver.disconnect() + cleanupFunctions.forEach((cleanup) => cleanup()) + } + }, [isTooltipVisible, tooltipHeight, screenshots]) + + const handleTooltipVisibilityChange = (visible: boolean, height: number) => { + setIsTooltipVisible(visible) + setTooltipHeight(height) + } + + const handleOpenSettings = () => { + window.electronAPI.openSettingsPortal(); + }; + + return ( +
+
+
+ + + +
+
+
+ ) +} + +export default Queue diff --git a/src/_pages/Solutions.tsx b/src/_pages/Solutions.tsx new file mode 100644 index 0000000..019bf6f --- /dev/null +++ b/src/_pages/Solutions.tsx @@ -0,0 +1,549 @@ +// Solutions.tsx +import React, { useState, useEffect, useRef } from "react" +import { useQuery, useQueryClient } from "@tanstack/react-query" +import { Prism as SyntaxHighlighter } from "react-syntax-highlighter" +import { dracula } from "react-syntax-highlighter/dist/esm/styles/prism" + +import ScreenshotQueue from "../components/Queue/ScreenshotQueue" + +import { ProblemStatementData } from "../types/solutions" +import SolutionCommands from "../components/Solutions/SolutionCommands" +import Debug from "./Debug" +import { useToast } from "../contexts/toast" +import { COMMAND_KEY } from "../utils/platform" + +export const ContentSection = ({ + title, + content, + isLoading +}: { + title: string + content: React.ReactNode + isLoading: boolean +}) => ( +
+

+ {title} +

+ {isLoading ? ( +
+

+ Extracting problem statement... +

+
+ ) : ( +
+ {content} +
+ )} +
+) +const SolutionSection = ({ + title, + content, + isLoading, + currentLanguage +}: { + title: string + content: React.ReactNode + isLoading: boolean + currentLanguage: string +}) => ( +
+

+ {title} +

+ {isLoading ? ( +
+
+

+ Loading solutions... +

+
+
+ ) : ( +
+ + {content as string} + +
+ )} +
+) + +export const ComplexitySection = ({ + timeComplexity, + spaceComplexity, + isLoading +}: { + timeComplexity: string | null + spaceComplexity: string | null + isLoading: boolean +}) => { + // Helper to ensure we have proper complexity values + const formatComplexity = (complexity: string | null): string => { + if (!complexity) return "O(n) - Linear time/space complexity"; + + // Return the complexity as is if it already has Big O notation + if (complexity.match(/O\([^)]+\)/i)) { + return complexity; + } + + // Otherwise, add a default Big O + return `O(n) - ${complexity}`; + }; + + const formattedTimeComplexity = formatComplexity(timeComplexity); + const formattedSpaceComplexity = formatComplexity(spaceComplexity); + + return ( +
+

+ Complexity +

+ {isLoading ? ( +

+ Calculating complexity... +

+ ) : ( +
+
+
+
+
+ Time: {formattedTimeComplexity} +
+
+
+
+
+
+
+ Space: {formattedSpaceComplexity} +
+
+
+
+ )} +
+ ); +} + +export interface SolutionsProps { + setView: (view: "queue" | "solutions" | "debug") => void + credits: number + currentLanguage: string + setLanguage: (language: string) => void +} +const Solutions: React.FC = ({ + setView, + credits, + currentLanguage, + setLanguage +}) => { + const queryClient = useQueryClient() + const contentRef = useRef(null) + + const [debugProcessing, setDebugProcessing] = useState(false) + const [problemStatementData, setProblemStatementData] = + useState(null) + const [solutionData, setSolutionData] = useState(null) + const [thoughtsData, setThoughtsData] = useState(null) + const [timeComplexityData, setTimeComplexityData] = useState( + null + ) + const [spaceComplexityData, setSpaceComplexityData] = useState( + null + ) + + const [isTooltipVisible, setIsTooltipVisible] = useState(false) + const [tooltipHeight, setTooltipHeight] = useState(0) + + const [isResetting, setIsResetting] = useState(false) + + interface Screenshot { + id: string + path: string + preview: string + timestamp: number + } + + const [extraScreenshots, setExtraScreenshots] = useState([]) + + useEffect(() => { + const fetchScreenshots = async () => { + try { + const existing = await window.electronAPI.getScreenshots() + console.log("Raw screenshot data:", existing) + const screenshots = (Array.isArray(existing) ? existing : []).map( + (p) => ({ + id: p.path, + path: p.path, + preview: p.preview, + timestamp: Date.now() + }) + ) + console.log("Processed screenshots:", screenshots) + setExtraScreenshots(screenshots) + } catch (error) { + console.error("Error loading extra screenshots:", error) + setExtraScreenshots([]) + } + } + + fetchScreenshots() + }, [solutionData]) + + const { showToast } = useToast() + + useEffect(() => { + // Height update logic + const updateDimensions = () => { + if (contentRef.current) { + let contentHeight = contentRef.current.scrollHeight + const contentWidth = contentRef.current.scrollWidth + if (isTooltipVisible) { + contentHeight += tooltipHeight + } + window.electronAPI.updateContentDimensions({ + width: contentWidth, + height: contentHeight + }) + } + } + + // Initialize resize observer + const resizeObserver = new ResizeObserver(updateDimensions) + if (contentRef.current) { + resizeObserver.observe(contentRef.current) + } + updateDimensions() + + // Set up event listeners + const cleanupFunctions = [ + window.electronAPI.onScreenshotTaken(async () => { + try { + const existing = await window.electronAPI.getScreenshots() + const screenshots = (Array.isArray(existing) ? existing : []).map( + (p) => ({ + id: p.path, + path: p.path, + preview: p.preview, + timestamp: Date.now() + }) + ) + setExtraScreenshots(screenshots) + } catch (error) { + console.error("Error loading extra screenshots:", error) + } + }), + window.electronAPI.onResetView(() => { + // Set resetting state first + setIsResetting(true) + + // Remove queries + queryClient.removeQueries({ + queryKey: ["solution"] + }) + queryClient.removeQueries({ + queryKey: ["new_solution"] + }) + + // Reset screenshots + setExtraScreenshots([]) + + // After a small delay, clear the resetting state + setTimeout(() => { + setIsResetting(false) + }, 0) + }), + window.electronAPI.onSolutionStart(() => { + // Every time processing starts, reset relevant states + setSolutionData(null) + setThoughtsData(null) + setTimeComplexityData(null) + setSpaceComplexityData(null) + }), + window.electronAPI.onProblemExtracted((data) => { + queryClient.setQueryData(["problem_statement"], data) + }), + //if there was an error processing the initial solution + window.electronAPI.onSolutionError((error: string) => { + showToast("Processing Failed", error, "error") + // Reset solutions in the cache (even though this shouldn't ever happen) and complexities to previous states + const solution = queryClient.getQueryData(["solution"]) as { + code: string + thoughts: string[] + time_complexity: string + space_complexity: string + } | null + if (!solution) { + setView("queue") + } + setSolutionData(solution?.code || null) + setThoughtsData(solution?.thoughts || null) + setTimeComplexityData(solution?.time_complexity || null) + setSpaceComplexityData(solution?.space_complexity || null) + console.error("Processing error:", error) + }), + //when the initial solution is generated, we'll set the solution data to that + window.electronAPI.onSolutionSuccess((data) => { + if (!data) { + console.warn("Received empty or invalid solution data") + return + } + console.log({ data }) + const solutionData = { + code: data.code, + thoughts: data.thoughts, + time_complexity: data.time_complexity, + space_complexity: data.space_complexity + } + + queryClient.setQueryData(["solution"], solutionData) + setSolutionData(solutionData.code || null) + setThoughtsData(solutionData.thoughts || null) + setTimeComplexityData(solutionData.time_complexity || null) + setSpaceComplexityData(solutionData.space_complexity || null) + + // Fetch latest screenshots when solution is successful + const fetchScreenshots = async () => { + try { + const existing = await window.electronAPI.getScreenshots() + const screenshots = + existing.previews?.map((p) => ({ + id: p.path, + path: p.path, + preview: p.preview, + timestamp: Date.now() + })) || [] + setExtraScreenshots(screenshots) + } catch (error) { + console.error("Error loading extra screenshots:", error) + setExtraScreenshots([]) + } + } + fetchScreenshots() + }), + + //######################################################## + //DEBUG EVENTS + //######################################################## + window.electronAPI.onDebugStart(() => { + //we'll set the debug processing state to true and use that to render a little loader + setDebugProcessing(true) + }), + //the first time debugging works, we'll set the view to debug and populate the cache with the data + window.electronAPI.onDebugSuccess((data) => { + queryClient.setQueryData(["new_solution"], data) + setDebugProcessing(false) + }), + //when there was an error in the initial debugging, we'll show a toast and stop the little generating pulsing thing. + window.electronAPI.onDebugError(() => { + showToast( + "Processing Failed", + "There was an error debugging your code.", + "error" + ) + setDebugProcessing(false) + }), + window.electronAPI.onProcessingNoScreenshots(() => { + showToast( + "No Screenshots", + "There are no extra screenshots to process.", + "neutral" + ) + }), + // Removed out of credits handler - unlimited credits in this version + ] + + return () => { + resizeObserver.disconnect() + cleanupFunctions.forEach((cleanup) => cleanup()) + } + }, [isTooltipVisible, tooltipHeight]) + + useEffect(() => { + setProblemStatementData( + queryClient.getQueryData(["problem_statement"]) || null + ) + setSolutionData(queryClient.getQueryData(["solution"]) || null) + + const unsubscribe = queryClient.getQueryCache().subscribe((event) => { + if (event?.query.queryKey[0] === "problem_statement") { + setProblemStatementData( + queryClient.getQueryData(["problem_statement"]) || null + ) + } + if (event?.query.queryKey[0] === "solution") { + const solution = queryClient.getQueryData(["solution"]) as { + code: string + thoughts: string[] + time_complexity: string + space_complexity: string + } | null + + setSolutionData(solution?.code ?? null) + setThoughtsData(solution?.thoughts ?? null) + setTimeComplexityData(solution?.time_complexity ?? null) + setSpaceComplexityData(solution?.space_complexity ?? null) + } + }) + return () => unsubscribe() + }, [queryClient]) + + const handleTooltipVisibilityChange = (visible: boolean, height: number) => { + setIsTooltipVisible(visible) + setTooltipHeight(height) + } + + const handleDeleteExtraScreenshot = async (index: number) => { + const screenshotToDelete = extraScreenshots[index] + + try { + const response = await window.electronAPI.deleteScreenshot( + screenshotToDelete.path + ) + + if (response.success) { + // Fetch and update screenshots after successful deletion + const existing = await window.electronAPI.getScreenshots() + const screenshots = (Array.isArray(existing) ? existing : []).map( + (p) => ({ + id: p.path, + path: p.path, + preview: p.preview, + timestamp: Date.now() + }) + ) + setExtraScreenshots(screenshots) + } else { + console.error("Failed to delete extra screenshot:", response.error) + showToast("Error", "Failed to delete the screenshot", "error") + } + } catch (error) { + console.error("Error deleting extra screenshot:", error) + showToast("Error", "Failed to delete the screenshot", "error") + } + } + + return ( + <> + {!isResetting && queryClient.getQueryData(["new_solution"]) ? ( + + ) : ( +
+
+ {/* Conditionally render the screenshot queue if solutionData is available */} + {solutionData && ( +
+
+
+ +
+
+
+ )} + + {/* Navbar of commands with the SolutionsHelper */} + + + {/* Main Content - Modified width constraints */} +
+
+
+ {!solutionData && ( + <> + + {problemStatementData && ( +
+

+ Generating solutions... +

+
+ )} + + )} + + {solutionData && ( + <> + +
+ {thoughtsData.map((thought, index) => ( +
+
+
{thought}
+
+ ))} +
+
+ ) + } + isLoading={!thoughtsData} + /> + + + + + + )} +
+
+
+
+
+ )} + + ) +} + +export default Solutions diff --git a/src/_pages/SubscribePage.tsx b/src/_pages/SubscribePage.tsx new file mode 100644 index 0000000..7b4dc07 --- /dev/null +++ b/src/_pages/SubscribePage.tsx @@ -0,0 +1,161 @@ +import { useState, useRef, useEffect } from "react" +import { supabase } from "../lib/supabase" +import { User } from "@supabase/supabase-js" + +interface SubscribePageProps { + user: User +} + +export default function SubscribePage({ user }: SubscribePageProps) { + const [error, setError] = useState(null) + const containerRef = useRef(null) + + useEffect(() => { + const updateDimensions = () => { + if (containerRef.current) { + window.electronAPI.updateContentDimensions({ + width: 400, // Fixed width + height: 400 // Fixed height + }) + } + } + + updateDimensions() + }, []) + + const handleSignOut = async () => { + try { + const { error: signOutError } = await supabase.auth.signOut() + if (signOutError) throw signOutError + } catch (err) { + console.error("Error signing out:", err) + setError("Failed to sign out. Please try again.") + setTimeout(() => setError(null), 3000) + } + } + + const handleSubscribe = async () => { + if (!user) return + + try { + const result = await window.electronAPI.openSubscriptionPortal({ + id: user.id, + email: user.email! + }) + + if (!result.success) { + throw new Error(result.error || "Failed to open subscription portal") + } + } catch (err) { + console.error("Error opening subscription portal:", err) + setError("Failed to open subscription portal. Please try again.") + setTimeout(() => setError(null), 3000) + } + } + + return ( +
+
+
+

+ Welcome to Interview Coder +

+

+ To continue using Interview Coder, you'll need to subscribe + ($60/month) +

+

+ * Undetectability may not work with some versions of MacOS. See our + help center for more details +

+ + {/* Keyboard Shortcuts */} +
+
+
+ Toggle Visibility +
+ + ⌘ + + + B + +
+
+
+ Quit App +
+ + ⌘ + + + Q + +
+
+
+
+ + {/* Subscribe Button */} + + + {/* Logout Section */} +
+ +
+ + {error && ( +
+

{error}

+
+ )} +
+
+
+ ) +} diff --git a/src/_pages/SubscribedApp.tsx b/src/_pages/SubscribedApp.tsx new file mode 100644 index 0000000..2163e86 --- /dev/null +++ b/src/_pages/SubscribedApp.tsx @@ -0,0 +1,158 @@ +// file: src/components/SubscribedApp.tsx +import { useQueryClient } from "@tanstack/react-query" +import { useEffect, useRef, useState } from "react" +import Queue from "../_pages/Queue" +import Solutions from "../_pages/Solutions" +import { useToast } from "../contexts/toast" + +interface SubscribedAppProps { + credits: number + currentLanguage: string + setLanguage: (language: string) => void +} + +const SubscribedApp: React.FC = ({ + credits, + currentLanguage, + setLanguage +}) => { + const queryClient = useQueryClient() + const [view, setView] = useState<"queue" | "solutions" | "debug">("queue") + const containerRef = useRef(null) + const { showToast } = useToast() + + // Let's ensure we reset queries etc. if some electron signals happen + useEffect(() => { + const cleanup = window.electronAPI.onResetView(() => { + queryClient.invalidateQueries({ + queryKey: ["screenshots"] + }) + queryClient.invalidateQueries({ + queryKey: ["problem_statement"] + }) + queryClient.invalidateQueries({ + queryKey: ["solution"] + }) + queryClient.invalidateQueries({ + queryKey: ["new_solution"] + }) + setView("queue") + }) + + return () => { + cleanup() + } + }, []) + + // Dynamically update the window size + useEffect(() => { + if (!containerRef.current) return + + const updateDimensions = () => { + if (!containerRef.current) return + const height = containerRef.current.scrollHeight || 600 + const width = containerRef.current.scrollWidth || 800 + window.electronAPI?.updateContentDimensions({ width, height }) + } + + // Force initial dimension update immediately + updateDimensions() + + // Set a fallback timer to ensure dimensions are set even if content isn't fully loaded + const fallbackTimer = setTimeout(() => { + window.electronAPI?.updateContentDimensions({ width: 800, height: 600 }) + }, 500) + + const resizeObserver = new ResizeObserver(updateDimensions) + resizeObserver.observe(containerRef.current) + + // Also watch DOM changes + const mutationObserver = new MutationObserver(updateDimensions) + mutationObserver.observe(containerRef.current, { + childList: true, + subtree: true, + attributes: true, + characterData: true + }) + + // Do another update after a delay to catch any late-loading content + const delayedUpdate = setTimeout(updateDimensions, 1000) + + return () => { + resizeObserver.disconnect() + mutationObserver.disconnect() + clearTimeout(fallbackTimer) + clearTimeout(delayedUpdate) + } + }, [view]) + + // Listen for events that might switch views or show errors + useEffect(() => { + const cleanupFunctions = [ + window.electronAPI.onSolutionStart(() => { + setView("solutions") + }), + window.electronAPI.onUnauthorized(() => { + queryClient.removeQueries({ + queryKey: ["screenshots"] + }) + queryClient.removeQueries({ + queryKey: ["solution"] + }) + queryClient.removeQueries({ + queryKey: ["problem_statement"] + }) + setView("queue") + }), + window.electronAPI.onResetView(() => { + queryClient.removeQueries({ + queryKey: ["screenshots"] + }) + queryClient.removeQueries({ + queryKey: ["solution"] + }) + queryClient.removeQueries({ + queryKey: ["problem_statement"] + }) + setView("queue") + }), + window.electronAPI.onResetView(() => { + queryClient.setQueryData(["problem_statement"], null) + }), + window.electronAPI.onProblemExtracted((data: any) => { + if (view === "queue") { + queryClient.invalidateQueries({ + queryKey: ["problem_statement"] + }) + queryClient.setQueryData(["problem_statement"], data) + } + }), + window.electronAPI.onSolutionError((error: string) => { + showToast("Error", error, "error") + }) + ] + return () => cleanupFunctions.forEach((fn) => fn()) + }, [view]) + + return ( +
+ {view === "queue" ? ( + + ) : view === "solutions" ? ( + + ) : null} +
+ ) +} + +export default SubscribedApp diff --git a/src/components/Header/Header.tsx b/src/components/Header/Header.tsx new file mode 100644 index 0000000..b82b799 --- /dev/null +++ b/src/components/Header/Header.tsx @@ -0,0 +1,132 @@ +import React, { useState } from 'react'; +import { Settings, LogOut, ChevronDown, ChevronUp } from 'lucide-react'; +import { Button } from '../ui/button'; +import { useToast } from '../../contexts/toast'; + +interface HeaderProps { + currentLanguage: string; + setLanguage: (language: string) => void; + onOpenSettings: () => void; +} + +// Available programming languages +const LANGUAGES = [ + { value: 'python', label: 'Python' }, + { value: 'javascript', label: 'JavaScript' }, + { value: 'java', label: 'Java' }, + { value: 'cpp', label: 'C++' }, + { value: 'csharp', label: 'C#' }, + { value: 'go', label: 'Go' }, + { value: 'rust', label: 'Rust' }, + { value: 'typescript', label: 'TypeScript' }, +]; + +export function Header({ currentLanguage, setLanguage, onOpenSettings }: HeaderProps) { + const [dropdownOpen, setDropdownOpen] = useState(false); + const { showToast } = useToast(); + + // Handle logout - clear API key and reload app + const handleLogout = async () => { + try { + // Update config with empty API key + await window.electronAPI.updateConfig({ + apiKey: '', + }); + + showToast('Success', 'Logged out successfully', 'success'); + + // Reload the app after a short delay + setTimeout(() => { + window.location.reload(); + }, 1500); + } catch (error) { + console.error('Error logging out:', error); + showToast('Error', 'Failed to log out', 'error'); + } + }; + + // Handle language selection + const handleLanguageSelect = (lang: string) => { + setLanguage(lang); + setDropdownOpen(false); + + // Also save the language preference to config + window.electronAPI.updateConfig({ + language: lang + }).catch(error => { + console.error('Failed to save language preference:', error); + }); + }; + + const toggleDropdown = () => { + setDropdownOpen(!dropdownOpen); + }; + + // Find the current language object + const currentLangObj = LANGUAGES.find(lang => lang.value === currentLanguage) || LANGUAGES[0]; + + return ( +
+
+ Language: +
+ + + {dropdownOpen && ( +
+
+ {LANGUAGES.map((lang) => ( + + ))} +
+
+ )} +
+
+ +
+ + + +
+
+ ); +} diff --git a/src/components/Queue/QueueCommands.tsx b/src/components/Queue/QueueCommands.tsx new file mode 100644 index 0000000..1f8d471 --- /dev/null +++ b/src/components/Queue/QueueCommands.tsx @@ -0,0 +1,434 @@ +import React, { useState, useEffect, useRef } from "react" + +import { useToast } from "../../contexts/toast" +import { LanguageSelector } from "../shared/LanguageSelector" +import { COMMAND_KEY } from "../../utils/platform" + +interface QueueCommandsProps { + onTooltipVisibilityChange: (visible: boolean, height: number) => void + screenshotCount?: number + credits: number + currentLanguage: string + setLanguage: (language: string) => void +} + +const QueueCommands: React.FC = ({ + onTooltipVisibilityChange, + screenshotCount = 0, + credits, + currentLanguage, + setLanguage +}) => { + const [isTooltipVisible, setIsTooltipVisible] = useState(false) + const tooltipRef = useRef(null) + const { showToast } = useToast() + + useEffect(() => { + let tooltipHeight = 0 + if (tooltipRef.current && isTooltipVisible) { + tooltipHeight = tooltipRef.current.offsetHeight + 10 + } + onTooltipVisibilityChange(isTooltipVisible, tooltipHeight) + }, [isTooltipVisible]) + + const handleSignOut = async () => { + try { + // Clear any local storage or electron-specific data + localStorage.clear(); + sessionStorage.clear(); + + // Clear the API key in the configuration + await window.electronAPI.updateConfig({ + apiKey: '', + }); + + showToast('Success', 'Logged out successfully', 'success'); + + // Reload the app after a short delay + setTimeout(() => { + window.location.reload(); + }, 1500); + } catch (err) { + console.error("Error logging out:", err); + showToast('Error', 'Failed to log out', 'error'); + } + } + + const handleMouseEnter = () => { + setIsTooltipVisible(true) + } + + const handleMouseLeave = () => { + setIsTooltipVisible(false) + } + + return ( +
+
+
+ {/* Screenshot */} +
{ + try { + const result = await window.electronAPI.triggerScreenshot() + if (!result.success) { + console.error("Failed to take screenshot:", result.error) + showToast("Error", "Failed to take screenshot", "error") + } + } catch (error) { + console.error("Error taking screenshot:", error) + showToast("Error", "Failed to take screenshot", "error") + } + }} + > + + {screenshotCount === 0 + ? "Take first screenshot" + : screenshotCount === 1 + ? "Take second screenshot" + : screenshotCount === 2 + ? "Take third screenshot" + : screenshotCount === 3 + ? "Take fourth screenshot" + : screenshotCount === 4 + ? "Take fifth screenshot" + : "Next will replace first screenshot"} + +
+ + +
+
+ + {/* Solve Command */} + {screenshotCount > 0 && ( +
{ + + try { + const result = + await window.electronAPI.triggerProcessScreenshots() + if (!result.success) { + console.error( + "Failed to process screenshots:", + result.error + ) + showToast("Error", "Failed to process screenshots", "error") + } + } catch (error) { + console.error("Error processing screenshots:", error) + showToast("Error", "Failed to process screenshots", "error") + } + }} + > +
+ Solve +
+ + +
+
+
+ )} + + {/* Separator */} +
+ + {/* Settings with Tooltip */} +
+ {/* Gear icon */} +
+ + + + +
+ + {/* Tooltip Content */} + {isTooltipVisible && ( +
+ {/* Add transparent bridge */} +
+
+
+

Keyboard Shortcuts

+
+ {/* Toggle Command */} +
{ + try { + const result = + await window.electronAPI.toggleMainWindow() + if (!result.success) { + console.error( + "Failed to toggle window:", + result.error + ) + showToast( + "Error", + "Failed to toggle window", + "error" + ) + } + } catch (error) { + console.error("Error toggling window:", error) + showToast( + "Error", + "Failed to toggle window", + "error" + ) + } + }} + > +
+ Toggle Window +
+ + {COMMAND_KEY} + + + B + +
+
+

+ Show or hide this window. +

+
+ + {/* Screenshot Command */} +
{ + try { + const result = + await window.electronAPI.triggerScreenshot() + if (!result.success) { + console.error( + "Failed to take screenshot:", + result.error + ) + showToast( + "Error", + "Failed to take screenshot", + "error" + ) + } + } catch (error) { + console.error("Error taking screenshot:", error) + showToast( + "Error", + "Failed to take screenshot", + "error" + ) + } + }} + > +
+ Take Screenshot +
+ + {COMMAND_KEY} + + + H + +
+
+

+ Take a screenshot of the problem description. +

+
+ + {/* Solve Command */} +
0 + ? "" + : "opacity-50 cursor-not-allowed" + }`} + onClick={async () => { + if (screenshotCount === 0) return + + try { + const result = + await window.electronAPI.triggerProcessScreenshots() + if (!result.success) { + console.error( + "Failed to process screenshots:", + result.error + ) + showToast( + "Error", + "Failed to process screenshots", + "error" + ) + } + } catch (error) { + console.error( + "Error processing screenshots:", + error + ) + showToast( + "Error", + "Failed to process screenshots", + "error" + ) + } + }} + > +
+ Solve +
+ + {COMMAND_KEY} + + + ↵ + +
+
+

+ {screenshotCount > 0 + ? "Generate a solution based on the current problem." + : "Take a screenshot first to generate a solution."} +

+
+ + {/* Delete Last Screenshot Command */} +
0 + ? "" + : "opacity-50 cursor-not-allowed" + }`} + onClick={async () => { + if (screenshotCount === 0) return + + try { + const result = await window.electronAPI.deleteLastScreenshot() + if (!result.success) { + console.error( + "Failed to delete last screenshot:", + result.error + ) + showToast( + "Error", + result.error || "Failed to delete screenshot", + "error" + ) + } + } catch (error) { + console.error("Error deleting screenshot:", error) + showToast( + "Error", + "Failed to delete screenshot", + "error" + ) + } + }} + > +
+ Delete Last Screenshot +
+ + {COMMAND_KEY} + + + L + +
+
+

+ {screenshotCount > 0 + ? "Remove the most recently taken screenshot." + : "No screenshots to delete."} +

+
+
+ + {/* Separator and Log Out */} +
+ + + {/* API Key Settings */} +
+
+ OpenAI API Settings + +
+
+ + +
+
+
+
+ )} +
+
+
+
+ ) +} + +export default QueueCommands diff --git a/src/components/Queue/ScreenshotItem.tsx b/src/components/Queue/ScreenshotItem.tsx new file mode 100644 index 0000000..bf4859b --- /dev/null +++ b/src/components/Queue/ScreenshotItem.tsx @@ -0,0 +1,67 @@ +// src/components/ScreenshotItem.tsx +import React from "react" +import { X } from "lucide-react" + +interface Screenshot { + path: string + preview: string +} + +interface ScreenshotItemProps { + screenshot: Screenshot + onDelete: (index: number) => void + index: number + isLoading: boolean +} + +const ScreenshotItem: React.FC = ({ + screenshot, + onDelete, + index, + isLoading +}) => { + const handleDelete = async () => { + await onDelete(index) + } + + return ( + <> +
+
+ {isLoading && ( +
+
+
+ )} + Screenshot +
+ {!isLoading && ( + + )} +
+ + ) +} + +export default ScreenshotItem diff --git a/src/components/Queue/ScreenshotQueue.tsx b/src/components/Queue/ScreenshotQueue.tsx new file mode 100644 index 0000000..a2a5b23 --- /dev/null +++ b/src/components/Queue/ScreenshotQueue.tsx @@ -0,0 +1,40 @@ +import React from "react" +import ScreenshotItem from "./ScreenshotItem" + +interface Screenshot { + path: string + preview: string +} + +interface ScreenshotQueueProps { + isLoading: boolean + screenshots: Screenshot[] + onDeleteScreenshot: (index: number) => void +} +const ScreenshotQueue: React.FC = ({ + isLoading, + screenshots, + onDeleteScreenshot +}) => { + if (screenshots.length === 0) { + return <> + } + + const displayScreenshots = screenshots.slice(0, 5) + + return ( +
+ {displayScreenshots.map((screenshot, index) => ( + + ))} +
+ ) +} + +export default ScreenshotQueue diff --git a/src/components/Settings/SettingsDialog.tsx b/src/components/Settings/SettingsDialog.tsx new file mode 100644 index 0000000..be685c2 --- /dev/null +++ b/src/components/Settings/SettingsDialog.tsx @@ -0,0 +1,355 @@ +import { useState, useEffect } from "react"; +import { + Dialog, + DialogTrigger, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, + DialogFooter, +} from "../ui/dialog"; +import { Input } from "../ui/input"; +import { Button } from "../ui/button"; +import { Settings } from "lucide-react"; +import { useToast } from "../../contexts/toast"; + +type OpenAIModel = { + id: string; + name: string; + description: string; +}; + +type ModelCategory = { + key: 'extractionModel' | 'solutionModel' | 'debuggingModel'; + title: string; + description: string; + models: OpenAIModel[]; +}; + +// Define available models for each category +const modelCategories: ModelCategory[] = [ + { + key: 'extractionModel', + title: 'Problem Extraction', + description: 'Model used to analyze screenshots and extract problem details', + models: [ + { + id: "gpt-4o", + name: "gpt-4o", + description: "Best overall performance for problem extraction" + }, + { + id: "gpt-4o-mini", + name: "gpt-4o-mini", + description: "Faster, more cost-effective option" + } + ] + }, + { + key: 'solutionModel', + title: 'Solution Generation', + description: 'Model used to generate coding solutions', + models: [ + { + id: "gpt-4o", + name: "gpt-4o", + description: "Strong overall performance for coding tasks" + }, + { + id: "gpt-4o-mini", + name: "gpt-4o-mini", + description: "Faster, more cost-effective option" + } + ] + }, + { + key: 'debuggingModel', + title: 'Debugging', + description: 'Model used to debug and improve solutions', + models: [ + { + id: "gpt-4o", + name: "gpt-4o", + description: "Best for analyzing code and error messages" + }, + { + id: "gpt-4o-mini", + name: "gpt-4o-mini", + description: "Faster, more cost-effective option" + } + ] + } +]; + +interface SettingsDialogProps { + open?: boolean; + onOpenChange?: (open: boolean) => void; +} + +export function SettingsDialog({ open: externalOpen, onOpenChange }: SettingsDialogProps) { + const [open, setOpen] = useState(externalOpen || false); + const [apiKey, setApiKey] = useState(""); + const [extractionModel, setExtractionModel] = useState("gpt-4o"); + const [solutionModel, setSolutionModel] = useState("gpt-4o"); + const [debuggingModel, setDebuggingModel] = useState("gpt-4o"); + const [isLoading, setIsLoading] = useState(false); + const { showToast } = useToast(); + + // Sync with external open state + useEffect(() => { + if (externalOpen !== undefined) { + setOpen(externalOpen); + } + }, [externalOpen]); + + // Handle open state changes + const handleOpenChange = (newOpen: boolean) => { + setOpen(newOpen); + // Only call onOpenChange when there's actually a change + if (onOpenChange && newOpen !== externalOpen) { + onOpenChange(newOpen); + } + }; + + // Load current config on dialog open + useEffect(() => { + if (open) { + setIsLoading(true); + window.electronAPI + .getConfig() + .then((config) => { + setApiKey(config.apiKey || ""); + setExtractionModel(config.extractionModel || "gpt-4o"); + setSolutionModel(config.solutionModel || "gpt-4o"); + setDebuggingModel(config.debuggingModel || "gpt-4o"); + }) + .catch((error) => { + console.error("Failed to load config:", error); + showToast("Error", "Failed to load settings", "error"); + }) + .finally(() => { + setIsLoading(false); + }); + } + }, [open, showToast]); + + const handleSave = async () => { + setIsLoading(true); + try { + const result = await window.electronAPI.updateConfig({ + apiKey, + extractionModel, + solutionModel, + debuggingModel, + }); + + if (result) { + showToast("Success", "Settings saved successfully", "success"); + handleOpenChange(false); + + // Force reload the app to apply the API key + setTimeout(() => { + window.location.reload(); + }, 1500); + } + } catch (error) { + console.error("Failed to save settings:", error); + showToast("Error", "Failed to save settings", "error"); + } finally { + setIsLoading(false); + } + }; + + // Mask API key for display + const maskApiKey = (key: string) => { + if (!key || key.length < 10) return ""; + return `${key.substring(0, 4)}...${key.substring(key.length - 4)}`; + }; + + // Open external link handler + const openExternalLink = (url: string) => { + window.electronAPI.openLink(url); + }; + + return ( + + {/* Removed unnecessary dialog trigger - using the icon in QueueCommands instead */} + + OpenAI API Settings + + Configure your OpenAI API key and model preferences. You'll need your own OpenAI API key to use this application. + + +
+
+ + setApiKey(e.target.value)} + placeholder="sk-..." + className="bg-black/50 border-white/10 text-white" + /> + {apiKey && ( +

+ Current: {maskApiKey(apiKey)} +

+ )} +

+ Your API key is stored locally and never sent to any server except OpenAI +

+
+

Don't have an API key?

+

1. Create an account at +

+

2. Go to section +

+

3. Create a new secret key and paste it here

+
+
+ +
+ +
+
+
Toggle Visibility
+
Ctrl+B / Cmd+B
+ +
Take Screenshot
+
Ctrl+H / Cmd+H
+ +
Process Screenshots
+
Ctrl+Enter / Cmd+Enter
+ +
Delete Last Screenshot
+
Ctrl+L / Cmd+L
+ +
Reset View
+
Ctrl+R / Cmd+R
+ +
Quit Application
+
Ctrl+Q / Cmd+Q
+ +
Move Window
+
Ctrl+Arrow Keys
+ +
Decrease Opacity
+
Ctrl+[ / Cmd+[
+ +
Increase Opacity
+
Ctrl+] / Cmd+]
+ +
Zoom Out
+
Ctrl+- / Cmd+-
+ +
Reset Zoom
+
Ctrl+0 / Cmd+0
+ +
Zoom In
+
Ctrl+= / Cmd+=
+
+
+
+ +
+ +

+ Select which models to use for each stage of the process +

+ + {modelCategories.map((category) => ( +
+ +

{category.description}

+ +
+ {category.models.map((m) => { + // Determine which state to use based on category key + const currentValue = + category.key === 'extractionModel' ? extractionModel : + category.key === 'solutionModel' ? solutionModel : + debuggingModel; + + // Determine which setter function to use + const setValue = + category.key === 'extractionModel' ? setExtractionModel : + category.key === 'solutionModel' ? setSolutionModel : + setDebuggingModel; + + return ( +
setValue(m.id)} + > +
+
+
+

{m.name}

+

{m.description}

+
+
+
+ ); + })} +
+
+ ))} +
+
+ + + + + +
+ ); +} \ No newline at end of file diff --git a/src/components/Solutions/SolutionCommands.tsx b/src/components/Solutions/SolutionCommands.tsx new file mode 100644 index 0000000..4949729 --- /dev/null +++ b/src/components/Solutions/SolutionCommands.tsx @@ -0,0 +1,466 @@ +import React, { useState, useEffect, useRef } from "react" +import { useToast } from "../../contexts/toast" +import { Screenshot } from "../../types/screenshots" +import { supabase } from "../../lib/supabase" +import { LanguageSelector } from "../shared/LanguageSelector" +import { COMMAND_KEY } from "../../utils/platform" + +export interface SolutionCommandsProps { + onTooltipVisibilityChange: (visible: boolean, height: number) => void + isProcessing: boolean + screenshots?: Screenshot[] + extraScreenshots?: Screenshot[] + credits: number + currentLanguage: string + setLanguage: (language: string) => void +} + +const handleSignOut = async () => { + try { + // Clear any local storage or electron-specific data first + localStorage.clear() + sessionStorage.clear() + + // Then sign out from Supabase + const { error } = await supabase.auth.signOut() + if (error) throw error + } catch (err) { + console.error("Error signing out:", err) + } +} + +const SolutionCommands: React.FC = ({ + onTooltipVisibilityChange, + isProcessing, + extraScreenshots = [], + credits, + currentLanguage, + setLanguage +}) => { + const [isTooltipVisible, setIsTooltipVisible] = useState(false) + const tooltipRef = useRef(null) + const { showToast } = useToast() + + useEffect(() => { + if (onTooltipVisibilityChange) { + let tooltipHeight = 0 + if (tooltipRef.current && isTooltipVisible) { + tooltipHeight = tooltipRef.current.offsetHeight + 10 // Adjust if necessary + } + onTooltipVisibilityChange(isTooltipVisible, tooltipHeight) + } + }, [isTooltipVisible, onTooltipVisibilityChange]) + + const handleMouseEnter = () => { + setIsTooltipVisible(true) + } + + const handleMouseLeave = () => { + setIsTooltipVisible(false) + } + + return ( +
+
+
+ {/* Show/Hide - Always visible */} +
{ + try { + const result = await window.electronAPI.toggleMainWindow() + if (!result.success) { + console.error("Failed to toggle window:", result.error) + showToast("Error", "Failed to toggle window", "error") + } + } catch (error) { + console.error("Error toggling window:", error) + showToast("Error", "Failed to toggle window", "error") + } + }} + > + Show/Hide +
+ + +
+
+ + {/* Screenshot and Debug commands - Only show if not processing */} + {!isProcessing && ( + <> +
{ + try { + const result = await window.electronAPI.triggerScreenshot() + if (!result.success) { + console.error("Failed to take screenshot:", result.error) + showToast("Error", "Failed to take screenshot", "error") + } + } catch (error) { + console.error("Error taking screenshot:", error) + showToast("Error", "Failed to take screenshot", "error") + } + }} + > + + {extraScreenshots.length === 0 + ? "Screenshot your code" + : "Screenshot"} + +
+ + +
+
+ + {extraScreenshots.length > 0 && ( +
{ + try { + const result = + await window.electronAPI.triggerProcessScreenshots() + if (!result.success) { + console.error( + "Failed to process screenshots:", + result.error + ) + showToast( + "Error", + "Failed to process screenshots", + "error" + ) + } + } catch (error) { + console.error("Error processing screenshots:", error) + showToast( + "Error", + "Failed to process screenshots", + "error" + ) + } + }} + > + Debug +
+ + +
+
+ )} + + )} + + {/* Start Over - Always visible */} +
{ + try { + const result = await window.electronAPI.triggerReset() + if (!result.success) { + console.error("Failed to reset:", result.error) + showToast("Error", "Failed to reset", "error") + } + } catch (error) { + console.error("Error resetting:", error) + showToast("Error", "Failed to reset", "error") + } + }} + > + Start Over +
+ + +
+
+ + {/* Separator */} +
+ + {/* Settings with Tooltip */} +
+ {/* Gear icon */} +
+ + + + +
+ + {/* Tooltip Content */} + {isTooltipVisible && ( +
+ {/* Add transparent bridge */} +
+
+
+

+ Keyboard Shortcuts +

+
+ {/* Show/Hide - Always visible */} +
{ + try { + const result = + await window.electronAPI.toggleMainWindow() + if (!result.success) { + console.error( + "Failed to toggle window:", + result.error + ) + showToast( + "Error", + "Failed to toggle window", + "error" + ) + } + } catch (error) { + console.error("Error toggling window:", error) + showToast( + "Error", + "Failed to toggle window", + "error" + ) + } + }} + > +
+ Toggle Window +
+ + {COMMAND_KEY} + + + B + +
+
+

+ Show or hide this window. +

+
+ + {/* Screenshot and Debug commands - Only show if not processing */} + {!isProcessing && ( + <> +
{ + try { + const result = + await window.electronAPI.triggerScreenshot() + if (!result.success) { + console.error( + "Failed to take screenshot:", + result.error + ) + showToast( + "Error", + "Failed to take screenshot", + "error" + ) + } + } catch (error) { + console.error("Error taking screenshot:", error) + showToast( + "Error", + "Failed to take screenshot", + "error" + ) + } + }} + > +
+ Take Screenshot +
+ + {COMMAND_KEY} + + + H + +
+
+

+ Capture additional parts of the question or your + solution for debugging help. +

+
+ + {extraScreenshots.length > 0 && ( +
{ + try { + const result = + await window.electronAPI.triggerProcessScreenshots() + if (!result.success) { + console.error( + "Failed to process screenshots:", + result.error + ) + showToast( + "Error", + "Failed to process screenshots", + "error" + ) + } + } catch (error) { + console.error( + "Error processing screenshots:", + error + ) + showToast( + "Error", + "Failed to process screenshots", + "error" + ) + } + }} + > +
+ Debug +
+ + {COMMAND_KEY} + + + ↵ + +
+
+

+ Generate new solutions based on all previous and + newly added screenshots. +

+
+ )} + + )} + + {/* Start Over - Always visible */} +
{ + try { + const result = + await window.electronAPI.triggerReset() + if (!result.success) { + console.error("Failed to reset:", result.error) + showToast("Error", "Failed to reset", "error") + } + } catch (error) { + console.error("Error resetting:", error) + showToast("Error", "Failed to reset", "error") + } + }} + > +
+ Start Over +
+ + {COMMAND_KEY} + + + R + +
+
+

+ Start fresh with a new question. +

+
+
+ + {/* Separator and Log Out */} +
+ + + {/* API Key Settings */} +
+
+ OpenAI API Settings + +
+
+ + +
+
+
+
+ )} +
+
+
+
+ ) +} + +export default SolutionCommands diff --git a/src/components/UpdateNotification.tsx b/src/components/UpdateNotification.tsx new file mode 100644 index 0000000..528101b --- /dev/null +++ b/src/components/UpdateNotification.tsx @@ -0,0 +1,101 @@ +import React, { useEffect, useState } from "react" +import { Dialog, DialogContent } from "./ui/dialog" +import { Button } from "./ui/button" +import { useToast } from "../contexts/toast" + +export const UpdateNotification: React.FC = () => { + const [updateAvailable, setUpdateAvailable] = useState(false) + const [updateDownloaded, setUpdateDownloaded] = useState(false) + const [isDownloading, setIsDownloading] = useState(false) + const { showToast } = useToast() + + useEffect(() => { + console.log("UpdateNotification: Setting up event listeners") + + const unsubscribeAvailable = window.electronAPI.onUpdateAvailable( + (info) => { + console.log("UpdateNotification: Update available received", info) + setUpdateAvailable(true) + } + ) + + const unsubscribeDownloaded = window.electronAPI.onUpdateDownloaded( + (info) => { + console.log("UpdateNotification: Update downloaded received", info) + setUpdateDownloaded(true) + setIsDownloading(false) + } + ) + + return () => { + console.log("UpdateNotification: Cleaning up event listeners") + unsubscribeAvailable() + unsubscribeDownloaded() + } + }, []) + + const handleStartUpdate = async () => { + console.log("UpdateNotification: Starting update download") + setIsDownloading(true) + const result = await window.electronAPI.startUpdate() + console.log("UpdateNotification: Update download result", result) + if (!result.success) { + setIsDownloading(false) + showToast("Error", "Failed to download update", "error") + } + } + + const handleInstallUpdate = () => { + console.log("UpdateNotification: Installing update") + window.electronAPI.installUpdate() + } + + console.log("UpdateNotification: Render state", { + updateAvailable, + updateDownloaded, + isDownloading + }) + if (!updateAvailable && !updateDownloaded) return null + + return ( + + e.preventDefault()} + > +
+

+ {updateDownloaded + ? "Update Ready to Install" + : "A New Version is Available"} +

+

+ {updateDownloaded + ? "The update has been downloaded and will be installed when you restart the app." + : "A new version of Interview Coder is available. Please update to continue using the app."} +

+
+ {updateDownloaded ? ( + + ) : ( + + )} +
+
+
+
+ ) +} diff --git a/src/components/WelcomeScreen.tsx b/src/components/WelcomeScreen.tsx new file mode 100644 index 0000000..142ffeb --- /dev/null +++ b/src/components/WelcomeScreen.tsx @@ -0,0 +1,73 @@ +import React from 'react'; +import { Button } from './ui/button'; + +interface WelcomeScreenProps { + onOpenSettings: () => void; +} + +export const WelcomeScreen: React.FC = ({ onOpenSettings }) => { + return ( +
+
+

+ Interview Coder + Unlocked Edition +

+ +
+

Welcome to Interview Coder

+

+ This application helps you ace technical interviews by providing AI-powered + solutions to coding problems. +

+
+

Global Shortcuts

+
    +
  • + Toggle Visibility + Ctrl+B / Cmd+B +
  • +
  • + Take Screenshot + Ctrl+H / Cmd+H +
  • +
  • + Delete Last Screenshot + Ctrl+L / Cmd+L +
  • +
  • + Process Screenshots + Ctrl+Enter / Cmd+Enter +
  • +
  • + Reset View + Ctrl+R / Cmd+R +
  • +
  • + Quit App + Ctrl+Q / Cmd+Q +
  • +
+
+
+ +
+

Getting Started

+

+ Before using the application, you need to configure your OpenAI API key. +

+ +
+ +
+ Start by taking screenshots of your coding problem (Ctrl+H / Cmd+H) +
+
+
+ ); +}; \ No newline at end of file diff --git a/src/components/shared/LanguageSelector.tsx b/src/components/shared/LanguageSelector.tsx new file mode 100644 index 0000000..2f63f79 --- /dev/null +++ b/src/components/shared/LanguageSelector.tsx @@ -0,0 +1,57 @@ +import React from "react" + +interface LanguageSelectorProps { + currentLanguage: string + setLanguage: (language: string) => void +} + +export const LanguageSelector: React.FC = ({ + currentLanguage, + setLanguage +}) => { + const handleLanguageChange = async ( + e: React.ChangeEvent + ) => { + const newLanguage = e.target.value + + try { + // Save language preference to electron store + await window.electronAPI.updateConfig({ language: newLanguage }) + + // Update global language variable + window.__LANGUAGE__ = newLanguage + + // Update state in React + setLanguage(newLanguage) + + console.log(`Language changed to ${newLanguage}`); + } catch (error) { + console.error("Error updating language:", error) + } + } + + return ( +
+
+ Language + +
+
+ ) +} diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsx new file mode 100644 index 0000000..ef2a689 --- /dev/null +++ b/src/components/ui/button.tsx @@ -0,0 +1,56 @@ +import * as React from "react" +import { Slot } from "@radix-ui/react-slot" +import { cva, type VariantProps } from "class-variance-authority" +import { cn } from "../../lib/utils" + +const buttonVariants = cva( + "inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50", + { + variants: { + variant: { + default: + "bg-primary text-primary-foreground shadow hover:bg-primary/90", + destructive: + "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90", + outline: + "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground", + secondary: + "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80", + ghost: "hover:bg-accent hover:text-accent-foreground", + link: "text-primary underline-offset-4 hover:underline" + }, + size: { + default: "h-9 px-4 py-2", + sm: "h-8 rounded-md px-3 text-xs", + lg: "h-10 rounded-md px-8", + icon: "h-9 w-9" + } + }, + defaultVariants: { + variant: "default", + size: "default" + } + } +) + +export interface ButtonProps + extends React.ButtonHTMLAttributes, + VariantProps { + asChild?: boolean +} + +const Button = React.forwardRef( + ({ className, variant, size, asChild = false, ...props }, ref) => { + const Comp = asChild ? Slot : "button" + return ( + + ) + } +) +Button.displayName = "Button" + +export { Button, buttonVariants } diff --git a/src/components/ui/card.tsx b/src/components/ui/card.tsx new file mode 100644 index 0000000..ee88067 --- /dev/null +++ b/src/components/ui/card.tsx @@ -0,0 +1,75 @@ +import * as React from "react" +import { cn } from "../../lib/utils" + +const Card = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +Card.displayName = "Card" + +const CardHeader = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardHeader.displayName = "CardHeader" + +const CardTitle = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +

+)) +CardTitle.displayName = "CardTitle" + +const CardDescription = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +

+)) +CardDescription.displayName = "CardDescription" + +const CardContent = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +

+)) +CardContent.displayName = "CardContent" + +const CardFooter = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardFooter.displayName = "CardFooter" + +export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent } diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsx new file mode 100644 index 0000000..fce8f89 --- /dev/null +++ b/src/components/ui/dialog.tsx @@ -0,0 +1,98 @@ +// src/components/ui/dialog.tsx + +import * as React from "react" +import * as DialogPrimitive from "@radix-ui/react-dialog" +import { cn } from "../../lib/utils" + +const Dialog = DialogPrimitive.Root +const DialogTrigger = DialogPrimitive.Trigger +const DialogPortal = DialogPrimitive.Portal + +const DialogOverlay = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +DialogOverlay.displayName = DialogPrimitive.Overlay.displayName + +const DialogContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + + + + {children} + + +)) +DialogContent.displayName = DialogPrimitive.Content.displayName + +const DialogClose = DialogPrimitive.Close + +const DialogHeader = ({ className, ...props }: React.HTMLAttributes) => ( +
+) +DialogHeader.displayName = "DialogHeader" + +const DialogFooter = ({ className, ...props }: React.HTMLAttributes) => ( +
+) +DialogFooter.displayName = "DialogFooter" + +const DialogTitle = React.forwardRef< + HTMLHeadingElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( + +)) +DialogTitle.displayName = DialogPrimitive.Title.displayName + +const DialogDescription = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( + +)) +DialogDescription.displayName = DialogPrimitive.Description.displayName + +export { + Dialog, + DialogTrigger, + DialogContent, + DialogClose, + DialogHeader, + DialogFooter, + DialogTitle, + DialogDescription +} diff --git a/src/components/ui/input.tsx b/src/components/ui/input.tsx new file mode 100644 index 0000000..b15be1f --- /dev/null +++ b/src/components/ui/input.tsx @@ -0,0 +1,24 @@ +import * as React from "react" +import { cn } from "../../lib/utils" + +export interface InputProps + extends React.InputHTMLAttributes {} + +const Input = React.forwardRef( + ({ className, type, ...props }, ref) => { + return ( + + ) + } +) +Input.displayName = "Input" + +export { Input } diff --git a/src/components/ui/toast.tsx b/src/components/ui/toast.tsx new file mode 100644 index 0000000..8f408c7 --- /dev/null +++ b/src/components/ui/toast.tsx @@ -0,0 +1,125 @@ +import * as React from "react" +import * as ToastPrimitive from "@radix-ui/react-toast" +import { cn } from "../../lib/utils" +import { AlertCircle, CheckCircle2, Info, X } from "lucide-react" + +const ToastProvider = ToastPrimitive.Provider + +export type ToastMessage = { + title: string + description: string + variant: ToastVariant +} + +const ToastViewport = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +ToastViewport.displayName = ToastPrimitive.Viewport.displayName + +type ToastVariant = "neutral" | "success" | "error" + +interface ToastProps + extends React.ComponentPropsWithoutRef { + variant?: ToastVariant + swipeDirection?: "right" | "left" | "up" | "down" +} + +const toastVariants: Record< + ToastVariant, + { icon: React.ReactNode; bgColor: string } +> = { + neutral: { + icon: , + bgColor: "bg-amber-100" + }, + success: { + icon: , + bgColor: "bg-emerald-100" + }, + error: { + icon: , + bgColor: "bg-red-100" + } +} + +const Toast = React.forwardRef< + React.ElementRef, + ToastProps +>(({ className, variant = "neutral", ...props }, ref) => ( + + {toastVariants[variant].icon} +
{props.children}
+ + + +
+)) +Toast.displayName = ToastPrimitive.Root.displayName + +const ToastAction = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +ToastAction.displayName = ToastPrimitive.Action.displayName + +const ToastTitle = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +ToastTitle.displayName = ToastPrimitive.Title.displayName + +const ToastDescription = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +ToastDescription.displayName = ToastPrimitive.Description.displayName + +export type { ToastProps, ToastVariant } +export { + ToastProvider, + ToastViewport, + Toast, + ToastAction, + ToastTitle, + ToastDescription +} diff --git a/src/contexts/toast.tsx b/src/contexts/toast.tsx new file mode 100644 index 0000000..8b0bd4b --- /dev/null +++ b/src/contexts/toast.tsx @@ -0,0 +1,19 @@ +import { createContext, useContext } from "react" + +type ToastVariant = "neutral" | "success" | "error" + +interface ToastContextType { + showToast: (title: string, description: string, variant: ToastVariant) => void +} + +export const ToastContext = createContext( + undefined +) + +export function useToast() { + const context = useContext(ToastContext) + if (!context) { + throw new Error("useToast must be used within a ToastProvider") + } + return context +} diff --git a/src/env.d.ts b/src/env.d.ts new file mode 100644 index 0000000..f161fa1 --- /dev/null +++ b/src/env.d.ts @@ -0,0 +1,76 @@ +/// + +import { ToastMessage } from "./components/ui/toast" + +interface ImportMetaEnv { + readonly VITE_SUPABASE_URL: string + readonly VITE_SUPABASE_ANON_KEY: string + readonly NODE_ENV: string +} + +interface ImportMeta { + readonly env: ImportMetaEnv +} + +interface ElectronAPI { + openSubscriptionPortal: (authData: { + id: string + email: string + }) => Promise<{ success: boolean; error?: string }> + updateContentDimensions: (dimensions: { + width: number + height: number + }) => Promise + clearStore: () => Promise<{ success: boolean; error?: string }> + getScreenshots: () => Promise<{ + success: boolean + previews?: Array<{ path: string; preview: string }> | null + error?: string + }> + deleteScreenshot: ( + path: string + ) => Promise<{ success: boolean; error?: string }> + onScreenshotTaken: ( + callback: (data: { path: string; preview: string }) => void + ) => () => void + onResetView: (callback: () => void) => () => void + onSolutionStart: (callback: () => void) => () => void + onDebugStart: (callback: () => void) => () => void + onDebugSuccess: (callback: (data: any) => void) => () => void + onSolutionError: (callback: (error: string) => void) => () => void + onProcessingNoScreenshots: (callback: () => void) => () => void + onProblemExtracted: (callback: (data: any) => void) => () => void + onSolutionSuccess: (callback: (data: any) => void) => () => void + onUnauthorized: (callback: () => void) => () => void + onDebugError: (callback: (error: string) => void) => () => void + openExternal: (url: string) => void + toggleMainWindow: () => Promise<{ success: boolean; error?: string }> + triggerScreenshot: () => Promise<{ success: boolean; error?: string }> + triggerProcessScreenshots: () => Promise<{ success: boolean; error?: string }> + triggerReset: () => Promise<{ success: boolean; error?: string }> + triggerMoveLeft: () => Promise<{ success: boolean; error?: string }> + triggerMoveRight: () => Promise<{ success: boolean; error?: string }> + triggerMoveUp: () => Promise<{ success: boolean; error?: string }> + triggerMoveDown: () => Promise<{ success: boolean; error?: string }> + onSubscriptionUpdated: (callback: () => void) => () => void + onSubscriptionPortalClosed: (callback: () => void) => () => void + // Add update-related methods + startUpdate: () => Promise<{ success: boolean; error?: string }> + installUpdate: () => void + onUpdateAvailable: (callback: (info: any) => void) => () => void + onUpdateDownloaded: (callback: (info: any) => void) => () => void +} + +interface Window { + electronAPI: ElectronAPI + electron: { + ipcRenderer: { + on(channel: string, func: (...args: any[]) => void): void + removeListener(channel: string, func: (...args: any[]) => void): void + } + } + __CREDITS__: number + __LANGUAGE__: string + __IS_INITIALIZED__: boolean + __AUTH_TOKEN__: string +} diff --git a/src/index.css b/src/index.css new file mode 100644 index 0000000..9ee28e2 --- /dev/null +++ b/src/index.css @@ -0,0 +1,70 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; + +/* Custom animations for UI elements */ +@keyframes fadeIn { + from { opacity: 0; transform: translate(-50%, -48%); } + to { opacity: 0.98; transform: translate(-50%, -50%); } +} + +/* Dialog transition improvements */ +.settings-dialog { + transform-origin: center; + backface-visibility: hidden; + will-change: opacity, transform; +} + +/* Custom styling for dropdowns */ +select { + appearance: menulist; + background-color: #000000 !important; + color: white !important; +} + +option { + background-color: #1a1a1a !important; + color: white !important; + padding: 8px !important; +} + +.frosted-glass { + background: rgba(26, 26, 26, 0.8); + backdrop-filter: blur(8px); +} + +.auth-button { + background: rgba(252, 252, 252, 0.98); + color: rgba(60, 60, 60, 0.9); + transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1); + position: relative; + z-index: 2; + box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05); +} + +.auth-button:hover { + background: rgba(255, 255, 255, 1); +} + +.auth-button::before { + content: ""; + position: absolute; + inset: -8px; + background: linear-gradient(45deg, #ff000000, #0000ff00); + z-index: -1; + transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1); + border-radius: inherit; + filter: blur(24px); + opacity: 0; +} + +.auth-button:hover::before { + background: linear-gradient( + 45deg, + rgba(255, 0, 0, 0.4), + rgba(0, 0, 255, 0.4) + ); + filter: blur(48px); + inset: -16px; + opacity: 1; +} diff --git a/src/lib/supabase.ts b/src/lib/supabase.ts new file mode 100644 index 0000000..32d5adb --- /dev/null +++ b/src/lib/supabase.ts @@ -0,0 +1,122 @@ +import { createClient } from "@supabase/supabase-js" + +console.log("Supabase URL:", import.meta.env.VITE_SUPABASE_URL) +console.log( + "Supabase Anon Key:", + import.meta.env.VITE_SUPABASE_ANON_KEY?.slice(0, 10) + "..." +) + +const supabaseUrl = import.meta.env.VITE_SUPABASE_URL +const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY + +if (!supabaseUrl || !supabaseAnonKey) { + throw new Error("Missing Supabase environment variables") +} + +export const supabase = createClient(supabaseUrl, supabaseAnonKey, { + auth: { + flowType: "pkce", + detectSessionInUrl: true, + persistSession: true, + autoRefreshToken: true, + debug: true, + storage: { + getItem: (key) => { + const item = localStorage.getItem(key) + console.log("Auth storage - Getting key:", key, "Value exists:", !!item) + return item + }, + setItem: (key, value) => { + console.log("Auth storage - Setting key:", key) + localStorage.setItem(key, value) + }, + removeItem: (key) => { + console.log("Auth storage - Removing key:", key) + localStorage.removeItem(key) + } + } + }, + realtime: { + params: { + eventsPerSecond: 10 + }, + headers: { + apikey: supabaseAnonKey + } + } +}) + +export const signInWithGoogle = async () => { + try { + console.log("Initiating Google sign in...") + const { data, error } = await supabase.auth.signInWithOAuth({ + provider: "google", + options: { + redirectTo: window.location.origin + } + }) + + if (error) { + console.error("Google sign in error:", error) + throw error + } + + console.log("Google sign in response:", data) + return data + } catch (error) { + console.error("Unexpected error during Google sign in:", error) + throw error + } +} + +let channel: ReturnType | null = null + +// Monitor auth state changes and manage realtime connection +supabase.auth.onAuthStateChange((event, session) => { + console.log("Auth state changed:", event, session?.user?.id) + console.log("Full session data:", session) + + if (event === "SIGNED_IN" && session) { + // Only establish realtime connection after successful sign in + console.log("Establishing realtime connection...") + + // Clean up existing channel if any + if (channel) { + channel.unsubscribe() + } + + channel = supabase.channel("system", { + config: { + presence: { + key: session.user.id + } + } + }) + + channel + .on("system", { event: "*" }, (payload) => { + console.log("System event:", payload) + }) + .subscribe((status) => { + console.log("Realtime subscription status:", status) + if (status === "SUBSCRIBED") { + console.log("Successfully connected to realtime system") + } + if (status === "CHANNEL_ERROR") { + console.error("Realtime connection error - will retry in 5s") + setTimeout(() => { + channel?.subscribe() + }, 5000) + } + }) + } + + if (event === "SIGNED_OUT") { + // Clean up realtime connection on sign out + if (channel) { + console.log("Cleaning up realtime connection") + channel.unsubscribe() + channel = null + } + } +}) diff --git a/src/lib/utils.ts b/src/lib/utils.ts new file mode 100644 index 0000000..35a11fe --- /dev/null +++ b/src/lib/utils.ts @@ -0,0 +1,8 @@ +// src/lib/utils.ts + +import { type ClassValue, clsx } from "clsx" +import { twMerge } from "tailwind-merge" + +export function cn(...inputs: ClassValue[]) { + return twMerge(clsx(inputs)) +} diff --git a/src/main.tsx b/src/main.tsx new file mode 100644 index 0000000..44814f6 --- /dev/null +++ b/src/main.tsx @@ -0,0 +1,10 @@ +import React from "react" +import ReactDOM from "react-dom/client" +import App from "./App" +import "./index.css" + +ReactDOM.createRoot(document.getElementById("root")!).render( + + + +) diff --git a/src/types/electron.d.ts b/src/types/electron.d.ts new file mode 100644 index 0000000..a467cae --- /dev/null +++ b/src/types/electron.d.ts @@ -0,0 +1,83 @@ +export interface ElectronAPI { + // Original methods + openSubscriptionPortal: (authData: { + id: string + email: string + }) => Promise<{ success: boolean; error?: string }> + updateContentDimensions: (dimensions: { + width: number + height: number + }) => Promise + clearStore: () => Promise<{ success: boolean; error?: string }> + getScreenshots: () => Promise<{ + success: boolean + previews?: Array<{ path: string; preview: string }> | null + error?: string + }> + deleteScreenshot: ( + path: string + ) => Promise<{ success: boolean; error?: string }> + onScreenshotTaken: ( + callback: (data: { path: string; preview: string }) => void + ) => () => void + onResetView: (callback: () => void) => () => void + onSolutionStart: (callback: () => void) => () => void + onDebugStart: (callback: () => void) => () => void + onDebugSuccess: (callback: (data: any) => void) => () => void + onSolutionError: (callback: (error: string) => void) => () => void + onProcessingNoScreenshots: (callback: () => void) => () => void + onProblemExtracted: (callback: (data: any) => void) => () => void + onSolutionSuccess: (callback: (data: any) => void) => () => void + onUnauthorized: (callback: () => void) => () => void + onDebugError: (callback: (error: string) => void) => () => void + openExternal: (url: string) => void + toggleMainWindow: () => Promise<{ success: boolean; error?: string }> + triggerScreenshot: () => Promise<{ success: boolean; error?: string }> + triggerProcessScreenshots: () => Promise<{ success: boolean; error?: string }> + triggerReset: () => Promise<{ success: boolean; error?: string }> + triggerMoveLeft: () => Promise<{ success: boolean; error?: string }> + triggerMoveRight: () => Promise<{ success: boolean; error?: string }> + triggerMoveUp: () => Promise<{ success: boolean; error?: string }> + triggerMoveDown: () => Promise<{ success: boolean; error?: string }> + onSubscriptionUpdated: (callback: () => void) => () => void + onSubscriptionPortalClosed: (callback: () => void) => () => void + startUpdate: () => Promise<{ success: boolean; error?: string }> + installUpdate: () => void + onUpdateAvailable: (callback: (info: any) => void) => () => void + onUpdateDownloaded: (callback: (info: any) => void) => () => void + + decrementCredits: () => Promise + setInitialCredits: (credits: number) => Promise + onCreditsUpdated: (callback: (credits: number) => void) => () => void + onOutOfCredits: (callback: () => void) => () => void + openSettingsPortal: () => Promise + getPlatform: () => string + + // New methods for OpenAI integration + getConfig: () => Promise<{ apiKey: string; model: string }> + updateConfig: (config: { apiKey?: string; model?: string }) => Promise + checkApiKey: () => Promise + validateApiKey: (apiKey: string) => Promise<{ valid: boolean; error?: string }> + openLink: (url: string) => void + onApiKeyInvalid: (callback: () => void) => () => void + removeListener: (eventName: string, callback: (...args: any[]) => void) => void +} + +declare global { + interface Window { + electronAPI: ElectronAPI + electron: { + ipcRenderer: { + on: (channel: string, func: (...args: any[]) => void) => void + removeListener: ( + channel: string, + func: (...args: any[]) => void + ) => void + } + } + __CREDITS__: number + __LANGUAGE__: string + __IS_INITIALIZED__: boolean + __AUTH_TOKEN__?: string | null + } +} diff --git a/src/types/global.d.ts b/src/types/global.d.ts new file mode 100644 index 0000000..f3a4eda --- /dev/null +++ b/src/types/global.d.ts @@ -0,0 +1,9 @@ +interface Window { + __IS_INITIALIZED__: boolean + __CREDITS__: number + __LANGUAGE__: string + __AUTH_TOKEN__: string | null + supabase: any // Replace with proper Supabase client type if needed + electron: any // Replace with proper Electron type if needed + electronAPI: any // Replace with proper Electron API type if needed +} diff --git a/src/types/index.tsx b/src/types/index.tsx new file mode 100644 index 0000000..2147bab --- /dev/null +++ b/src/types/index.tsx @@ -0,0 +1,13 @@ +export interface Screenshot { + id: string + path: string + timestamp: number + thumbnail: string // Base64 thumbnail +} + +export interface Solution { + initial_thoughts: string[] + thought_steps: string[] + description: string + code: string +} diff --git a/src/types/screenshots.ts b/src/types/screenshots.ts new file mode 100644 index 0000000..86228da --- /dev/null +++ b/src/types/screenshots.ts @@ -0,0 +1,4 @@ +export interface Screenshot { + path: string + preview: string +} diff --git a/src/types/solutions.ts b/src/types/solutions.ts new file mode 100644 index 0000000..c0f74f8 --- /dev/null +++ b/src/types/solutions.ts @@ -0,0 +1,30 @@ +export interface Solution { + initial_thoughts: string[] + thought_steps: string[] + description: string + code: string +} + +export interface SolutionsResponse { + [key: string]: Solution +} + +export interface ProblemStatementData { + problem_statement: string + input_format: { + description: string + parameters: any[] + } + output_format: { + description: string + type: string + subtype: string + } + complexity: { + time: string + space: string + } + test_cases: any[] + validation_type: string + difficulty: string +} diff --git a/src/utils/platform.ts b/src/utils/platform.ts new file mode 100644 index 0000000..e06651e --- /dev/null +++ b/src/utils/platform.ts @@ -0,0 +1,17 @@ +// Get the platform safely +const getPlatform = () => { + try { + return window.electronAPI?.getPlatform() || 'win32' // Default to win32 if API is not available + } catch { + return 'win32' // Default to win32 if there's an error + } +} + +// Platform-specific command key symbol +export const COMMAND_KEY = getPlatform() === 'darwin' ? '⌘' : 'Ctrl' + +// Helper to check if we're on Windows +export const isWindows = getPlatform() === 'win32' + +// Helper to check if we're on macOS +export const isMacOS = getPlatform() === 'darwin' \ No newline at end of file diff --git a/src/vite-env.d.ts b/src/vite-env.d.ts new file mode 100644 index 0000000..e38da9b --- /dev/null +++ b/src/vite-env.d.ts @@ -0,0 +1,11 @@ +/// + +interface ImportMetaEnv { + readonly VITE_SUPABASE_URL: string + + readonly VITE_SUPABASE_ANON_KEY: string +} + +interface ImportMeta { + readonly env: ImportMetaEnv +} diff --git a/stealth-run.bat b/stealth-run.bat new file mode 100644 index 0000000..b1bfa6b --- /dev/null +++ b/stealth-run.bat @@ -0,0 +1,37 @@ +@echo off +echo === Interview Coder - Invisible Edition (No Paywall) === +echo. +echo IMPORTANT: This app is designed to be INVISIBLE by default! +echo Use the keyboard shortcuts to control it: +echo. +echo - Toggle Visibility: Ctrl+B (or Cmd+B on Mac) +echo - Take Screenshot: Ctrl+H +echo - Process Screenshots: Ctrl+Enter +echo - Move Window: Ctrl+Arrows (Left/Right/Up/Down) +echo - Adjust Opacity: Ctrl+[ (decrease) / Ctrl+] (increase) +echo - Reset View: Ctrl+R +echo - Quit App: Ctrl+Q +echo. +echo When you press Ctrl+B, the window will toggle between visible and invisible. +echo If movement shortcuts aren't working, try making the window visible first with Ctrl+B. +echo. + +cd /D "%~dp0" + +echo 1. Creating required directories... +mkdir "%APPDATA%\interview-coder-v1\temp" 2>nul +mkdir "%APPDATA%\interview-coder-v1\cache" 2>nul +mkdir "%APPDATA%\interview-coder-v1\screenshots" 2>nul +mkdir "%APPDATA%\interview-coder-v1\extra_screenshots" 2>nul + +echo 2. Building application... +call npm run build + +echo 3. Launching in stealth mode... +echo Remember: Press Ctrl+B to make it visible, Ctrl+[ and Ctrl+] to adjust opacity! +echo. +set NODE_ENV=production +start /B cmd /c "npx electron ./dist-electron/main.js" + +echo App is now running invisibly! Press Ctrl+B to make it visible. +echo. diff --git a/tailwind.config.js b/tailwind.config.js new file mode 100644 index 0000000..7d85e74 --- /dev/null +++ b/tailwind.config.js @@ -0,0 +1,49 @@ +/** @type {import('tailwindcss').Config} */ +export default { + content: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"], + theme: { + extend: { + fontFamily: { + sans: ["Inter", "system-ui", "sans-serif"] + }, + animation: { + in: "in 0.2s ease-out", + out: "out 0.2s ease-in", + pulse: "pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite", + shimmer: "shimmer 2s linear infinite", + "text-gradient-wave": "textGradientWave 2s infinite ease-in-out" + }, + keyframes: { + textGradientWave: { + "0%": { backgroundPosition: "0% 50%" }, + "100%": { backgroundPosition: "200% 50%" } + }, + shimmer: { + "0%": { + backgroundPosition: "200% 0" + }, + "100%": { + backgroundPosition: "-200% 0" + } + }, + in: { + "0%": { transform: "translateY(100%)", opacity: 0 }, + "100%": { transform: "translateY(0)", opacity: 1 } + }, + out: { + "0%": { transform: "translateY(0)", opacity: 1 }, + "100%": { transform: "translateY(100%)", opacity: 0 } + }, + pulse: { + "0%, 100%": { + opacity: 1 + }, + "50%": { + opacity: 0.5 + } + } + } + } + }, + plugins: [] +} diff --git a/tsconfig.electron.json b/tsconfig.electron.json new file mode 100644 index 0000000..daa4561 --- /dev/null +++ b/tsconfig.electron.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "CommonJS", + "moduleResolution": "node", + "skipLibCheck": true, + "strict": false, + "noUnusedLocals": false, + "noUnusedParameters": false, + "outDir": "dist-electron", + "esModuleInterop": true, + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": ".", + "paths": { + "main": ["electron/main.ts"] + } + }, + "include": ["electron/**/*"] +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..a831c76 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ES2020", + "skipLibCheck": true, + "moduleResolution": "bundler", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": false, + "noUnusedParameters": false, + "noFallthroughCasesInSwitch": true, + "allowJs": true, + "esModuleInterop": true, + "allowImportingTsExtensions": true, + "types": ["vite/client"] + }, + "include": ["electron/**/*", "src/**/*"], + "references": [{ "path": "./tsconfig.node.json" }] +} diff --git a/tsconfig.node.json b/tsconfig.node.json new file mode 100644 index 0000000..42872c5 --- /dev/null +++ b/tsconfig.node.json @@ -0,0 +1,10 @@ +{ + "compilerOptions": { + "composite": true, + "skipLibCheck": true, + "module": "ESNext", + "moduleResolution": "bundler", + "allowSyntheticDefaultImports": true + }, + "include": ["vite.config.ts"] +} diff --git a/vite.config.ts b/vite.config.ts new file mode 100644 index 0000000..d736077 --- /dev/null +++ b/vite.config.ts @@ -0,0 +1,58 @@ +// vite.config.ts +import { defineConfig } from "vite" +import electron from "vite-plugin-electron" +import react from "@vitejs/plugin-react" +import path from "path" + +export default defineConfig({ + plugins: [ + react(), + electron([ + { + // main.ts + entry: "electron/main.ts", + vite: { + build: { + outDir: "dist-electron", + sourcemap: true, + minify: false, + rollupOptions: { + external: ["electron"] + } + } + } + }, + { + // preload.ts + entry: "electron/preload.ts", + vite: { + build: { + outDir: "dist-electron", + sourcemap: true, + rollupOptions: { + external: ["electron"] + } + } + } + } + ]) + ], + base: process.env.NODE_ENV === "production" ? "./" : "/", + server: { + port: 54321, + strictPort: true, + watch: { + usePolling: true + } + }, + build: { + outDir: "dist", + emptyOutDir: true, + sourcemap: true + }, + resolve: { + alias: { + "@": path.resolve(__dirname, "./src") + } + } +})