Initial commit - NoPayWall-interviewcoderversion

main
greeneu 2 years ago
parent 6f2f042ffa
commit 4d5faa0076

3
.gitattributes vendored

@ -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

13
.gitignore vendored

@ -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

@ -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.

@ -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!

@ -8,654 +8,33 @@
Preamble Preamble
The GNU Affero General Public License is a free, copyleft license for The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software. cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast, to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to 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 share and change all versions of a program--to make sure it remains free
software for all its users. software for all its users.
When we speak of free software, we are referring to freedom, not When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for 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 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 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. free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute you this License which gives you legal permission to copy, distribute
and/or modify the software. and/or modify the software.
A secondary benefit of defending all users' freedom is that A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about. software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its letting the public access it on a server without ever releasing its
source code to the public. source code to
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/>.

@ -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 <https://www.gnu.org/licenses/>.
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.

@ -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.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 232 KiB

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<key>com.apple.security.cs.debugger</key>
<true/>
<key>com.apple.security.device.camera</key>
<true/>
<key>com.apple.security.device.microphone</key>
<true/>
<key>com.apple.security.files.user-selected.read-write</key>
<true/>
<key>com.apple.security.network.client</key>
<true/>
</dict>
</plist>

Binary file not shown.

@ -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

@ -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>): 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();

@ -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<void> {
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<number> {
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<string> {
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<void> {
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)
}
}
}

@ -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<Buffer> {
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<string> {
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<string> {
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 = []
}
}

@ -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()
})
}

@ -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" }
}
})
}

@ -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<string>
getImagePreview: (filepath: string) => Promise<string>
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<string>
getImagePreview: (filepath: string) => Promise<string>
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<string>
processingHelper: ProcessingHelper | null
PROCESSING_EVENTS: typeof state.PROCESSING_EVENTS
takeScreenshot: () => Promise<string>
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<void> {
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<string> {
if (!state.mainWindow) throw new Error("No main window available")
return (
state.screenshotHelper?.takeScreenshot(
() => hideMainWindow(),
() => showMainWindow()
) || ""
)
}
async function getImagePreview(filepath: string): Promise<string> {
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)

@ -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

@ -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()
})
}
}

@ -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<StoreSchema>({
defaults: {},
encryptionKey: "your-encryption-key"
}) as Store<StoreSchema> & {
store: StoreSchema
get: <K extends keyof StoreSchema>(key: K) => StoreSchema[K]
set: <K extends keyof StoreSchema>(key: K, value: StoreSchema[K]) => void
}
export { store }

@ -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"]
}

10
env.d.ts vendored

@ -0,0 +1,10 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_SUPABASE_URL: string
readonly VITE_SUPABASE_ANON_KEY: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}

@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Interview Coder</title>
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap"
rel="stylesheet"
/>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

@ -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"
]
}
}

@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

@ -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*

@ -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/).

@ -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"
]
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

@ -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"
}

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

@ -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);
}
}

@ -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(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});

@ -0,0 +1,26 @@
import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;

@ -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;
}

@ -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(
<React.StrictMode>
<App />
</React.StrictMode>
);
// 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();

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

@ -0,0 +1 @@
/// <reference types="react-scripts" />

@ -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;

@ -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';

@ -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"]
}

@ -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<number>(999) // Unlimited credits
const [currentLanguage, setCurrentLanguage] = useState<string>("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 (
<QueryClientProvider client={queryClient}>
<ToastProvider>
<ToastContext.Provider value={{ showToast }}>
<div className="relative">
{isInitialized ? (
hasApiKey ? (
<SubscribedApp
credits={credits}
currentLanguage={currentLanguage}
setLanguage={updateLanguage}
/>
) : (
<WelcomeScreen onOpenSettings={handleOpenSettings} />
)
) : (
<div className="min-h-screen bg-black flex items-center justify-center">
<div className="flex flex-col items-center gap-3">
<div className="w-6 h-6 border-2 border-white/20 border-t-white/80 rounded-full animate-spin"></div>
<p className="text-white/60 text-sm">
Initializing...
</p>
</div>
</div>
)}
<UpdateNotification />
</div>
{/* Settings Dialog */}
<SettingsDialog
open={isSettingsOpen}
onOpenChange={handleCloseSettings}
/>
<Toast
open={toastState.open}
onOpenChange={(open) =>
setToastState((prev) => ({ ...prev, open }))
}
variant={toastState.variant}
duration={1500}
>
<ToastTitle>{toastState.title}</ToastTitle>
<ToastDescription>{toastState.description}</ToastDescription>
</Toast>
<ToastViewport />
</ToastContext.Provider>
</ToastProvider>
</QueryClientProvider>
)
}
export default App

@ -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
}) => (
<div className="space-y-2">
<h2 className="text-[13px] font-medium text-white tracking-wide"></h2>
{isLoading ? (
<div className="space-y-1.5">
<div className="mt-4 flex">
<p className="text-xs bg-gradient-to-r from-gray-300 via-gray-100 to-gray-300 bg-clip-text text-transparent animate-pulse">
Loading solutions...
</p>
</div>
</div>
) : (
<div className="w-full">
<SyntaxHighlighter
showLineNumbers
language={currentLanguage == "golang" ? "go" : currentLanguage}
style={dracula}
customStyle={{
maxWidth: "100%",
margin: 0,
padding: "1rem",
whiteSpace: "pre-wrap",
wordBreak: "break-all",
backgroundColor: "rgba(22, 27, 34, 0.5)"
}}
wrapLongLines={true}
>
{code as string}
</SyntaxHighlighter>
</div>
)}
</div>
)
async function fetchScreenshots(): Promise<Screenshot[]> {
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<DebugProps> = ({
isProcessing,
setIsProcessing,
currentLanguage,
setLanguage
}) => {
const [tooltipVisible, setTooltipVisible] = useState(false)
const [tooltipHeight, setTooltipHeight] = useState(0)
const { showToast } = useToast()
const { data: screenshots = [], refetch } = useQuery<Screenshot[]>({
queryKey: ["screenshots"],
queryFn: fetchScreenshots,
staleTime: Infinity,
gcTime: Infinity,
refetchOnWindowFocus: false
})
const [newCode, setNewCode] = useState<string | null>(null)
const [thoughtsData, setThoughtsData] = useState<string[] | null>(null)
const [timeComplexityData, setTimeComplexityData] = useState<string | null>(
null
)
const [spaceComplexityData, setSpaceComplexityData] = useState<string | null>(
null
)
const [debugAnalysis, setDebugAnalysis] = useState<string | null>(null)
const queryClient = useQueryClient()
const contentRef = useRef<HTMLDivElement>(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 (
<div ref={contentRef} className="relative">
<div className="space-y-3 px-4 py-3">
{/* Conditionally render the screenshot queue */}
<div className="bg-transparent w-fit">
<div className="pb-3">
<div className="space-y-3 w-fit">
<ScreenshotQueue
screenshots={screenshots}
onDeleteScreenshot={handleDeleteExtraScreenshot}
isLoading={isProcessing}
/>
</div>
</div>
</div>
{/* Navbar of commands with the tooltip */}
<SolutionCommands
screenshots={screenshots}
onTooltipVisibilityChange={handleTooltipVisibilityChange}
isProcessing={isProcessing}
extraScreenshots={screenshots}
credits={window.__CREDITS__}
currentLanguage={currentLanguage}
setLanguage={setLanguage}
/>
{/* Main Content */}
<div className="w-full text-sm text-black bg-black/60 rounded-md">
<div className="rounded-lg overflow-hidden">
<div className="px-4 py-3 space-y-4">
{/* Thoughts Section */}
<ContentSection
title="What I Changed"
content={
thoughtsData && (
<div className="space-y-3">
<div className="space-y-1">
{thoughtsData.map((thought, index) => (
<div key={index} className="flex items-start gap-2">
<div className="w-1 h-1 rounded-full bg-blue-400/80 mt-2 shrink-0" />
<div>{thought}</div>
</div>
))}
</div>
</div>
)
}
isLoading={!thoughtsData}
/>
{/* Code Section */}
<CodeSection
title="Original Code"
code={newCode}
isLoading={!newCode}
currentLanguage={currentLanguage}
/>
{/* Debug Analysis Section */}
<div className="space-y-2">
<h2 className="text-[13px] font-medium text-white tracking-wide">Analysis & Improvements</h2>
{!debugAnalysis ? (
<div className="space-y-1.5">
<div className="mt-4 flex">
<p className="text-xs bg-gradient-to-r from-gray-300 via-gray-100 to-gray-300 bg-clip-text text-transparent animate-pulse">
Loading debug analysis...
</p>
</div>
</div>
) : (
<div className="w-full bg-black/30 rounded-md p-4 text-[13px] leading-[1.4] text-gray-100 whitespace-pre-wrap overflow-auto max-h-[600px]">
{/* 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) => (
<div key={sectionIndex} className="mb-6">
{section.title && (
<div className="font-bold text-white/90 text-[14px] mb-2 pb-1 border-b border-white/10">
{section.title}
</div>
)}
<div className="pl-1">
{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 (
<div key={lineIndex} className="font-mono text-xs bg-black/50 p-3 my-2 rounded overflow-x-auto">
{codeContent}
</div>
);
}
}
}
// Handle bullet points
if (line.trim().match(/^[\-*•]\s/) || line.trim().match(/^\d+\.\s/)) {
return (
<div key={lineIndex} className="flex items-start gap-2 my-1.5">
<div className="w-1.5 h-1.5 rounded-full bg-blue-400/80 mt-2 shrink-0" />
<div className="flex-1">
{line.replace(/^[\-*•]\s|^\d+\.\s/, '')}
</div>
</div>
);
}
// Handle inline code
if (line.includes('`')) {
const parts = line.split(/(`[^`]+`)/g);
return (
<div key={lineIndex} className="my-1.5">
{parts.map((part, partIndex) => {
if (part.startsWith('`') && part.endsWith('`')) {
return <span key={partIndex} className="font-mono bg-black/30 px-1 py-0.5 rounded">{part.slice(1, -1)}</span>;
}
return <span key={partIndex}>{part}</span>;
})}
</div>
);
}
// Handle sub-headers
if (line.trim().match(/^#+\s/) || (line.trim().match(/^[A-Z][\w\s]+:/) && line.length < 60)) {
return (
<div key={lineIndex} className="font-semibold text-white/80 mt-3 mb-1">
{line.replace(/^#+\s+/, '')}
</div>
);
}
// Regular text
return <div key={lineIndex} className="my-1.5">{line}</div>;
})}
</div>
</div>
));
})()}
</div>
)}
</div>
{/* Complexity Section */}
<ComplexitySection
timeComplexity={timeComplexityData}
spaceComplexity={spaceComplexityData}
isLoading={!timeComplexityData || !spaceComplexityData}
/>
</div>
</div>
</div>
</div>
</div>
)
}
export default Debug

@ -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<Screenshot[]> {
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<QueueProps> = ({
setView,
credits,
currentLanguage,
setLanguage
}) => {
const { showToast } = useToast()
const [isTooltipVisible, setIsTooltipVisible] = useState(false)
const [tooltipHeight, setTooltipHeight] = useState(0)
const contentRef = useRef<HTMLDivElement>(null)
const {
data: screenshots = [],
isLoading,
refetch
} = useQuery<Screenshot[]>({
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 (
<div ref={contentRef} className={`bg-transparent w-1/2`}>
<div className="px-4 py-3">
<div className="space-y-3 w-fit">
<ScreenshotQueue
isLoading={false}
screenshots={screenshots}
onDeleteScreenshot={handleDeleteScreenshot}
/>
<QueueCommands
onTooltipVisibilityChange={handleTooltipVisibilityChange}
screenshotCount={screenshots.length}
credits={credits}
currentLanguage={currentLanguage}
setLanguage={setLanguage}
/>
</div>
</div>
</div>
)
}
export default Queue

@ -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
}) => (
<div className="space-y-2">
<h2 className="text-[13px] font-medium text-white tracking-wide">
{title}
</h2>
{isLoading ? (
<div className="mt-4 flex">
<p className="text-xs bg-gradient-to-r from-gray-300 via-gray-100 to-gray-300 bg-clip-text text-transparent animate-pulse">
Extracting problem statement...
</p>
</div>
) : (
<div className="text-[13px] leading-[1.4] text-gray-100 max-w-[600px]">
{content}
</div>
)}
</div>
)
const SolutionSection = ({
title,
content,
isLoading,
currentLanguage
}: {
title: string
content: React.ReactNode
isLoading: boolean
currentLanguage: string
}) => (
<div className="space-y-2">
<h2 className="text-[13px] font-medium text-white tracking-wide">
{title}
</h2>
{isLoading ? (
<div className="space-y-1.5">
<div className="mt-4 flex">
<p className="text-xs bg-gradient-to-r from-gray-300 via-gray-100 to-gray-300 bg-clip-text text-transparent animate-pulse">
Loading solutions...
</p>
</div>
</div>
) : (
<div className="w-full">
<SyntaxHighlighter
showLineNumbers
language={currentLanguage == "golang" ? "go" : currentLanguage}
style={dracula}
customStyle={{
maxWidth: "100%",
margin: 0,
padding: "1rem",
whiteSpace: "pre-wrap",
wordBreak: "break-all",
backgroundColor: "rgba(22, 27, 34, 0.5)"
}}
wrapLongLines={true}
>
{content as string}
</SyntaxHighlighter>
</div>
)}
</div>
)
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 (
<div className="space-y-2">
<h2 className="text-[13px] font-medium text-white tracking-wide">
Complexity
</h2>
{isLoading ? (
<p className="text-xs bg-gradient-to-r from-gray-300 via-gray-100 to-gray-300 bg-clip-text text-transparent animate-pulse">
Calculating complexity...
</p>
) : (
<div className="space-y-3">
<div className="text-[13px] leading-[1.4] text-gray-100 bg-white/5 rounded-md p-3">
<div className="flex items-start gap-2">
<div className="w-1 h-1 rounded-full bg-blue-400/80 mt-2 shrink-0" />
<div>
<strong>Time:</strong> {formattedTimeComplexity}
</div>
</div>
</div>
<div className="text-[13px] leading-[1.4] text-gray-100 bg-white/5 rounded-md p-3">
<div className="flex items-start gap-2">
<div className="w-1 h-1 rounded-full bg-blue-400/80 mt-2 shrink-0" />
<div>
<strong>Space:</strong> {formattedSpaceComplexity}
</div>
</div>
</div>
</div>
)}
</div>
);
}
export interface SolutionsProps {
setView: (view: "queue" | "solutions" | "debug") => void
credits: number
currentLanguage: string
setLanguage: (language: string) => void
}
const Solutions: React.FC<SolutionsProps> = ({
setView,
credits,
currentLanguage,
setLanguage
}) => {
const queryClient = useQueryClient()
const contentRef = useRef<HTMLDivElement>(null)
const [debugProcessing, setDebugProcessing] = useState(false)
const [problemStatementData, setProblemStatementData] =
useState<ProblemStatementData | null>(null)
const [solutionData, setSolutionData] = useState<string | null>(null)
const [thoughtsData, setThoughtsData] = useState<string[] | null>(null)
const [timeComplexityData, setTimeComplexityData] = useState<string | null>(
null
)
const [spaceComplexityData, setSpaceComplexityData] = useState<string | null>(
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<Screenshot[]>([])
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"]) ? (
<Debug
isProcessing={debugProcessing}
setIsProcessing={setDebugProcessing}
currentLanguage={currentLanguage}
setLanguage={setLanguage}
/>
) : (
<div ref={contentRef} className="relative">
<div className="space-y-3 px-4 py-3">
{/* Conditionally render the screenshot queue if solutionData is available */}
{solutionData && (
<div className="bg-transparent w-fit">
<div className="pb-3">
<div className="space-y-3 w-fit">
<ScreenshotQueue
isLoading={debugProcessing}
screenshots={extraScreenshots}
onDeleteScreenshot={handleDeleteExtraScreenshot}
/>
</div>
</div>
</div>
)}
{/* Navbar of commands with the SolutionsHelper */}
<SolutionCommands
onTooltipVisibilityChange={handleTooltipVisibilityChange}
isProcessing={!problemStatementData || !solutionData}
extraScreenshots={extraScreenshots}
credits={credits}
currentLanguage={currentLanguage}
setLanguage={setLanguage}
/>
{/* Main Content - Modified width constraints */}
<div className="w-full text-sm text-black bg-black/60 rounded-md">
<div className="rounded-lg overflow-hidden">
<div className="px-4 py-3 space-y-4 max-w-full">
{!solutionData && (
<>
<ContentSection
title="Problem Statement"
content={problemStatementData?.problem_statement}
isLoading={!problemStatementData}
/>
{problemStatementData && (
<div className="mt-4 flex">
<p className="text-xs bg-gradient-to-r from-gray-300 via-gray-100 to-gray-300 bg-clip-text text-transparent animate-pulse">
Generating solutions...
</p>
</div>
)}
</>
)}
{solutionData && (
<>
<ContentSection
title={`My Thoughts (${COMMAND_KEY} + Arrow keys to scroll)`}
content={
thoughtsData && (
<div className="space-y-3">
<div className="space-y-1">
{thoughtsData.map((thought, index) => (
<div
key={index}
className="flex items-start gap-2"
>
<div className="w-1 h-1 rounded-full bg-blue-400/80 mt-2 shrink-0" />
<div>{thought}</div>
</div>
))}
</div>
</div>
)
}
isLoading={!thoughtsData}
/>
<SolutionSection
title="Solution"
content={solutionData}
isLoading={!solutionData}
currentLanguage={currentLanguage}
/>
<ComplexitySection
timeComplexity={timeComplexityData}
spaceComplexity={spaceComplexityData}
isLoading={!timeComplexityData || !spaceComplexityData}
/>
</>
)}
</div>
</div>
</div>
</div>
</div>
)}
</>
)
}
export default Solutions

@ -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<string | null>(null)
const containerRef = useRef<HTMLDivElement>(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 (
<div
ref={containerRef}
className="h-[400px] w-[400px] bg-black flex items-center justify-center"
>
<div className="w-full px-6">
<div className="text-center">
<h2 className="text-2xl font-bold text-white">
Welcome to Interview Coder
</h2>
<p className="text-gray-400 text-sm mt-2 mb-6">
To continue using Interview Coder, you'll need to subscribe
($60/month)
</p>
<p className="text-gray-500 text-[11px] -mt-4 mb-6 italic">
* Undetectability may not work with some versions of MacOS. See our
help center for more details
</p>
{/* Keyboard Shortcuts */}
<div className="bg-white/[0.03] border border-white/[0.06] rounded-xl p-3 mb-6">
<div className="flex items-center justify-between text-white/70 text-xs">
<div className="flex items-center gap-2">
<span className="text-white/40">Toggle Visibility</span>
<div className="flex gap-1">
<kbd className="bg-white/[0.07] border border-white/[0.1] rounded-md px-1.5 py-1 text-[10px] leading-none text-white/60">
⌘
</kbd>
<kbd className="bg-white/[0.07] border border-white/[0.1] rounded-md px-1.5 py-1 text-[10px] leading-none text-white/60">
B
</kbd>
</div>
</div>
<div className="flex items-center gap-2">
<span className="text-white/40">Quit App</span>
<div className="flex gap-1">
<kbd className="bg-white/[0.07] border border-white/[0.1] rounded-md px-1.5 py-1 text-[10px] leading-none text-white/60">
⌘
</kbd>
<kbd className="bg-white/[0.07] border border-white/[0.1] rounded-md px-1.5 py-1 text-[10px] leading-none text-white/60">
Q
</kbd>
</div>
</div>
</div>
</div>
{/* Subscribe Button */}
<button
onClick={handleSubscribe}
className="w-full px-4 py-3 bg-white text-black rounded-xl font-medium hover:bg-white/90 transition-colors flex items-center justify-center gap-2 mb-6"
>
Subscribe
<svg
xmlns="http://www.w3.org/2000/svg"
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
<polyline points="15 3 21 3 21 9" />
<line x1="10" y1="14" x2="21" y2="3" />
</svg>
</button>
{/* Logout Section */}
<div className="border-t border-white/[0.06] pt-4">
<button
onClick={handleSignOut}
className="flex items-center justify-center gap-1.5 text-[11px] text-red-400/80 hover:text-red-400 transition-colors w-full group"
>
<div className="w-3.5 h-3.5 flex items-center justify-center opacity-60 group-hover:opacity-100 transition-opacity">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="w-full h-full"
>
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
<polyline points="16 17 21 12 16 7" />
<line x1="21" y1="12" x2="9" y2="12" />
</svg>
</div>
Log Out
</button>
</div>
{error && (
<div className="mt-4 px-3 py-2 rounded-lg bg-red-500/10 border border-red-500/20">
<p className="text-xs text-red-400">{error}</p>
</div>
)}
</div>
</div>
</div>
)
}

@ -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<SubscribedAppProps> = ({
credits,
currentLanguage,
setLanguage
}) => {
const queryClient = useQueryClient()
const [view, setView] = useState<"queue" | "solutions" | "debug">("queue")
const containerRef = useRef<HTMLDivElement>(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 (
<div ref={containerRef} className="min-h-0">
{view === "queue" ? (
<Queue
setView={setView}
credits={credits}
currentLanguage={currentLanguage}
setLanguage={setLanguage}
/>
) : view === "solutions" ? (
<Solutions
setView={setView}
credits={credits}
currentLanguage={currentLanguage}
setLanguage={setLanguage}
/>
) : null}
</div>
)
}
export default SubscribedApp

@ -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 (
<div className="bg-black p-2 border-b border-white/10 flex items-center justify-between">
<div className="flex items-center space-x-1">
<span className="text-white text-sm mr-2">Language:</span>
<div className="relative">
<button
onClick={toggleDropdown}
className="flex items-center gap-1 rounded-md bg-white/5 px-3 py-1.5 text-sm text-white hover:bg-white/10 transition-colors"
>
{currentLangObj.label}
{dropdownOpen ? (
<ChevronUp className="h-4 w-4 text-white/70" />
) : (
<ChevronDown className="h-4 w-4 text-white/70" />
)}
</button>
{dropdownOpen && (
<div className="absolute z-10 mt-1 w-full rounded-md bg-black border border-white/10 shadow-lg">
<div className="py-1">
{LANGUAGES.map((lang) => (
<button
key={lang.value}
onClick={() => handleLanguageSelect(lang.value)}
className={`block w-full text-left px-4 py-2 text-sm ${
currentLanguage === lang.value
? 'bg-white/10 text-white'
: 'text-white/70 hover:bg-white/5'
}`}
>
{lang.label}
</button>
))}
</div>
</div>
)}
</div>
</div>
<div className="flex items-center space-x-2">
<Button
variant="ghost"
size="sm"
className="h-8 px-2 text-white/70 hover:text-white hover:bg-white/10"
onClick={onOpenSettings}
title="Settings"
>
<Settings className="h-4 w-4 mr-1" />
<span className="text-xs">Settings</span>
</Button>
<Button
variant="ghost"
size="sm"
className="h-8 px-2 text-red-400/80 hover:text-red-400 hover:bg-white/10"
onClick={handleLogout}
title="Log Out"
>
<LogOut className="h-4 w-4 mr-1" />
<span className="text-xs">Log Out</span>
</Button>
</div>
</div>
);
}

@ -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<QueueCommandsProps> = ({
onTooltipVisibilityChange,
screenshotCount = 0,
credits,
currentLanguage,
setLanguage
}) => {
const [isTooltipVisible, setIsTooltipVisible] = useState(false)
const tooltipRef = useRef<HTMLDivElement>(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 (
<div>
<div className="pt-2 w-fit">
<div className="text-xs text-white/90 backdrop-blur-md bg-black/60 rounded-lg py-2 px-4 flex items-center justify-center gap-4">
{/* Screenshot */}
<div
className="flex items-center gap-2 cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
onClick={async () => {
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")
}
}}
>
<span className="text-[11px] leading-none truncate">
{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"}
</span>
<div className="flex gap-1">
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
{COMMAND_KEY}
</button>
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
H
</button>
</div>
</div>
{/* Solve Command */}
{screenshotCount > 0 && (
<div
className={`flex flex-col cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors ${
credits <= 0 ? "opacity-50 cursor-not-allowed" : ""
}`}
onClick={async () => {
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")
}
}}
>
<div className="flex items-center justify-between">
<span className="text-[11px] leading-none">Solve </span>
<div className="flex gap-1 ml-2">
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
{COMMAND_KEY}
</button>
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
↵
</button>
</div>
</div>
</div>
)}
{/* Separator */}
<div className="mx-2 h-4 w-px bg-white/20" />
{/* Settings with Tooltip */}
<div
className="relative inline-block"
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
{/* Gear icon */}
<div className="w-4 h-4 flex items-center justify-center cursor-pointer text-white/70 hover:text-white/90 transition-colors">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="w-3.5 h-3.5"
>
<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" />
<circle cx="12" cy="12" r="3" />
</svg>
</div>
{/* Tooltip Content */}
{isTooltipVisible && (
<div
ref={tooltipRef}
className="absolute top-full left-0 mt-2 w-80 transform -translate-x-[calc(50%-12px)]"
style={{ zIndex: 100 }}
>
{/* Add transparent bridge */}
<div className="absolute -top-2 right-0 w-full h-2" />
<div className="p-3 text-xs bg-black/80 backdrop-blur-md rounded-lg border border-white/10 text-white/90 shadow-lg">
<div className="space-y-4">
<h3 className="font-medium truncate">Keyboard Shortcuts</h3>
<div className="space-y-3">
{/* Toggle Command */}
<div
className="cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
onClick={async () => {
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"
)
}
}}
>
<div className="flex items-center justify-between">
<span className="truncate">Toggle Window</span>
<div className="flex gap-1 flex-shrink-0">
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
{COMMAND_KEY}
</span>
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
B
</span>
</div>
</div>
<p className="text-[10px] leading-relaxed text-white/70 truncate mt-1">
Show or hide this window.
</p>
</div>
{/* Screenshot Command */}
<div
className="cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
onClick={async () => {
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"
)
}
}}
>
<div className="flex items-center justify-between">
<span className="truncate">Take Screenshot</span>
<div className="flex gap-1 flex-shrink-0">
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
{COMMAND_KEY}
</span>
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
H
</span>
</div>
</div>
<p className="text-[10px] leading-relaxed text-white/70 truncate mt-1">
Take a screenshot of the problem description.
</p>
</div>
{/* Solve Command */}
<div
className={`cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors ${
screenshotCount > 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"
)
}
}}
>
<div className="flex items-center justify-between">
<span className="truncate">Solve</span>
<div className="flex gap-1 flex-shrink-0">
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
{COMMAND_KEY}
</span>
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
↵
</span>
</div>
</div>
<p className="text-[10px] leading-relaxed text-white/70 truncate mt-1">
{screenshotCount > 0
? "Generate a solution based on the current problem."
: "Take a screenshot first to generate a solution."}
</p>
</div>
{/* Delete Last Screenshot Command */}
<div
className={`cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors ${
screenshotCount > 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"
)
}
}}
>
<div className="flex items-center justify-between">
<span className="truncate">Delete Last Screenshot</span>
<div className="flex gap-1 flex-shrink-0">
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
{COMMAND_KEY}
</span>
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
L
</span>
</div>
</div>
<p className="text-[10px] leading-relaxed text-white/70 truncate mt-1">
{screenshotCount > 0
? "Remove the most recently taken screenshot."
: "No screenshots to delete."}
</p>
</div>
</div>
{/* Separator and Log Out */}
<div className="pt-3 mt-3 border-t border-white/10">
<LanguageSelector
currentLanguage={currentLanguage}
setLanguage={setLanguage}
/>
{/* API Key Settings */}
<div className="mb-3 px-2 space-y-1">
<div className="flex items-center justify-between text-[13px] font-medium text-white/90">
<span>OpenAI API Settings</span>
<button
className="bg-white/10 hover:bg-white/20 px-2 py-1 rounded text-[11px]"
onClick={() => window.electronAPI.openSettingsPortal()}
>
Settings
</button>
</div>
</div>
<button
onClick={handleSignOut}
className="flex items-center gap-2 text-[11px] text-red-400 hover:text-red-300 transition-colors w-full"
>
<div className="w-4 h-4 flex items-center justify-center">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="w-3 h-3"
>
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
<polyline points="16 17 21 12 16 7" />
<line x1="21" y1="12" x2="9" y2="12" />
</svg>
</div>
Log Out
</button>
</div>
</div>
</div>
</div>
)}
</div>
</div>
</div>
</div>
)
}
export default QueueCommands

@ -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<ScreenshotItemProps> = ({
screenshot,
onDelete,
index,
isLoading
}) => {
const handleDelete = async () => {
await onDelete(index)
}
return (
<>
<div
className={`border border-white relative w-[128px] h-[72px] ${
isLoading ? "" : "group"
}`}
>
<div className="w-full h-full relative">
{isLoading && (
<div className="absolute inset-0 bg-black bg-opacity-50 z-10 flex items-center justify-center">
<div className="w-6 h-6 border-2 border-white border-t-transparent rounded-full animate-spin" />
</div>
)}
<img
src={screenshot.preview}
alt="Screenshot"
className={`w-full h-full object-cover transition-transform duration-300 ${
isLoading
? "opacity-50"
: "cursor-pointer group-hover:scale-105 group-hover:brightness-75"
}`}
/>
</div>
{!isLoading && (
<button
onClick={(e) => {
e.stopPropagation()
handleDelete()
}}
className="absolute top-2 left-2 p-1 rounded-full bg-black bg-opacity-50 text-white opacity-0 group-hover:opacity-100 transition-opacity duration-300"
aria-label="Delete screenshot"
>
<X size={16} />
</button>
)}
</div>
</>
)
}
export default ScreenshotItem

@ -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<ScreenshotQueueProps> = ({
isLoading,
screenshots,
onDeleteScreenshot
}) => {
if (screenshots.length === 0) {
return <></>
}
const displayScreenshots = screenshots.slice(0, 5)
return (
<div className="flex gap-4">
{displayScreenshots.map((screenshot, index) => (
<ScreenshotItem
key={screenshot.path}
isLoading={isLoading}
screenshot={screenshot}
index={index}
onDelete={onDeleteScreenshot}
/>
))}
</div>
)
}
export default ScreenshotQueue

@ -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 (
<Dialog open={open} onOpenChange={handleOpenChange}>
{/* Removed unnecessary dialog trigger - using the icon in QueueCommands instead */}
<DialogContent
className="sm:max-w-md bg-black border border-white/10 text-white settings-dialog"
style={{
position: 'fixed',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 'min(450px, 90vw)',
height: 'auto',
minHeight: '400px',
maxHeight: '90vh',
overflowY: 'auto',
zIndex: 9999,
margin: 0,
padding: '20px',
transition: 'opacity 0.25s ease, transform 0.25s ease',
animation: 'fadeIn 0.25s ease forwards',
opacity: 0.98
}}
> <DialogHeader>
<DialogTitle>OpenAI API Settings</DialogTitle>
<DialogDescription className="text-white/70">
Configure your OpenAI API key and model preferences. You'll need your own OpenAI API key to use this application.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<label className="text-sm font-medium text-white" htmlFor="apiKey">
OpenAI API Key
</label>
<Input
id="apiKey"
type="password"
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
placeholder="sk-..."
className="bg-black/50 border-white/10 text-white"
/>
{apiKey && (
<p className="text-xs text-white/50">
Current: {maskApiKey(apiKey)}
</p>
)}
<p className="text-xs text-white/50">
Your API key is stored locally and never sent to any server except OpenAI
</p>
<div className="mt-2 p-2 rounded-md bg-white/5 border border-white/10">
<p className="text-xs text-white/80 mb-1">Don't have an API key?</p>
<p className="text-xs text-white/60 mb-1">1. Create an account at <button
onClick={() => openExternalLink('https://platform.openai.com/signup')}
className="text-blue-400 hover:underline cursor-pointer">OpenAI</button>
</p>
<p className="text-xs text-white/60 mb-1">2. Go to <button
onClick={() => openExternalLink('https://platform.openai.com/api-keys')}
className="text-blue-400 hover:underline cursor-pointer">API Keys</button> section
</p>
<p className="text-xs text-white/60">3. Create a new secret key and paste it here</p>
</div>
</div>
<div className="space-y-2 mt-4">
<label className="text-sm font-medium text-white mb-2 block">Keyboard Shortcuts</label>
<div className="bg-black/30 border border-white/10 rounded-lg p-3">
<div className="grid grid-cols-2 gap-y-2 text-xs">
<div className="text-white/70">Toggle Visibility</div>
<div className="text-white/90 font-mono">Ctrl+B / Cmd+B</div>
<div className="text-white/70">Take Screenshot</div>
<div className="text-white/90 font-mono">Ctrl+H / Cmd+H</div>
<div className="text-white/70">Process Screenshots</div>
<div className="text-white/90 font-mono">Ctrl+Enter / Cmd+Enter</div>
<div className="text-white/70">Delete Last Screenshot</div>
<div className="text-white/90 font-mono">Ctrl+L / Cmd+L</div>
<div className="text-white/70">Reset View</div>
<div className="text-white/90 font-mono">Ctrl+R / Cmd+R</div>
<div className="text-white/70">Quit Application</div>
<div className="text-white/90 font-mono">Ctrl+Q / Cmd+Q</div>
<div className="text-white/70">Move Window</div>
<div className="text-white/90 font-mono">Ctrl+Arrow Keys</div>
<div className="text-white/70">Decrease Opacity</div>
<div className="text-white/90 font-mono">Ctrl+[ / Cmd+[</div>
<div className="text-white/70">Increase Opacity</div>
<div className="text-white/90 font-mono">Ctrl+] / Cmd+]</div>
<div className="text-white/70">Zoom Out</div>
<div className="text-white/90 font-mono">Ctrl+- / Cmd+-</div>
<div className="text-white/70">Reset Zoom</div>
<div className="text-white/90 font-mono">Ctrl+0 / Cmd+0</div>
<div className="text-white/70">Zoom In</div>
<div className="text-white/90 font-mono">Ctrl+= / Cmd+=</div>
</div>
</div>
</div>
<div className="space-y-4 mt-4">
<label className="text-sm font-medium text-white">AI Model Selection</label>
<p className="text-xs text-white/60 -mt-3 mb-2">
Select which models to use for each stage of the process
</p>
{modelCategories.map((category) => (
<div key={category.key} className="mb-4">
<label className="text-sm font-medium text-white mb-1 block">
{category.title}
</label>
<p className="text-xs text-white/60 mb-2">{category.description}</p>
<div className="space-y-2">
{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 (
<div
key={m.id}
className={`p-2 rounded-lg cursor-pointer transition-colors ${
currentValue === m.id
? "bg-white/10 border border-white/20"
: "bg-black/30 border border-white/5 hover:bg-white/5"
}`}
onClick={() => setValue(m.id)}
>
<div className="flex items-center gap-2">
<div
className={`w-3 h-3 rounded-full ${
currentValue === m.id ? "bg-white" : "bg-white/20"
}`}
/>
<div>
<p className="font-medium text-white text-xs">{m.name}</p>
<p className="text-xs text-white/60">{m.description}</p>
</div>
</div>
</div>
);
})}
</div>
</div>
))}
</div>
</div>
<DialogFooter className="flex justify-between sm:justify-between">
<Button
variant="outline"
onClick={() => handleOpenChange(false)}
className="border-white/10 hover:bg-white/5 text-white"
>
Cancel
</Button>
<Button
className="px-4 py-3 bg-white text-black rounded-xl font-medium hover:bg-white/90 transition-colors"
onClick={handleSave}
disabled={isLoading || !apiKey}
>
{isLoading ? "Saving..." : "Save Settings"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

@ -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<SolutionCommandsProps> = ({
onTooltipVisibilityChange,
isProcessing,
extraScreenshots = [],
credits,
currentLanguage,
setLanguage
}) => {
const [isTooltipVisible, setIsTooltipVisible] = useState(false)
const tooltipRef = useRef<HTMLDivElement>(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 (
<div>
<div className="pt-2 w-fit">
<div className="text-xs text-white/90 backdrop-blur-md bg-black/60 rounded-lg py-2 px-4 flex items-center justify-center gap-4">
{/* Show/Hide - Always visible */}
<div
className="flex items-center gap-2 cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
onClick={async () => {
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")
}
}}
>
<span className="text-[11px] leading-none">Show/Hide</span>
<div className="flex gap-1">
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
{COMMAND_KEY}
</button>
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
B
</button>
</div>
</div>
{/* Screenshot and Debug commands - Only show if not processing */}
{!isProcessing && (
<>
<div
className="flex items-center gap-2 cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
onClick={async () => {
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")
}
}}
>
<span className="text-[11px] leading-none truncate">
{extraScreenshots.length === 0
? "Screenshot your code"
: "Screenshot"}
</span>
<div className="flex gap-1">
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
{COMMAND_KEY}
</button>
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
H
</button>
</div>
</div>
{extraScreenshots.length > 0 && (
<div
className="flex items-center gap-2 cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
onClick={async () => {
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"
)
}
}}
>
<span className="text-[11px] leading-none">Debug</span>
<div className="flex gap-1">
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
{COMMAND_KEY}
</button>
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
↵
</button>
</div>
</div>
)}
</>
)}
{/* Start Over - Always visible */}
<div
className="flex items-center gap-2 cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
onClick={async () => {
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")
}
}}
>
<span className="text-[11px] leading-none">Start Over</span>
<div className="flex gap-1">
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
{COMMAND_KEY}
</button>
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
R
</button>
</div>
</div>
{/* Separator */}
<div className="mx-2 h-4 w-px bg-white/20" />
{/* Settings with Tooltip */}
<div
className="relative inline-block"
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
{/* Gear icon */}
<div className="w-4 h-4 flex items-center justify-center cursor-pointer text-white/70 hover:text-white/90 transition-colors">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="w-3.5 h-3.5"
>
<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" />
<circle cx="12" cy="12" r="3" />
</svg>
</div>
{/* Tooltip Content */}
{isTooltipVisible && (
<div
ref={tooltipRef}
className="absolute top-full right-0 mt-2 w-80"
style={{ zIndex: 100 }}
>
{/* Add transparent bridge */}
<div className="absolute -top-2 right-0 w-full h-2" />
<div className="p-3 text-xs bg-black/80 backdrop-blur-md rounded-lg border border-white/10 text-white/90 shadow-lg">
<div className="space-y-4">
<h3 className="font-medium whitespace-nowrap">
Keyboard Shortcuts
</h3>
<div className="space-y-3">
{/* Show/Hide - Always visible */}
<div
className="cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
onClick={async () => {
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"
)
}
}}
>
<div className="flex items-center justify-between">
<span className="truncate">Toggle Window</span>
<div className="flex gap-1 flex-shrink-0">
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
{COMMAND_KEY}
</span>
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
B
</span>
</div>
</div>
<p className="text-[10px] leading-relaxed text-white/70 truncate mt-1">
Show or hide this window.
</p>
</div>
{/* Screenshot and Debug commands - Only show if not processing */}
{!isProcessing && (
<>
<div
className="cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
onClick={async () => {
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"
)
}
}}
>
<div className="flex items-center justify-between">
<span className="truncate">Take Screenshot</span>
<div className="flex gap-1 flex-shrink-0">
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
{COMMAND_KEY}
</span>
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
H
</span>
</div>
</div>
<p className="text-[10px] leading-relaxed text-white/70 truncate mt-1">
Capture additional parts of the question or your
solution for debugging help.
</p>
</div>
{extraScreenshots.length > 0 && (
<div
className="cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
onClick={async () => {
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"
)
}
}}
>
<div className="flex items-center justify-between">
<span className="truncate">Debug</span>
<div className="flex gap-1 flex-shrink-0">
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
{COMMAND_KEY}
</span>
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
↵
</span>
</div>
</div>
<p className="text-[10px] leading-relaxed text-white/70 truncate mt-1">
Generate new solutions based on all previous and
newly added screenshots.
</p>
</div>
)}
</>
)}
{/* Start Over - Always visible */}
<div
className="cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
onClick={async () => {
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")
}
}}
>
<div className="flex items-center justify-between">
<span className="truncate">Start Over</span>
<div className="flex gap-1 flex-shrink-0">
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
{COMMAND_KEY}
</span>
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
R
</span>
</div>
</div>
<p className="text-[10px] leading-relaxed text-white/70 truncate mt-1">
Start fresh with a new question.
</p>
</div>
</div>
{/* Separator and Log Out */}
<div className="pt-3 mt-3 border-t border-white/10">
<LanguageSelector
currentLanguage={currentLanguage}
setLanguage={setLanguage}
/>
{/* API Key Settings */}
<div className="mb-3 px-2 space-y-1">
<div className="flex items-center justify-between text-[13px] font-medium text-white/90">
<span>OpenAI API Settings</span>
<button
className="bg-white/10 hover:bg-white/20 px-2 py-1 rounded text-[11px]"
onClick={() => window.electronAPI.openSettingsPortal()}
>
Settings
</button>
</div>
</div>
<button
onClick={handleSignOut}
className="flex items-center gap-2 text-[11px] text-red-400 hover:text-red-300 transition-colors w-full"
>
<div className="w-4 h-4 flex items-center justify-center">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="w-3 h-3"
>
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
<polyline points="16 17 21 12 16 7" />
<line x1="21" y1="12" x2="9" y2="12" />
</svg>
</div>
Log Out
</button>
</div>
</div>
</div>
</div>
)}
</div>
</div>
</div>
</div>
)
}
export default SolutionCommands

@ -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 (
<Dialog open={true}>
<DialogContent
className="bg-black/90 text-white border-white/20"
onPointerDownOutside={(e) => e.preventDefault()}
>
<div className="p-4">
<h2 className="text-lg font-semibold mb-4">
{updateDownloaded
? "Update Ready to Install"
: "A New Version is Available"}
</h2>
<p className="text-sm text-white/70 mb-6">
{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."}
</p>
<div className="flex justify-end gap-2">
{updateDownloaded ? (
<Button
variant="outline"
onClick={handleInstallUpdate}
className="border-white/20 hover:bg-white/10"
>
Restart and Install
</Button>
) : (
<Button
variant="outline"
onClick={handleStartUpdate}
disabled={isDownloading}
className="border-white/20 hover:bg-white/10"
>
{isDownloading ? "Downloading..." : "Download Update"}
</Button>
)}
</div>
</div>
</DialogContent>
</Dialog>
)
}

@ -0,0 +1,73 @@
import React from 'react';
import { Button } from './ui/button';
interface WelcomeScreenProps {
onOpenSettings: () => void;
}
export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({ onOpenSettings }) => {
return (
<div className="bg-black min-h-screen flex flex-col items-center justify-center p-6">
<div className="max-w-md w-full bg-black border border-white/10 rounded-xl p-6 shadow-lg">
<h1 className="text-2xl font-bold text-white mb-6 flex items-center gap-2">
<span>Interview Coder</span>
<span className="text-sm font-normal px-2 py-0.5 bg-blue-500/20 text-blue-400 rounded-md">Unlocked Edition</span>
</h1>
<div className="mb-8">
<h2 className="text-lg font-medium text-white mb-3">Welcome to Interview Coder</h2>
<p className="text-white/70 text-sm mb-4">
This application helps you ace technical interviews by providing AI-powered
solutions to coding problems.
</p>
<div className="bg-white/5 border border-white/10 rounded-lg p-4 mb-4">
<h3 className="text-white/90 font-medium mb-2">Global Shortcuts</h3>
<ul className="space-y-2">
<li className="flex justify-between text-sm">
<span className="text-white/70">Toggle Visibility</span>
<span className="text-white/90">Ctrl+B / Cmd+B</span>
</li>
<li className="flex justify-between text-sm">
<span className="text-white/70">Take Screenshot</span>
<span className="text-white/90">Ctrl+H / Cmd+H</span>
</li>
<li className="flex justify-between text-sm">
<span className="text-white/70">Delete Last Screenshot</span>
<span className="text-white/90">Ctrl+L / Cmd+L</span>
</li>
<li className="flex justify-between text-sm">
<span className="text-white/70">Process Screenshots</span>
<span className="text-white/90">Ctrl+Enter / Cmd+Enter</span>
</li>
<li className="flex justify-between text-sm">
<span className="text-white/70">Reset View</span>
<span className="text-white/90">Ctrl+R / Cmd+R</span>
</li>
<li className="flex justify-between text-sm">
<span className="text-white/70">Quit App</span>
<span className="text-white/90">Ctrl+Q / Cmd+Q</span>
</li>
</ul>
</div>
</div>
<div className="bg-white/5 border border-white/10 rounded-lg p-4 mb-6">
<h3 className="text-white/90 font-medium mb-2">Getting Started</h3>
<p className="text-white/70 text-sm mb-3">
Before using the application, you need to configure your OpenAI API key.
</p>
<Button
className="w-full px-4 py-3 bg-white text-black rounded-xl font-medium hover:bg-white/90 transition-colors flex items-center justify-center gap-2"
onClick={onOpenSettings}
>
Open Settings
</Button>
</div>
<div className="text-white/40 text-xs text-center">
Start by taking screenshots of your coding problem (Ctrl+H / Cmd+H)
</div>
</div>
</div>
);
};

@ -0,0 +1,57 @@
import React from "react"
interface LanguageSelectorProps {
currentLanguage: string
setLanguage: (language: string) => void
}
export const LanguageSelector: React.FC<LanguageSelectorProps> = ({
currentLanguage,
setLanguage
}) => {
const handleLanguageChange = async (
e: React.ChangeEvent<HTMLSelectElement>
) => {
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 (
<div className="mb-3 px-2 space-y-1">
<div className="flex items-center justify-between text-[13px] font-medium text-white/90">
<span>Language</span>
<select
value={currentLanguage}
onChange={handleLanguageChange}
className="bg-black/80 text-white/90 rounded px-2 py-1 text-sm outline-none border border-white/10 focus:border-white/20"
style={{ WebkitAppearance: 'menulist' }}
>
<option value="python" className="bg-black text-white">Python</option>
<option value="javascript" className="bg-black text-white">JavaScript</option>
<option value="java" className="bg-black text-white">Java</option>
<option value="golang" className="bg-black text-white">Go</option>
<option value="cpp" className="bg-black text-white">C++</option>
<option value="swift" className="bg-black text-white">Swift</option>
<option value="kotlin" className="bg-black text-white">Kotlin</option>
<option value="ruby" className="bg-black text-white">Ruby</option>
<option value="sql" className="bg-black text-white">SQL</option>
<option value="r" className="bg-black text-white">R</option>
</select>
</div>
</div>
)
}

@ -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<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }

@ -0,0 +1,75 @@
import * as React from "react"
import { cn } from "../../lib/utils"
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-xl border bg-card text-card-foreground shadow",
className
)}
{...props}
/>
))
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h3
ref={ref}
className={cn("font-semibold leading-none tracking-tight", className)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<p
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }

@ -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<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn("fixed inset-0 bg-black bg-opacity-50 z-50", className)}
{...props}
/>
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed z-50 top-[50%] left-[50%] -translate-x-1/2 -translate-y-1/2",
"w-[90vw] max-w-md md:w-full",
"bg-white p-4 rounded-lg shadow-lg",
"focus:outline-none focus-visible:ring-0",
className
)}
style={{ maxHeight: '90vh', overflow: 'auto' }}
{...props}
>
{children}
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
const DialogClose = DialogPrimitive.Close
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn("flex flex-col space-y-1.5 text-left mb-4", className)}
{...props}
/>
)
DialogHeader.displayName = "DialogHeader"
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2 mt-4", className)}
{...props}
/>
)
DialogFooter.displayName = "DialogFooter"
const DialogTitle = React.forwardRef<
HTMLHeadingElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold text-white", className)}
{...props}
/>
))
DialogTitle.displayName = DialogPrimitive.Title.displayName
const DialogDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-gray-400", className)}
{...props}
/>
))
DialogDescription.displayName = DialogPrimitive.Description.displayName
export {
Dialog,
DialogTrigger,
DialogContent,
DialogClose,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription
}

@ -0,0 +1,24 @@
import * as React from "react"
import { cn } from "../../lib/utils"
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }

@ -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<typeof ToastPrimitive.Viewport>,
React.ComponentPropsWithoutRef<typeof ToastPrimitive.Viewport>
>(({ className, ...props }, ref) => (
<ToastPrimitive.Viewport
ref={ref}
className={cn(
"fixed top-0 right-0 z-[100] flex max-h-screen w-full flex-col-reverse gap-1 p-2 sm:top-0 sm:right-0 sm:flex-col md:max-w-[320px]",
className
)}
{...props}
/>
))
ToastViewport.displayName = ToastPrimitive.Viewport.displayName
type ToastVariant = "neutral" | "success" | "error"
interface ToastProps
extends React.ComponentPropsWithoutRef<typeof ToastPrimitive.Root> {
variant?: ToastVariant
swipeDirection?: "right" | "left" | "up" | "down"
}
const toastVariants: Record<
ToastVariant,
{ icon: React.ReactNode; bgColor: string }
> = {
neutral: {
icon: <Info className="h-3 w-3 text-amber-700" />,
bgColor: "bg-amber-100"
},
success: {
icon: <CheckCircle2 className="h-3 w-3 text-emerald-700" />,
bgColor: "bg-emerald-100"
},
error: {
icon: <AlertCircle className="h-3 w-3 text-red-700" />,
bgColor: "bg-red-100"
}
}
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitive.Root>,
ToastProps
>(({ className, variant = "neutral", ...props }, ref) => (
<ToastPrimitive.Root
ref={ref}
duration={4000}
className={cn(
"group pointer-events-auto relative flex w-full items-center space-x-2 overflow-hidden rounded-md p-2",
toastVariants[variant].bgColor,
className
)}
{...props}
>
{toastVariants[variant].icon}
<div className="flex-1">{props.children}</div>
<ToastPrimitive.Close className="absolute right-1 top-1 rounded-md p-0.5 text-zinc-500 opacity-0 transition-opacity hover:text-zinc-700 group-hover:opacity-100">
<X className="h-2 w-2" />
</ToastPrimitive.Close>
</ToastPrimitive.Root>
))
Toast.displayName = ToastPrimitive.Root.displayName
const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof ToastPrimitive.Action>
>(({ className, ...props }, ref) => (
<ToastPrimitive.Action
ref={ref}
className={cn(
"text-[0.65rem] font-medium text-zinc-600 hover:text-zinc-900",
className
)}
{...props}
/>
))
ToastAction.displayName = ToastPrimitive.Action.displayName
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitive.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitive.Title
ref={ref}
className={cn("text-[0.7rem] font-medium text-zinc-900", className)}
{...props}
/>
))
ToastTitle.displayName = ToastPrimitive.Title.displayName
const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitive.Description>
>(({ className, ...props }, ref) => (
<ToastPrimitive.Description
ref={ref}
className={cn("text-[0.65rem] text-zinc-600", className)}
{...props}
/>
))
ToastDescription.displayName = ToastPrimitive.Description.displayName
export type { ToastProps, ToastVariant }
export {
ToastProvider,
ToastViewport,
Toast,
ToastAction,
ToastTitle,
ToastDescription
}

@ -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<ToastContextType | undefined>(
undefined
)
export function useToast() {
const context = useContext(ToastContext)
if (!context) {
throw new Error("useToast must be used within a ToastProvider")
}
return context
}

76
src/env.d.ts vendored

@ -0,0 +1,76 @@
/// <reference types="vite/client" />
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<void>
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
}

@ -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;
}

@ -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<typeof supabase.channel> | 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
}
}
})

@ -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))
}

@ -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(
<React.StrictMode>
<App />
</React.StrictMode>
)

@ -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<void>
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<void>
setInitialCredits: (credits: number) => Promise<void>
onCreditsUpdated: (callback: (credits: number) => void) => () => void
onOutOfCredits: (callback: () => void) => () => void
openSettingsPortal: () => Promise<void>
getPlatform: () => string
// New methods for OpenAI integration
getConfig: () => Promise<{ apiKey: string; model: string }>
updateConfig: (config: { apiKey?: string; model?: string }) => Promise<boolean>
checkApiKey: () => Promise<boolean>
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
}
}

@ -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
}

@ -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
}

@ -0,0 +1,4 @@
export interface Screenshot {
path: string
preview: string
}

@ -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
}

@ -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'

11
src/vite-env.d.ts vendored

@ -0,0 +1,11 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_SUPABASE_URL: string
readonly VITE_SUPABASE_ANON_KEY: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}

@ -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.

@ -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: []
}

@ -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/**/*"]
}

@ -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" }]
}

@ -0,0 +1,10 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true
},
"include": ["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")
}
}
})
Loading…
Cancel
Save