Compare commits

..
156 changed files with 2817 additions and 13495 deletions

No files matched your search

-41
View File
@@ -279,47 +279,6 @@ The AI assistant's behavior and knowledge is defined by the AGENTS.md file, whic
1. Edit AGENTS.md directly
2. The changes take effect in the next session
## Translations
Shakespeare includes internationalization (i18n) support using react-i18next. The translation system allows the interface to be displayed in multiple languages.
### Key Files
- **`src/lib/i18n.ts`**: Main translation configuration file containing all translation resources for supported languages
- **`src/components/LanguagePicker.tsx`**: Language selection component used in preferences, must be updated when adding new languages
### Usage in Components
Use the `useTranslation` hook to access translations in React components:
```tsx
import { useTranslation } from 'react-i18next';
function MyComponent() {
const { t } = useTranslation();
return <h1>{t('settings')}</h1>; // Returns "Settings", "Configurações", etc.
}
```
### Translation Key Organization
Translation keys are organized by functionality:
- **Navigation and Layout**: `preferences`, `settings`, `help`, etc.
- **Authentication**: `logIn`, `signUp`
- **UI Elements**: `save`, `cancel`, `loading`, etc.
- **Feature-specific sections**: AI Settings, Git Settings, Nostr Settings, etc.
### Adding New Languages
1. Add the new language code and translation object to the `resources` object in `src/lib/i18n.ts`
2. Add all required key-value pairs for the new language, following existing patterns
3. Update `src/components/LanguagePicker.tsx` to include the new language option in the dropdown
4. Add the language name translations (e.g., `spanish: 'Spanish'`) to all existing language objects
5. Use descriptive, hierarchical key names (avoid duplicates)
6. Keep translations concise and consistent with existing patterns
7. Test the new language thoroughly to ensure proper display across all components
## "Vibed with MKStack"
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
-661
View File
@@ -1,661 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<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/>.
-128
View File
@@ -1,128 +0,0 @@
# OPFS Compatibility Fix for isomorphic-git Clone Operations
## Issue Description
The error `TypeError: Cannot read properties of undefined (reading 'error')` occurs when using OPFS (Origin Private File System) with isomorphic-git during Git clone operations. This happens specifically in the `readObjectPacked` function within isomorphic-git when it tries to read Git pack files.
### Root Cause
The issue stems from subtle differences between how OPFS handles binary data compared to LightningFS/IndexedDB:
1. **Binary Data Handling**: isomorphic-git expects very specific behavior from Uint8Array objects, particularly when reading Git pack files
2. **Error Object Structure**: isomorphic-git expects error objects in a specific Node.js-style format
3. **Filesystem API Differences**: OPFS uses different APIs that don't always match the expected Node.js filesystem behavior
## Solution Implemented
### 1. Enhanced OPFS Adapter (`OPFSAdapterSimple.ts`)
**Improved Binary Data Handling:**
- Added special handling for Git files to ensure Uint8Array compatibility
- Created fresh Uint8Array instances to avoid browser-specific quirks
- Added validation for array methods that isomorphic-git expects
- Enhanced error handling with proper Node.js-style error codes
**Debug Mode:**
- Added optional debug logging to track filesystem operations
- Helps identify specific issues during Git operations
### 2. Better Error Handling (`ProjectsManager.ts`)
**Enhanced Clone Operation:**
- Added timeout mechanism (60 seconds) to prevent hanging
- Improved error detection for OPFS compatibility issues
- Better cleanup of failed project directories
- More descriptive error messages for users
**OPFS Issue Detection:**
- Automatically detects filesystem compatibility issues
- Provides clear recommendations to switch to LightningFS
- User-friendly error messages explaining the problem
### 3. Filesystem Selection UI (`DataSettings.tsx`)
**User Interface Improvements:**
- Clear warnings about OPFS Git compatibility issues
- Information about when to use each filesystem type
- Automatic fallback mechanism when OPFS initialization fails
### 4. Automatic Fallback (`App.tsx`)
**Robust Initialization:**
- Tests OPFS functionality before using it
- Automatically falls back to LightningFS if OPFS fails
- Better error reporting and user feedback
## Usage Recommendations
### When to Use LightningFS (Recommended)
- **Git Operations**: Better compatibility with isomorphic-git
- **Stability**: Proven track record with Shakespeare
- **Cross-browser**: Works in all modern browsers
- **Default Choice**: Recommended for most users
### When to Use OPFS (Experimental)
- **Large Storage**: When you need larger storage quotas
- **Performance**: Potentially better performance for file operations
- **Modern Browsers**: Only in Chrome, Edge, Firefox 111+
- **Non-Git Workflows**: For projects that don't require Git operations
## Technical Details
### Error Patterns Detected
The fix detects these specific error patterns that indicate OPFS compatibility issues:
- `Cannot read properties of undefined`
- `readObjectPacked` errors
- `reading 'error'` errors
- TypeError in isomorphic-git stack traces
### Binary Data Compatibility
```typescript
// Enhanced Uint8Array creation for Git compatibility
const gitCompatibleArray = new Uint8Array(uint8Array.length);
gitCompatibleArray.set(uint8Array);
// Validation of required methods
if (!gitCompatibleArray.slice || typeof gitCompatibleArray.slice !== 'function') {
throw new Error('Uint8Array missing required methods');
}
```
### Error Handling
```typescript
// Node.js-style error objects
const nodeError = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
nodeError.code = 'ENOENT';
nodeError.errno = -2;
nodeError.syscall = 'open';
nodeError.path = path;
```
## Testing
The fix includes:
- ✅ All existing tests pass
- ✅ Enhanced error handling
- ✅ Automatic fallback mechanisms
- ✅ User interface improvements
- ✅ Debug logging capabilities
## Migration Path
For users experiencing OPFS issues:
1. **Immediate Fix**: Switch to LightningFS in Data Settings
2. **Export Data**: Use the export feature before switching filesystems
3. **Refresh**: Page will automatically refresh to apply new filesystem
4. **Import**: Recreate projects as needed
## Future Improvements
1. **Better OPFS Support**: Continue improving OPFS compatibility
2. **Hybrid Approach**: Use OPFS for regular files, LightningFS for Git
3. **Performance Monitoring**: Track filesystem performance differences
4. **User Analytics**: Monitor which filesystem users prefer
## Conclusion
This fix provides a robust solution for the OPFS/isomorphic-git compatibility issue while maintaining backward compatibility and providing clear user guidance. Users can continue using OPFS for non-Git operations while having LightningFS as a reliable fallback for Git-heavy workflows.
-44
View File
@@ -1,44 +0,0 @@
# OPFS Debugging Instructions
## Current Issue
Project creation fails with OPFS due to isomorphic-git compatibility issues.
## Debug Steps
1. **Enable OPFS in browser**:
- Go to Shakespeare app
- Settings → Data Settings → Filesystem Type → OPFS
- Save and refresh
2. **Try to create a project**:
- Enter a description like "test project"
- Select a model
- Click "Create Project"
3. **Check browser console**:
- Open DevTools (F12)
- Look for debug logs starting with `OPFSAdapter.readFile called with path:`
- Look for `OPFSAdapter.mkdir called with path:`
- Look for `OPFSAdapter.stat called with path:`
## Expected Debug Output
If our fixes work, you should see logs like:
```
OPFSAdapter.readFile called with path: /projects/test-project/.git/config encoding: utf8
OPFSAdapter.stat called with path: /projects/test-project
OPFSAdapter.mkdir called with path: /projects/test-project options: { recursive: true }
```
## Current Problems
1. **Undefined paths**: isomorphic-git calls our adapter with `undefined` paths
2. **Git config parsing**: "text.split is not a function" error suggests Git is trying to parse error messages as config files
3. **Directory creation**: Git directory structure creation fails
## Next Steps
Based on what we see in debug logs, we can:
1. Identify exactly which paths are being called as undefined
2. Fix the specific filesystem contract issues
3. Ensure proper error handling that doesn't break Git operations
-265
View File
@@ -1,265 +0,0 @@
# OPFS Fixes for Shakespeare
This document summarizes the fixes implemented to resolve OPFS (Origin Private File System) issues in Shakespeare.
## Problem Description
Users experienced complete failures when attempting to create projects using OPFS. The errors included:
1. **Undefined Path Error**: `Cannot read properties of undefined (reading 'includes')`
2. **Directory Creation Failures**: `ENOENT: no such file or directory, scandir '/projects/squirrel-junction/.git'`
3. **Git Operation Failures**: `text.split is not a function` from Git config parsing
4. **Filesystem Incompatibility**: OPFS adapter wasn't fully compatible with isomorphic-git expectations
## Root Cause Analysis
The issues stemmed from several problems in the OPFS adapter implementation:
### 1. Insufficient Path Validation
The `readFile` method didn't validate input paths, leading to attempts to call `.includes()` on undefined values.
### 2. Inconsistent Error Handling
OPFS throws DOMException errors, but isomorphic-git expects Node.js-style errors with specific error codes (ENOENT, EACCES, etc.).
### 3. Recursive Directory Creation Issues
The recursive directory creation logic didn't handle partial path failures properly, especially for Git directory structures.
### 4. Git Compatibility Problems
The adapter didn't fully support the filesystem operations that isomorphic-git requires for repository operations.
## Fixes Implemented
### 1. Enhanced Path Validation
**File**: `src/lib/OPFSAdapter.ts`
**Changes**:
```typescript
// Added null/undefined path validation
if (!path || typeof path !== 'string') {
const error = new Error('ENOENT: no such file or directory, open \'undefined\'') as NodeJS.ErrnoException;
error.code = 'ENOENT';
error.errno = -2;
error.syscall = 'open';
error.path = path || 'undefined';
throw error;
}
```
**Impact**: Prevents the "Cannot read properties of undefined" error.
### 2. Improved Error Handling
**File**: `src/lib/OPFSAdapter.ts`
**Changes**:
```typescript
// Convert DOMException to Node.js style errors
if (error instanceof Error && error.message.includes('NotFound')) {
const nodeError = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
nodeError.code = 'ENOENT';
nodeError.errno = -2;
nodeError.syscall = 'open';
nodeError.path = path;
throw nodeError;
}
```
**Impact**: Makes OPFS errors compatible with isomorphic-git.
### 3. Better Recursive Directory Creation
**File**: `src/lib/OPFSAdapter.ts`
**Changes**:
```typescript
private async createDirectoriesRecursive(path: string): Promise<void> {
try {
const parts = path.split('/').filter(Boolean);
let currentHandle = await this.root;
for (const part of parts) {
try {
currentHandle = await currentHandle.getDirectoryHandle(part, { create: true });
} catch (error) {
console.error(`Failed to create directory part '${part}' in path '${path}':`, error);
throw new Error(`Failed to create directory ${path}: ${error}`);
}
}
} catch (error) {
console.error(`OPFSAdapter.createDirectoriesRecursive failed for path: ${path}`, error);
throw error;
}
}
```
**Impact**: Ensures Git directory structures can be created reliably.
### 4. Enhanced Git Operation Support
**File**: `src/lib/OPFSAdapter.ts`
**Changes**:
```typescript
private async readFileForGit(path: string): Promise<Uint8Array> {
try {
// Guard against undefined path
if (!path || typeof path !== 'string') {
const error = new Error('ENOENT: no such file or directory, open \'undefined\'') as NodeJS.ErrnoException;
error.code = 'ENOENT';
error.errno = -2;
error.syscall = 'open';
error.path = path || 'undefined';
throw error;
}
const fileHandle = await this.getFileHandle(path);
const file = await fileHandle.getFile();
const arrayBuffer = await file.arrayBuffer();
return new Uint8Array(arrayBuffer);
} catch (error) {
// Enhanced error handling for Git operations
console.error(`Git read operation failed for path: ${path}`, error);
// Create a more detailed error that isomorphic-git can handle
const gitError = new Error(`Failed to read Git object: ${path}`) as NodeJS.ErrnoException;
gitError.code = 'ENOENT';
gitError.errno = -2;
gitError.syscall = 'read';
gitError.path = path;
// Preserve original error information by adding it to the message
if (error instanceof Error) {
gitError.message = `${gitError.message}: ${error.message}`;
}
throw gitError;
}
}
```
**Impact**: Makes Git operations (clone, commit, etc.) work reliably with OPFS.
### 5. Improved ProjectsManager Logging
**File**: `src/lib/ProjectsManager.ts`
**Changes**:
```typescript
async createProject(name: string, customId?: string): Promise<Project> {
console.log(`Creating project: ${name}, customId: ${customId}`);
const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId, { depth: 1 });
console.log(`Project cloned at path: ${project.path}`);
try {
await this.fs.mkdir(this.dir + `/${project.id}/.ai/history`, { recursive: true });
console.log(`Created .ai/history directory for project ${project.id}`);
} catch (error) {
console.log(`Directory .ai/history might already exist for project ${project.id}:`, error);
// Directory might already exist
}
// ... rest of the method with enhanced logging
}
```
**Impact**: Provides better debugging information when issues occur.
### 6. Better Filesystem Initialization
**File**: `src/App.tsx`
**Changes**:
```typescript
constructor() {
// Check if OPFS is available
if (!('storage' in navigator) ||
typeof (navigator.storage as unknown as { getDirectory: () => Promise<FileSystemDirectoryHandle> }).getDirectory !== 'function') {
throw new Error('OPFS is not supported in this browser or environment');
}
// Get the root directory handle for OPFS
this.root = (navigator.storage as unknown as { getDirectory: () => Promise<FileSystemDirectoryHandle> }).getDirectory();
}
```
**Impact**: Fails fast if OPFS is not available.
## Testing
All existing tests pass:
```bash
✓ Test Files 83 passed (83)
Tests 564 passed | 6 skipped (570)
```
Type checking and build also pass successfully.
## Browser Compatibility
OPFS is supported in:
- Chrome 86+
- Edge 86+
- Firefox 111+ (limited support)
- Safari 16.4+
For browsers that don't support OPFS, the system automatically falls back to LightningFS.
## Usage Instructions
To use OPFS in Shakespeare:
1. **Enable OPFS in Settings**:
- Go to Settings → Data Settings
- Change "Filesystem Type" to "OPFS"
- Save changes
2. **Restart Application**:
- Refresh the page to apply the new filesystem type
3. **Verify OPFS is Working**:
- Try creating a new project
- Check browser console for successful filesystem operations
- Verify that project creation completes without errors
## Troubleshooting
If OPFS still fails:
1. **Check Browser Support**:
- Ensure you're using a supported browser version
- Check browser console for OPFS availability errors
2. **Clear Browser Data**:
- Clear site data and try again
- This can resolve corrupted OPFS storage issues
3. **Fallback to LightningFS**:
- If OPFS consistently fails, use LightningFS instead
- The system will automatically fall back if OPFS initialization fails
## Performance Considerations
OPFS provides better performance than LightningFS for:
- Large file operations
- Concurrent file access
- Storage persistence
However, OPFS has some limitations:
- No symbolic links
- Different permission model
- Browser-specific implementation details
## Future Improvements
Potential enhancements for OPFS support:
1. **Atomic Operations**: Implement atomic file writes using OPFS transactions
2. **File Locking**: Add file locking mechanisms for concurrent access
3. **Storage Quotas**: Better handling of storage quota limits
4. **Migration Tools**: Tools to migrate existing LightningFS data to OPFS
## Conclusion
The fixes implemented resolve the major OPFS compatibility issues and provide a robust filesystem backend for Shakespeare. The enhanced error handling, improved logging, and better Git compatibility ensure that project creation and management work reliably with OPFS.
-83
View File
@@ -1,83 +0,0 @@
# OPFS Git Clone Fix Summary
## Issues Identified and Fixed
### Issue 1: Binary Pack Files Returned as Text
**Problem**: Git pack index files (`.idx`) were being returned as text instead of binary data because isomorphic-git was passing options objects as the encoding parameter.
**Log Evidence**:
```
[OPFSAdapter] readFile called: path="/projects/untitled-1/.git/objects/pack/pack-be5dbf750d545d214e0191ae909d83915c6beb6a.idx", encoding="[object Object]"
[OPFSAdapter] Returning text content for encoding "[object Object]", length=5138
```
**Fix**: Modified encoding detection logic to always return binary data for Git pack files regardless of encoding parameter.
### Issue 2: Git Config Files Returned as Binary
**Problem**: Git configuration files (`.git/config`) were being returned as binary data when they should be text files.
**Log Evidence**:
```
[OPFSAdapter] readFile called: path="/projects/nut-cache/.git/config", encoding="[object Object]"
[OPFSAdapter] Returning binary content: 130 bytes, constructor: Uint8Array, isGitFile: true
TypeError: text.split is not a function
```
**Fix**: Added proper distinction between Git text files and Git binary files.
### Issue 3: Filesystem Capability Testing
**Problem**: isomorphic-git calls `readFile` with undefined paths to test filesystem capabilities, causing unnecessary error logs.
**Fix**: Added proper handling and logging for filesystem capability tests.
## Solution Implementation
### Enhanced File Type Detection
```typescript
// Git binary files that should ALWAYS be returned as Uint8Array
const isGitBinaryFile = path.includes('.git/objects/pack/') ||
(path.includes('.git/objects/') && !path.includes('.git/objects/info/')) ||
path.endsWith('.pack') ||
path.endsWith('.idx') ||
path.includes('.git/index');
// Git text files that should be returned as text
const isGitTextFile = path.includes('.git/config') ||
path.includes('.git/HEAD') ||
path.includes('.git/refs/') ||
path.includes('.git/logs/') ||
path.includes('.git/info/') ||
path.includes('.git/hooks/') ||
path.includes('.git/description');
// Smart encoding detection
const shouldReturnText = (encoding === 'utf8' && typeof encoding === 'string') ||
(!isGitBinaryFile && (isGitTextFile || !path.includes('.git/'))) ||
(isGitTextFile && typeof encoding !== 'string');
```
### Key Insights
1. **isomorphic-git Behavior**: isomorphic-git passes options objects as encoding parameters, not just strings
2. **File Type Distinction**: Git repositories contain both text files (config, refs) and binary files (pack, index, objects)
3. **Capability Testing**: isomorphic-git tests filesystem capabilities by calling methods with invalid parameters
### Testing Status
- ✅ Fixed binary pack file handling
- ✅ Fixed Git config file handling
- ✅ Added proper capability test handling
- ✅ Enhanced debug logging
- ✅ All existing tests pass
- 🔄 Ready for real-world Git clone testing
## Next Steps
The OPFS adapter should now correctly handle Git clone operations by:
1. Returning binary data for Git pack files and objects
2. Returning text data for Git configuration and reference files
3. Properly handling isomorphic-git's filesystem capability tests
4. Providing detailed debug logging for troubleshooting
This should resolve the `TypeError: Cannot read properties of undefined (reading 'error')` and `TypeError: text.split is not a function` errors during Git clone operations with OPFS.
-159
View File
@@ -1,159 +0,0 @@
# OPFS Implementation for Shakespeare
This document describes the implementation of OPFS (Origin Private File System) support as an alternative to LightningFS in the Shakespeare project.
## Overview
The project now supports two filesystem backends:
1. **LightningFS** (IndexedDB) - The original filesystem implementation
2. **OPFS** (Origin Private File System) - A modern browser API for better performance
## Implementation Details
### 1. OPFS Adapter (`src/lib/OPFSAdapter.ts`)
Created a new `OPFSAdapter` class that implements the `JSRuntimeFS` interface, making it compatible with the existing filesystem abstraction. The adapter provides:
- **File Operations**: `readFile`, `writeFile`, `stat`, `unlink`
- **Directory Operations**: `readdir`, `mkdir`, `rmdir`
- **Utility Operations**: `rename`, `copy`, `recursive operations`
- **Error Handling**: Proper error handling with fallback to LightningFS
### 2. Configuration Updates
#### AppContext (`src/contexts/AppContext.ts`)
- Added `FilesystemType` type: `"lightningfs" | "opfs"`
- Extended `AppConfig` interface to include `filesystemType` field
- Updated Zod schema for validation
#### AppProvider (`src/components/AppProvider.tsx`)
- Updated AppConfigSchema to include filesystemType validation
### 3. Dynamic Filesystem Initialization (`src/App.tsx`)
Created a new `FilesystemProvider` component that:
- Detects OPFS availability in the browser
- Dynamically selects the appropriate filesystem backend
- Provides automatic fallback to LightningFS if OPFS fails
- Shows loading states and error messages
### 4. User Interface Updates
#### AppSettingsDialog (`src/components/AppSettingsDialog.tsx`)
- Added filesystem selection UI with RadioGroup component
- Shows OPFS availability detection
- Displays warnings when OPFS is not available
- Includes educational information about each filesystem type
- Automatically refreshes the page when filesystem type changes
### 5. Type Definitions
#### Nostr Types (`src/types/nostr.d.ts`)
- Added proper TypeScript definitions for `window.nostr` object
- Fixed existing TypeScript errors related to Nostr extension access
## Features
### OPFS Advantages
- **Better Performance**: Direct filesystem access without IndexedDB overhead
- **Larger Storage Limits**: Typically higher storage quotas than IndexedDB
- **Modern API**: Uses native browser filesystem APIs
- **Atomic Operations**: Better support for atomic file operations
### LightningFS Advantages
- **Universal Support**: Works in all modern browsers
- **Mature Implementation**: Well-tested and stable
- **Symbolic Links**: Supports symbolic links (OPFS does not)
- **Proven Reliability**: Used in production for years
### User Experience
- **Automatic Detection**: UI automatically shows available options
- **Clear Warnings**: Users are informed when OPFS is not available
- **Safe Switching**: Page refresh ensures clean filesystem transition
- **Fallback Protection**: Automatic fallback prevents data loss
## Browser Compatibility
### OPFS Support
- ✅ Chrome 87+
- ✅ Edge 87+
- ✅ Firefox 111+
- ❌ Safari (limited support)
- ❌ Mobile browsers (varies)
### LightningFS Support
- ✅ All modern browsers
- ✅ Mobile browsers
- ✅ Older browsers (with polyfills)
## Usage
### For Users
1. Go to Settings → App Settings
2. Select preferred filesystem type in the Filesystem section
3. Save changes (page will refresh automatically)
4. The app will use the selected filesystem
### For Developers
- The filesystem is abstracted through the `JSRuntimeFS` interface
- All existing code continues to work without changes
- New filesystem types can be added by implementing the interface
- Use `useFS()` hook to access the filesystem
## Migration
### From LightningFS to OPFS
1. Export current projects using Data Settings → Export Files
2. Change filesystem type in settings
3. Import projects if needed
4. Verify all data is intact
### From OPFS to LightningFS
1. Export current projects using Data Settings → Export Files
2. Change filesystem type in settings
3. Import projects if needed
4. Verify all data is intact
## Error Handling
### OPFS Not Available
- UI shows warning message
- Option is disabled in settings
- Automatic fallback to LightningFS
### Initialization Failures
- Shows error message with details
- Provides browser compatibility information
- Suggests using LightningFS instead
### Runtime Errors
- Graceful error handling in adapter
- Proper error propagation to UI
- Fallback mechanisms where possible
## Testing
- All existing tests continue to pass
- TypeScript compilation successful
- Build process works correctly
- UI components properly render filesystem options
- Error states are handled appropriately
## Future Enhancements
### Potential Improvements
1. **Data Migration Tools**: Automatic migration between filesystem types
2. **Performance Metrics**: Show performance differences between backends
3. **Storage Analytics**: Display usage statistics for each filesystem
4. **Hybrid Approach**: Use different filesystems for different data types
5. **Compression**: Add compression support for better storage efficiency
### Considerations
- OPFS is still evolving; browser support may change
- LightningFS remains the safer choice for maximum compatibility
- Data portability is important for user freedom
- Performance benefits may vary by use case and browser
## Conclusion
The OPFS implementation provides users with a choice between filesystem backends, balancing modern performance advantages with broad compatibility. The implementation maintains backward compatibility while providing a path forward for users on modern browsers.
-68
View File
@@ -1,68 +0,0 @@
# OPFS Git Compatibility Test
## Issue Fixed
The main issue was that isomorphic-git was calling `fs.readFile()` on Git pack index files (`.idx`) with an options object as the encoding parameter, but the OPFS adapter was incorrectly interpreting this as a string encoding and returning text data instead of binary data.
## Debug Output Analysis
```
[OPFSAdapter] readFile called: path="/projects/untitled-1/.git/objects/pack/pack-be5dbf750d545d214e0191ae909d83915c6beb6a.idx", encoding="[object Object]"
[OPFSAdapter] File found: size=5328, type="", lastModified=1758521210388
[OPFSAdapter] Returning text content for encoding "[object Object]", length=5138
```
**Problem**: The `.idx` file is a binary Git pack index file, but it was being returned as text because `encoding="[object Object]"` was being treated as a truthy string value.
**Solution**: Modified the encoding detection logic to:
1. Always return binary data for Git pack files and object files
2. Only return text for explicit `encoding === 'utf8'` on non-Git binary files
3. Handle cases where isomorphic-git passes options objects as encoding
## Code Changes
### Before (Broken)
```typescript
if (encoding === 'utf8') {
return await file.text();
} else if (encoding) {
// BUG: This treated "[object Object]" as truthy and returned text
return await file.text();
} else {
// Binary data
return new Uint8Array(arrayBuffer);
}
```
### After (Fixed)
```typescript
// Git pack files (.pack, .idx) and object files should always be binary
const isGitBinaryFile = path.includes('.git/objects/pack/') ||
(path.includes('.git/objects/') && !path.includes('.git/objects/info/')) ||
path.endsWith('.pack') ||
path.endsWith('.idx') ||
path.includes('.git/index');
// Only return text for explicit 'utf8' encoding on non-Git binary files
const shouldReturnText = !isGitBinaryFile &&
encoding === 'utf8' &&
typeof encoding === 'string';
if (shouldReturnText) {
return await file.text();
} else {
// Return binary data (Uint8Array)
return new Uint8Array(arrayBuffer);
}
```
## Expected Result
With this fix, Git pack index files will be correctly returned as `Uint8Array` binary data, which should resolve the `Cannot read properties of undefined (reading 'error')` error in isomorphic-git's `readObjectPacked` function.
## Testing
To test this fix:
1. Try creating a new project with OPFS enabled
2. The Git clone operation should now succeed
3. Debug logs should show: `Returning binary content: X bytes` for `.idx` files instead of `Returning text content`
-138
View File
@@ -1,138 +0,0 @@
# OPFS UI Improvements
## Problem Addressed
The original implementation had a usability issue where the App Settings dialog (containing filesystem selection) was only accessible through a dropdown menu in the ActionsMenu component, making it very difficult for users to discover and access filesystem settings.
## Solution Implemented
### 1. **Added App Settings to Main Settings Page** (`src/pages/Settings.tsx`)
- Added "App Settings" option to the main settings menu
- Positioned logically between data-related settings and about section
- Uses `Settings` icon for clear visual identification
### 2. **Created Dedicated App Settings Page** (`src/pages/AppSettings.tsx`)
- Full-page settings interface for app configuration
- Organized into clear sections:
- **Filesystem Settings**: OPFS vs LightningFS selection
- **Deployment Settings**: Deploy server configuration
- Responsive design with mobile-friendly layout
- Clear back navigation on mobile devices
### 3. **Updated Routing** (`src/AppRouter.tsx`)
- Added `/settings/app` route for App Settings page
- Integrated with existing SettingsLayout for consistent navigation
- Proper route ordering in settings hierarchy
### 4. **Removed Hidden Access** (`src/components/ActionsMenu.tsx`)
- Removed AppSettingsDialog from ActionsMenu dropdown
- Cleaned up unused imports
- Settings no longer buried in project-specific actions menu
### 5. **Complete Translation Support** (`src/lib/i18n.ts`)
Added comprehensive translations for all new UI elements:
#### English
- `appSettings`: "App Settings"
- `appSettingsDescription`: "Configure filesystem and deployment settings"
- `filesystem`: "Filesystem"
- `filesystemType`: "Filesystem Type"
- `deployment`: "Deployment"
- `deployServer`: "Deploy Server"
- `deployServerDescription`: "Your projects will be deployed to subdomains of this server..."
- `saveSettings`: "Save Settings"
#### Portuguese
- `appSettings`: "Configurações do App"
- `appSettingsDescription`: "Configure sistema de arquivos e configurações de implantação"
- `filesystem`: "Sistema de Arquivos"
- `filesystemType`: "Tipo de Sistema de Arquivos"
- `deployment`: "Implantação"
- `deployServer`: "Servidor de Implantação"
- `deployServerDescription`: "Seus projetos serão implantados em subdomínios deste servidor..."
- `saveSettings`: "Salvar Configurações"
#### Chinese
- `appSettings`: "应用设置"
- `appSettingsDescription`: "配置文件系统和部署设置"
- `filesystem`: "文件系统"
- `filesystemType`: "文件系统类型"
- `deployment`: "部署"
- `deployServer`: "部署服务器"
- `deployServerDescription`: "您的项目将部署到此服务器的子域..."
- `saveSettings`: "保存设置"
## Key UI Improvements
### **Discoverability**
- ✅ Settings now easily accessible from main Settings page
- ✅ Clear, descriptive menu item with appropriate icon
- ✅ Logical grouping with related settings
### **User Experience**
- ✅ Full-page interface with adequate space for explanations
- ✅ Mobile-responsive design with proper navigation
- ✅ Clear visual hierarchy with cards and sections
- ✅ Informative descriptions for each filesystem type
### **Accessibility**
- ✅ Proper semantic HTML structure
- ✅ Clear form labels and associations
- ✅ Keyboard navigation support
- ✅ Screen reader friendly with proper ARIA labels
### **Error Handling**
- ✅ Clear warnings when OPFS is not available
- ✅ Visual indicators for disabled options
- ✅ Helpful error messages and browser compatibility info
- ✅ Automatic fallback to LightningFS when needed
### **Internationalization**
- ✅ Complete translation support for all languages
- ✅ Consistent terminology across languages
- ✅ Culturally appropriate descriptions
## User Flow
### **Before (Poor UX)**
1. User opens project
2. Clicks tiny "more options" button (⋮)
3. Finds "Settings" in dropdown menu
4. Opens dialog to change filesystem settings
5. Hidden and non-intuitive discovery
### **After (Good UX)**
1. User navigates to Settings (accessible from main navigation)
2. Sees "App Settings" option clearly listed
3. Clicks to access full settings page
4. Finds filesystem settings logically grouped with deployment settings
5. Clear, discoverable, and intuitive
## Technical Benefits
### **Maintainability**
- ✅ Dedicated page component for easier maintenance
- ✅ Separation of concerns between settings types
- ✅ Consistent patterns with other settings pages
### **Extensibility**
- ✅ Easy to add new app-level settings
- ✅ Scalable layout for additional configuration options
- ✅ Consistent with existing settings architecture
### **Testing**
- ✅ All existing tests continue to pass
- ✅ TypeScript compilation successful
- ✅ Build process works correctly
- ✅ No breaking changes to existing functionality
## Conclusion
The UI improvements make filesystem settings significantly more discoverable and accessible to users. The implementation follows established patterns in the codebase, maintains complete internationalization support, and provides a much better user experience overall.
Users can now easily find and configure filesystem settings through the main Settings page, rather than having to discover them through a hidden dropdown menu in project-specific actions.
-1
View File
@@ -27,7 +27,6 @@ export default tseslint.config(
},
rules: {
...reactHooks.configs.recommended.rules,
"react-hooks/exhaustive-deps": "error",
"react-refresh/only-export-components": [
"warn",
{ allowConstantExport: true },
+30 -72
View File
@@ -65,7 +65,7 @@ All messages follow JSON-RPC 2.0 specification:
"headers": {
"Content-Type": "application/json"
},
"body": "eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9" // base64 encoded: {"name":"John","age":30}
"body": "eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9" // base64 of: {"name":"John","age":30}
}
},
"id": 124
@@ -81,7 +81,7 @@ All messages follow JSON-RPC 2.0 specification:
"Content-Type": "application/javascript",
"Cache-Control": "no-cache"
},
"body": "Y29uc29sZS5sb2coJ2hlbGxvJyk7" // base64 encoded: console.log('hello');
"body": "Y29uc29sZS5sb2coJ2hlbGxvJyk7"
},
"id": 123
}
@@ -137,28 +137,16 @@ full request body support
Request bodies must be base64-encoded strings when not null. This ensures
consistent handling of both text and binary data across the messaging protocol.
### `console`
**Purpose:** Forward console messages from iframe to parent for display
**Parameters:**
- `level` (string): Log level - "log", "warn", "error", "info", "debug"
- `message` (string): The log message
**Result:** None (notification only, no response expected)
## Implementation
### Parent Page
The parent page acts as a static file server and console log collector:
In this example, the parent page acts as a static file server.
```javascript
class FetchClientParent {
constructor(files) {
this.files = files; // Map of path -> {content, contentType}
this.consoleLogs = []; // Store console messages
this.setupMessageListener();
}
@@ -168,43 +156,12 @@ class FetchClientParent {
if (event.origin !== "https://app123.example.com") return;
const message = event.data;
// Handle fetch requests
if (message.jsonrpc === "2.0" && message.method === "fetch") {
this.handleFetch(message);
}
// Handle console messages
if (message.jsonrpc === "2.0" && message.method === "console") {
this.handleConsoleMessage(message);
}
});
}
handleConsoleMessage(message) {
const { params } = message;
const { level, message: logMessage } = params;
// Store the log message
this.consoleLogs.push({
level,
message: logMessage,
timestamp: Date.now(),
id: Date.now()
});
// Update UI to show new logs
this.updateConsoleUI();
// Also log to parent's console for debugging
console[level](`[IFRAME] ${logMessage}`);
}
updateConsoleUI() {
// Implementation depends on your UI framework
console.log(`Total console logs: ${this.consoleLogs.length}`);
}
handleFetch(request) {
const { params, id } = request;
const { request: fetchRequest } = params;
@@ -213,6 +170,9 @@ class FetchClientParent {
const url = new URL(fetchRequest.url);
const path = url.pathname;
// Decode request body if present
const requestBody = fetchRequest.body ? atob(fetchRequest.body) : null;
const file = this.files.get(path);
if (file) {
@@ -226,10 +186,11 @@ class FetchClientParent {
"Content-Type": file.contentType,
"Cache-Control": "no-cache",
},
body: btoa(file.content),
body: btoa(file.content), // base64 encode the response body
},
});
} else {
// Return 404 response (not a JSON-RPC error)
this.sendResponse({
id,
jsonrpc: "2.0",
@@ -239,7 +200,7 @@ class FetchClientParent {
headers: {
"Content-Type": "text/plain",
},
body: btoa(`File not found: ${path}`),
body: btoa(`File not found: ${path}`), // base64 encode the error message
},
});
}
@@ -249,15 +210,22 @@ class FetchClientParent {
const iframe = document.getElementById("preview-iframe");
iframe.contentWindow.postMessage(message, "https://app123.example.com");
}
sendError(message) {
const iframe = document.getElementById("preview-iframe");
iframe.contentWindow.postMessage(message, "https://app123.example.com");
}
}
```
### iframe Client Communication
### Preview Page
The iframe client uses a simplified JSON-RPC client for communication. In the actual implementation, the ServiceWorker makes requests and the main thread acts as a relay:
Below is a simplified RPC client that could be used inside the iframe's main
thread to test functionality of the parent. In practice, requests originate from
the ServiceWorker and the main thread acts as a relay, so multiple steps of
communication are involved.
```javascript
// Simplified JSON-RPC client (actual implementation in _iframe-client/main.js)
class JSONRPCClient {
constructor() {
this.requestId = 0;
@@ -268,7 +236,7 @@ class JSONRPCClient {
setupMessageListener() {
window.addEventListener("message", (event) => {
const message = event.data;
if (message.jsonrpc === "2.0" && message.id !== undefined) {
if (message.jsonrpc === "2.0" && message.id) {
this.handleResponse(message);
}
});
@@ -280,6 +248,7 @@ class JSONRPCClient {
return new Promise((resolve, reject) => {
this.pendingRequests.set(id, { resolve, reject });
// Send request to parent
window.parent.postMessage({
jsonrpc: "2.0",
method: "fetch",
@@ -287,6 +256,7 @@ class JSONRPCClient {
id,
}, "*");
// Timeout after 10 seconds
setTimeout(() => {
if (this.pendingRequests.has(id)) {
this.pendingRequests.delete(id);
@@ -305,8 +275,9 @@ class JSONRPCClient {
this.pendingRequests.delete(id);
if (error) {
pending.reject(new Error(`${error.message} (code: ${error.code})`));
pending.reject(new Error(error.message));
} else {
// Result is a serialized response
pending.resolve(result);
}
}
@@ -315,7 +286,7 @@ class JSONRPCClient {
## Base64 Encoding
All request and response bodies are base64 encoded when not null to ensure proper transmission through JSON-RPC:
All request and response bodies must be base64 encoded when not null. This ensures:
- **Consistent Data Handling:** Both text and binary data are handled uniformly
- **JSON Compatibility:** Avoids issues with special characters in JSON messages
@@ -323,16 +294,11 @@ All request and response bodies are base64 encoded when not null to ensure prope
**Encoding/Decoding:**
```javascript
// Encoding text content (parent side)
const encodedBody = btoa(textContent);
// Encoding (before sending)
const encodedBody = btoa(originalBody);
// Encoding binary content (ServiceWorker side)
const bytes = new Uint8Array(arrayBuffer);
const encodedBody = btoa(String.fromCharCode(...bytes));
// Decoding (receiver side)
const decodedText = atob(encodedBody);
const decodedBytes = new Uint8Array(atob(encodedBody).split('').map(c => c.charCodeAt(0)));
// Decoding (after receiving)
const decodedBody = atob(encodedBody);
```
## Security
@@ -358,17 +324,9 @@ const decodedBytes = new Uint8Array(atob(encodedBody).split('').map(c => c.charC
content: "<!DOCTYPE html><html><body>Hello world!</body></html>",
contentType: "text/html",
}],
["/app.js", {
content: "console.log('App loaded');",
contentType: "application/javascript",
}],
]);
// Initialize the fetch client parent
// Example static file server
new FetchClientParent(files);
</script>
```
## Console Logging Implementation
The iframe client automatically intercepts console messages and forwards them to the parent. The implementation (in `_iframe-client/main.js`) overrides console methods.
+21 -35
View File
@@ -54,31 +54,30 @@ blocked.
```
/
├── index.html # Main iframe client page
├── _iframe-client/
│ ├── main.js # Main coordination script
│ └── client.css # Styles for the iframe client
├── sw.js # ServiceWorker
├── MESSAGING_PROTOCOL.md # Communication protocol docs
└── README.md # This file
├── index.html # Main iframe client page
├── _iframe-client.js # Main coordination script
├── _iframe-client.css # Styles for the iframe client
├── sw.js # ServiceWorker
├── MESSAGING_PROTOCOL.md # Communication protocol docs
├── example-parent.html # Example parent implementation
└── README.md # This file
```
## Simplified JSON-RPC Protocol
The system now uses a simplified JSON-RPC 2.0 protocol with two methods:
The system now uses a drastically simplified JSON-RPC 2.0 protocol with only one
method:
- **`fetch(request)`** - Handle HTTP requests with serialized fetch
request/response
- **`console(level, message)`** - Forward console messages from
iframe to parent for display
**Request:**
```javascript
{
"jsonrpc": "2.0",
"method": "fetch",
"params": {
"method": "fetch",
"params": {
"request": {
"url": "https://app123.example.com/assets/main.js",
"method": "GET",
@@ -107,19 +106,6 @@ The system now uses a simplified JSON-RPC 2.0 protocol with two methods:
}
```
**Console Message:**
```javascript
{
"jsonrpc": "2.0",
"method": "console",
"params": {
"level": "error",
"message": "Failed to load module"
}
}
```
## How It Works
1. **Initialization:**
@@ -150,9 +136,8 @@ Deploy these files to your iframe client subdomain:
```
https://*.example.com/
├── index.html
├── _iframe-client/
│ ├── main.js
│ └── client.css
├── _iframe-client.js
├── _iframe-client.css
└── sw.js
```
@@ -173,7 +158,8 @@ Include the iframe client in your parent page:
</iframe>
```
Implement the JSON-RPC protocol:
Implement the JSON-RPC protocol (see `example-parent.html` for a complete
example):
```javascript
class FetchClientParent {
@@ -284,9 +270,9 @@ function handleRequest(fetchRequest) {
## Testing
1. Create a parent page implementing the JSON-RPC protocol (see example in MESSAGING_PROTOCOL.md)
2. Load the iframe client in an iframe pointing to your deployed client domain
3. The iframe client should load and display the served content
1. Open `example-parent.html` in a browser
2. Click "Load Sample Site"
3. The iframe client should load and display the sample app
4. Test navigation and functionality within the iframe client
## Browser Support
@@ -326,10 +312,10 @@ function handleRequest(fetchRequest) {
To modify the system:
1. **iframe Client:** Edit `index.html`, `_iframe-client/main.js`,
`_iframe-client/client.css`, `sw.js`
1. **iframe Client:** Edit `index.html`, `_iframe-client.js`,
`_iframe-client.css`, `sw.js`
2. **Protocol:** Update `MESSAGING_PROTOCOL.md` for any changes
3. **Testing:** Create a parent page implementing the JSON-RPC protocol for testing changes
3. **Testing:** Use `example-parent.html` for testing changes
## License
+270
View File
@@ -0,0 +1,270 @@
/**
* iframe Fetch Client Main Script
* JSON-RPC based communication with parent page
*/
class JSONRPCClient {
constructor() {
this.requestId = 0;
this.pendingRequests = new Map();
this.setupMessageListener();
}
setupMessageListener() {
window.addEventListener("message", (event) => {
const message = event.data;
if (message.jsonrpc === "2.0" && message.id !== undefined) {
// Check if this is a response to our own request or a ServiceWorker request
if (this.pendingRequests.has(message.id)) {
this.handleResponse(message);
} else {
// This is a response to a ServiceWorker request, relay it back
this.relayJSONRPCToServiceWorker(message);
}
}
});
}
relayJSONRPCToServiceWorker(response) {
// Forward the JSON-RPC response to ServiceWorker
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage(response);
}
}
async fetch(request) {
const id = ++this.requestId;
return new Promise((resolve, reject) => {
this.pendingRequests.set(id, { resolve, reject });
// Send JSON-RPC request to parent
window.parent.postMessage({
jsonrpc: "2.0",
method: "fetch",
params: { request },
id,
}, "*");
// Timeout after 10 seconds
setTimeout(() => {
if (this.pendingRequests.has(id)) {
this.pendingRequests.delete(id);
reject(new Error(`Timeout fetching: ${request.url}`));
}
}, 10000);
});
}
handleResponse(message) {
const { id, result, error } = message;
const pending = this.pendingRequests.get(id);
if (!pending) return;
this.pendingRequests.delete(id);
if (error) {
pending.reject(new Error(`${error.message} (code: ${error.code})`));
} else {
pending.resolve(result);
}
}
}
class FetchClient {
constructor() {
this.rpcClient = new JSONRPCClient();
this.swReady = false;
this.init();
}
async init() {
try {
await this.registerServiceWorker();
this.setupServiceWorkerCommunication();
await this.waitForServiceWorker();
await this.fetchSiteIndex();
} catch (error) {
this.showError("Failed to initialize fetch client", error);
}
}
async registerServiceWorker() {
if (!("serviceWorker" in navigator)) {
throw new Error("ServiceWorker not supported");
}
// Check if SW is already registered
const existingRegistration = await navigator.serviceWorker
.getRegistration();
if (existingRegistration) {
console.log("ServiceWorker already registered");
this.swReady = true;
return;
}
try {
const registration = await navigator.serviceWorker.register("/sw.js", {
scope: "/",
});
console.log("ServiceWorker registered:", registration);
// Wait for SW to be ready
await navigator.serviceWorker.ready;
this.swReady = true;
// Block future registrations to prevent site from registering its own SW
this.blockFutureRegistrations();
} catch (error) {
throw new Error(`ServiceWorker registration failed: ${error.message}`);
}
}
blockFutureRegistrations() {
navigator.serviceWorker.register = function () {
console.log("Blocked ServiceWorker registration attempt");
return Promise.resolve({
scope: "/",
active: navigator.serviceWorker.controller,
installing: null,
waiting: null,
addEventListener: () => {},
removeEventListener: () => {},
});
};
}
setupServiceWorkerCommunication() {
// Listen for JSON-RPC requests from ServiceWorker and relay them to parent
navigator.serviceWorker.addEventListener("message", async (event) => {
const { data } = event;
// Check if this is a JSON-RPC request from ServiceWorker
if (data.jsonrpc === "2.0" && data.method && data.id !== undefined) {
this.relayJSONRPCToParent(data);
}
});
}
relayJSONRPCToParent(request) {
// Forward the JSON-RPC request directly to parent
window.parent.postMessage(request, "*");
}
async waitForServiceWorker() {
const timeout = 10000; // 10 seconds
const start = Date.now();
while (!this.swReady) {
if (Date.now() - start > timeout) {
throw new Error("Timeout waiting for ServiceWorker readiness");
}
await new Promise((resolve) => setTimeout(resolve, 100));
}
console.log("ServiceWorker is ready");
}
async fetchSiteIndex() {
try {
// Request site index from parent via JSON-RPC fetch
const serializedRequest = {
url: `${location.origin}/`,
method: "GET",
body: null,
headers: {},
};
const response = await this.rpcClient.fetch(serializedRequest);
if (response.status !== 200) {
throw new Error(`Failed to fetch site index: ${response.status} ${response.statusText}`);
}
if (response.headers["Content-Type"] !== "text/html") {
throw new Error(`Unexpected Content-Type: ${response.headers["Content-Type"]}`);
}
const bytes = new Uint8Array(atob(response.body).split('').map(c => c.charCodeAt(0)));
const text = new TextDecoder().decode(bytes);
// Replace current document with the site index content
this.replaceDocument(text);
} catch (error) {
this.showError("Failed to load site index", error);
}
}
replaceDocument(htmlContent) {
// Create a new document from the HTML content
const parser = new DOMParser();
const newDoc = parser.parseFromString(htmlContent, "text/html");
const scripts = [];
newDoc.querySelectorAll("script").forEach((script) => {
scripts.push({
src: script.src,
type: script.type,
async: script.hasAttribute("async"),
defer: script.hasAttribute("defer"),
});
script.parentNode.removeChild(script);
});
// Replace the entire document
document.head.innerHTML = newDoc.head.innerHTML;
document.body.innerHTML = newDoc.body.innerHTML;
// Re-add scripts (this is necessary to execute them)
scripts.forEach((script) => {
const newScript = document.createElement("script");
newScript.src = script.src;
newScript.type = script.type;
if (script.async) newScript.async = true;
if (script.defer) newScript.defer = true;
document.body.appendChild(newScript);
});
console.log("Document replaced with site content");
}
showError(message, error) {
console.error(message, error);
document.body.innerHTML = `
<div style="
font-family: system-ui, -apple-system, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
border-left: 4px solid #dc3545;
">
<h2 style="color: #dc3545; margin-top: 0;">Fetch Client Error</h2>
<p><strong>${message}</strong></p>
<p style="color: #6c757d;">${error.message || error}</p>
<details style="margin-top: 20px;">
<summary style="cursor: pointer; color: #007bff;">Technical Details</summary>
<pre style="
background: #f1f3f4;
padding: 10px;
border-radius: 4px;
overflow-x: auto;
font-size: 12px;
margin-top: 10px;
">${error.stack || JSON.stringify(error, null, 2)}</pre>
</details>
</div>
`;
}
}
// Initialize when DOM is ready
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => new FetchClient());
} else {
new FetchClient();
}
-350
View File
@@ -1,350 +0,0 @@
/**
* iframe Fetch Client - Simplified Implementation
* Implements JSON-RPC 2.0 messaging protocol per MESSAGING_PROTOCOL.md
*/
// JSON-RPC Client for communication with parent
class JSONRPCClient {
constructor() {
this.requestId = 0;
this.pendingRequests = new Map();
this.setupMessageListener();
}
setupMessageListener() {
window.addEventListener("message", (event) => {
const message = event.data;
// Check if this is a response to our own request or a ServiceWorker request
if (message.jsonrpc === "2.0" && message.id !== undefined) {
if (this.pendingRequests.has(message.id)) {
this.handleResponse(message);
} else {
// This is a response to a ServiceWorker request, relay it back
this.relayToServiceWorker(message);
}
}
});
}
relayToServiceWorker(response) {
// Forward the JSON-RPC response to ServiceWorker
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage(response);
}
}
async fetch(request) {
const id = ++this.requestId;
return new Promise((resolve, reject) => {
this.pendingRequests.set(id, { resolve, reject });
// Send JSON-RPC request to parent
window.parent.postMessage({
jsonrpc: "2.0",
method: "fetch",
params: { request },
id,
}, "*");
// Timeout after 10 seconds
setTimeout(() => {
if (this.pendingRequests.has(id)) {
this.pendingRequests.delete(id);
reject(new Error(`Timeout fetching: ${request.url}`));
}
}, 10000);
});
}
handleResponse(message) {
const { id, result, error } = message;
const pending = this.pendingRequests.get(id);
if (!pending) return;
this.pendingRequests.delete(id);
if (error) {
pending.reject(new Error(`${error.message} (code: ${error.code})`));
} else {
pending.resolve(result);
}
}
}
// Console Interceptor - forwards console messages to parent
class ConsoleInterceptor {
constructor() {
this.originalConsole = {};
this.methods = ['log', 'warn', 'error', 'info', 'debug'];
this.init();
}
init() {
// Store original methods and override in single pass
this.methods.forEach((method) => {
if (typeof console[method] === 'function') {
this.originalConsole[method] = console[method];
console[method] = (...args) => {
// Call original method
try {
this.originalConsole[method](...args);
} catch (e) {
// Continue if original fails
}
// Send to parent
this.sendConsoleMessage(method, ...args);
};
}
});
}
sendConsoleMessage(level, ...args) {
const message = args.map((arg) => {
if (arg === undefined) return 'undefined';
if (arg === null) return 'null';
if (typeof arg === 'object') {
try {
return JSON.stringify(arg, (key, value) => {
if (value instanceof Error) {
return {
name: value.name,
message: value.message,
stack: value.stack
};
}
return value;
});
} catch {
return String(arg);
}
}
return String(arg);
}).join(' ');
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: { level, message }
}, "*");
} catch (error) {
// Retry once after delay if postMessage fails
setTimeout(() => {
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: { level: "error", message: `[DELAYED] ${message}` }
}, "*");
} catch {
// Give up if retry fails
}
}, 100);
}
}
}
// Main Fetch Client
class FetchClient {
constructor() {
this.rpcClient = new JSONRPCClient();
this.consoleInterceptor = new ConsoleInterceptor();
this.init();
}
async init() {
try {
await this.setupServiceWorker();
await this.loadSiteIndex();
} catch (error) {
this.showError("Failed to initialize fetch client", error);
}
}
async setupServiceWorker() {
if (!("serviceWorker" in navigator)) {
throw new Error("ServiceWorker not supported");
}
// Check if already registered
const existing = await navigator.serviceWorker.getRegistration();
if (existing) {
console.log("ServiceWorker already registered");
this.setupServiceWorkerCommunication();
return;
}
// Register new ServiceWorker
const registration = await navigator.serviceWorker.register("/sw.js", { scope: "/" });
console.log("ServiceWorker registered:", registration);
await navigator.serviceWorker.ready;
this.setupServiceWorkerCommunication();
this.blockFutureRegistrations(); // Block future registrations to prevent site from registering its own SW
}
setupServiceWorkerCommunication() {
// Relay JSON-RPC requests from ServiceWorker to parent
navigator.serviceWorker.addEventListener("message", (event) => {
const { data } = event;
if (data.jsonrpc === "2.0" && data.method && data.id !== undefined) {
window.parent.postMessage(data, "*");
}
});
}
blockFutureRegistrations() {
navigator.serviceWorker.register = () => {
console.log("Blocked ServiceWorker registration attempt");
return Promise.resolve({
scope: "/",
active: navigator.serviceWorker.controller,
installing: null,
waiting: null,
addEventListener: () => {},
removeEventListener: () => {},
});
};
}
async loadSiteIndex() {
const serializedRequest = {
url: `${location.origin}/`,
method: "GET",
body: null,
headers: {},
};
const response = await this.rpcClient.fetch(serializedRequest);
if (response?.status !== 200) {
throw new Error(`Failed to fetch site index: ${response?.status || 'Invalid response from site: ' + response} ${response?.statusText || ''}`);
}
if (response.headers["Content-Type"] !== "text/html") {
throw new Error(`Unexpected Content-Type: ${response.headers["Content-Type"]}`);
}
const bytes = new Uint8Array(atob(response.body).split('').map(c => c.charCodeAt(0)));
const text = new TextDecoder().decode(bytes);
this.replaceDocument(text);
}
replaceDocument(htmlContent) {
// Create a new document from the HTML content
const parser = new DOMParser();
const newDoc = parser.parseFromString(htmlContent, "text/html");
// Extract scripts for re-execution
const scripts = [];
newDoc.querySelectorAll("script").forEach((script) => {
scripts.push({
src: script.src,
type: script.type,
async: script.hasAttribute("async"),
defer: script.hasAttribute("defer"),
});
script.remove();
});
// Replace document content
document.head.innerHTML = newDoc.head.innerHTML;
document.body.innerHTML = newDoc.body.innerHTML;
// Re-add scripts to execute them
scripts.forEach((script) => {
const newScript = document.createElement("script");
newScript.src = script.src;
newScript.type = script.type;
if (script.async) newScript.async = true;
if (script.defer) newScript.defer = true;
document.body.appendChild(newScript);
});
console.log("Document replaced with site content");
}
showError(message, error) {
console.error(message, error);
document.body.innerHTML = `
<div style="
font-family: system-ui, -apple-system, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
border-left: 4px solid #dc3545;
">
<h2 style="color: #dc3545; margin-top: 0;">Fetch Client Error</h2>
<p><strong>${message}</strong></p>
<p style="color: #6c757d;">${error.message || error}</p>
<details style="margin-top: 20px;">
<summary style="cursor: pointer; color: #007bff;">Technical Details</summary>
<pre style="
background: #f1f3f4;
padding: 10px;
border-radius: 4px;
overflow-x: auto;
font-size: 12px;
margin-top: 10px;
">${error.stack || JSON.stringify(error, null, 2)}</pre>
</details>
</div>
`;
}
}
// Global error handlers
const setupGlobalErrorHandlers = () => {
window.addEventListener('error', (event) => {
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: {
level: "error",
message: `Uncaught Error: ${event.message}`,
source: event.filename,
lineno: event.lineno,
colno: event.colno,
stack: event.error?.stack
}
}, "*");
} catch {
// Ignore postMessage errors
}
});
window.addEventListener('unhandledrejection', (event) => {
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: {
level: "error",
message: "Unhandled Promise Rejection",
reason: event.reason,
promise: event.promise ? 'Promise object' : 'No promise object'
}
}, "*");
} catch {
// Ignore postMessage errors
}
});
};
// Initialize
setupGlobalErrorHandlers();
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => new FetchClient());
} else {
new FetchClient();
}
+2 -2
View File
@@ -4,7 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Site Preview</title>
<link rel="stylesheet" href="/_iframe-client/client.css">
<link rel="stylesheet" href="/_iframe-client.css">
</head>
<body>
<div class="loading">
@@ -12,6 +12,6 @@
<p>Loading preview...</p>
<p><small>Waiting for ServiceWorker and parent communication</small></p>
</div>
<script type="module" src="/_iframe-client/main.js"></script>
<script src="/_iframe-client.js"></script>
</body>
</html>
+815 -221
View File
File diff suppressed because it is too large. Load diff
+6 -9
View File
@@ -6,14 +6,10 @@
"scripts": {
"dev": "npm i --silent && vite",
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
"typecheck": "npm i --silent && tsc --noEmit",
"test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'",
"test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'",
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
},
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^6.0.1",
"@hookform/resolvers": "^3.9.0",
@@ -48,7 +44,9 @@
"@radix-ui/react-toggle": "^1.1.0",
"@radix-ui/react-toggle-group": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.4",
"@soapbox.pub/streamdown": "^1.0.11",
"@std/encoding": "npm:@jsr/std__encoding@^1.0.10",
"@std/path": "npm:@jsr/std__path@^1.1.1",
"@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
@@ -59,7 +57,6 @@
"decimal.js": "^10.6.0",
"embla-carousel-react": "^8.3.0",
"esbuild-wasm": "^0.25.8",
"i18next": "^25.5.2",
"ignore": "^7.0.5",
"input-otp": "^1.2.4",
"isomorphic-git": "^1.32.1",
@@ -73,13 +70,13 @@
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.53.0",
"react-i18next": "^15.7.3",
"react-markdown": "^10.1.0",
"react-resizable-panels": "^3.0.3",
"react-router-dom": "^6.26.2",
"react-syntax-highlighter": "^15.6.1",
"recharts": "^2.12.7",
"remark-gfm": "^4.0.1",
"streamdown": "~1.0.0",
"streamdown": "^1.0.12",
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"turndown": "^7.2.1",
@@ -99,9 +96,9 @@
"@types/jszip": "^3.4.0",
"@types/node": "^22.5.5",
"@types/path-browserify": "^1.0.3",
"@types/qrcode": "^1.5.5",
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@types/react-syntax-highlighter": "^15.5.13",
"@types/turndown": "^5.0.5",
"@vitejs/plugin-react-swc": "^3.5.0",
"autoprefixer": "^10.4.20",
-661
View File
@@ -1,661 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<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/>.
+10 -115
View File
@@ -4,7 +4,7 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createHead, UnheadProvider } from '@unhead/react/client';
import { InferSeoMetaPlugin } from '@unhead/addons';
import { Suspense, useEffect, useState } from 'react';
import { Suspense, useEffect } from 'react';
import LightningFS from '@isomorphic-git/lightning-fs';
import NostrProvider from '@/components/NostrProvider';
import { Toaster } from "@/components/ui/toaster";
@@ -17,11 +17,7 @@ import { GitSettingsProvider } from '@/components/GitSettingsProvider';
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
import { FSProvider } from '@/components/FSProvider';
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
import { OPFSAdapterSimple } from '@/lib/OPFSAdapterSimple';
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import { useAppContext } from '@/hooks/useAppContext';
import { useFS } from '@/hooks/useFS';
import AppRouter from './AppRouter';
@@ -45,7 +41,6 @@ const defaultConfig: AppConfig = {
theme: "light",
relayUrl: "wss://relay.primal.net",
deployServer: "shakespeare.wtf",
filesystemType: "lightningfs",
};
const presetRelays = [
@@ -55,118 +50,18 @@ const presetRelays = [
{ url: 'wss://relay.primal.net', name: 'Primal' },
];
// Component to handle filesystem initialization and cleanup
function FilesystemProvider({ children }: { children: React.ReactNode }) {
const { config } = useAppContext();
const [fs, setFS] = useState<JSRuntimeFS | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const initializeFilesystem = async () => {
try {
let filesystem: JSRuntimeFS;
if (config.filesystemType === 'opfs') {
// Check if OPFS is available
if (!('storage' in navigator) || typeof (navigator.storage as unknown as { getDirectory: () => Promise<FileSystemDirectoryHandle> }).getDirectory !== 'function') {
throw new Error('OPFS is not supported in this browser');
}
console.log('Initializing OPFS filesystem...');
filesystem = new OPFSAdapterSimple({ debug: true });
// Test basic filesystem operations to ensure OPFS works correctly
try {
await filesystem.mkdir('/test-opfs', { recursive: true });
await filesystem.writeFile('/test-opfs/test.txt', 'test');
const testContent = await filesystem.readFile('/test-opfs/test.txt', 'utf8');
if (testContent !== 'test') {
throw new Error('OPFS test failed: content mismatch');
}
await filesystem.unlink('/test-opfs/test.txt');
await filesystem.rmdir('/test-opfs');
console.log('OPFS filesystem test passed');
} catch (testError) {
console.warn('OPFS filesystem test failed:', testError);
throw new Error(`OPFS filesystem test failed: ${testError}`);
}
} else {
// Default to LightningFS
console.log('Initializing LightningFS filesystem...');
const lightningFS = new LightningFS('shakespeare-fs');
filesystem = new LightningFSAdapter(lightningFS.promises);
}
setFS(filesystem);
setError(null);
console.log(`Successfully initialized ${config.filesystemType === 'opfs' ? 'OPFS' : 'LightningFS'} filesystem`);
} catch (err) {
console.error('Failed to initialize filesystem:', err);
const errorMessage = err instanceof Error ? err.message : 'Failed to initialize filesystem';
// Fallback to LightningFS if OPFS fails
if (config.filesystemType === 'opfs') {
console.warn('OPFS initialization failed, falling back to LightningFS...');
try {
const lightningFS = new LightningFS('shakespeare-fs');
const fallbackFs = new LightningFSAdapter(lightningFS.promises);
setFS(fallbackFs);
setError(null);
console.log('Successfully fell back to LightningFS');
} catch (fallbackErr) {
console.error('LightningFS fallback also failed:', fallbackErr);
setError(`Failed to initialize both OPFS and LightningFS: ${errorMessage}; Fallback error: ${fallbackErr}`);
}
} else {
setError(errorMessage);
}
}
};
initializeFilesystem();
}, [config.filesystemType]);
if (error) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center space-y-4">
<h1 className="text-2xl font-bold text-red-600">Filesystem Error</h1>
<p className="text-muted-foreground">{error}</p>
<p className="text-sm text-muted-foreground">
Please try refreshing the page or using a different browser.
If the problem persists, you may need to clear browser data and try again.
</p>
</div>
</div>
);
}
if (!fs) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center space-y-4">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
<p className="text-muted-foreground">Initializing filesystem...</p>
</div>
</div>
);
}
return <FSProvider fs={fs}>{children}</FSProvider>;
}
// Initialize LightningFS
const lightningFS = new LightningFS('shakespeare-fs');
const fs = new LightningFSAdapter(lightningFS.promises);
// Component to handle filesystem cleanup on startup
// Automatically removes files older than 1 hour from /tmp directory
function FSCleanupHandler() {
const { fs } = useFS();
useEffect(() => {
if (fs) {
// Run cleanup on application startup to remove stale temporary files
// This helps prevent the VFS from accumulating old files over time
cleanupTmpDirectory(fs).catch(console.error);
}
}, [fs]);
// Run cleanup on application startup to remove stale temporary files
// This helps prevent the VFS from accumulating old files over time
cleanupTmpDirectory(fs).catch(console.error);
}, []);
return null;
}
@@ -176,7 +71,7 @@ export function App() {
<UnheadProvider head={head}>
<QueryClientProvider client={queryClient}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
<FilesystemProvider>
<FSProvider fs={fs}>
<FSCleanupHandler />
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
@@ -194,7 +89,7 @@ export function App() {
</AISettingsProvider>
</NostrProvider>
</NostrLoginProvider>
</FilesystemProvider>
</FSProvider>
</AppProvider>
</QueryClientProvider>
</UnheadProvider>
-8
View File
@@ -5,13 +5,9 @@ import { SessionMonitor } from "./components/SessionMonitor";
import Index from "./pages/Index";
import Clone from "./pages/Clone";
import Settings from "./pages/Settings";
import Preferences from "./pages/Preferences";
import NostrSettings from "./pages/NostrSettings";
import AISettings from "./pages/AISettings";
import GitSettings from "./pages/GitSettings";
import DataSettings from "./pages/DataSettings";
import AboutSettings from "./pages/AboutSettings";
import GitHubOAuth from "./pages/GitHubOAuth";
import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound";
import { ProjectView } from "./pages/ProjectView";
@@ -25,15 +21,11 @@ export function AppRouter() {
<Routes>
<Route path="/" element={<Index />} />
<Route path="/clone" element={<Clone />} />
<Route path="/oauth/github" element={<GitHubOAuth />} />
<Route path="/settings" element={<SettingsLayout />}>
<Route index element={<Settings />} />
<Route path="preferences" element={<Preferences />} />
<Route path="nostr" element={<NostrSettings />} />
<Route path="ai" element={<AISettings />} />
<Route path="git" element={<GitSettings />} />
<Route path="data" element={<DataSettings />} />
<Route path="about" element={<AboutSettings />} />
</Route>
<Route path="/project/:projectId" element={<ProjectView />} />
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
+2 -51
View File
@@ -1,33 +1,23 @@
import { memo, useState } from 'react';
import { Streamdown } from 'streamdown';
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2 } from 'lucide-react';
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle } from 'lucide-react';
import type { AIMessage } from '@/lib/SessionManager';
import { cn } from '@/lib/utils';
import { UserMessage } from '@/components/UserMessage';
import OpenAI from 'openai';
import { useTheme } from '@/hooks/useTheme';
// Type guard to check if message has reasoning content
function hasReasoningContent(message: AIMessage): message is AIMessage & { reasoning_content: string } {
return message.role === 'assistant' && 'reasoning_content' in message && typeof (message as { reasoning_content?: unknown }).reasoning_content === 'string';
}
interface AIMessageItemProps {
message: AIMessage;
isCurrentlyLoading?: boolean;
toolCall?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined; // Tool call data passed from the assistant message
reasoningContent?: string; // Reasoning content for streaming messages
}
export const AIMessageItem = memo(({
message,
isCurrentlyLoading = false,
toolCall,
reasoningContent
toolCall
}: AIMessageItemProps) => {
const [isToolExpanded, setIsToolExpanded] = useState(false);
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
const { displayTheme } = useTheme();
// Get content to display
const getContent = () => {
@@ -238,49 +228,10 @@ export const AIMessageItem = memo(({
<div className="flex">
<div className="flex-1 min-w-0">
<div className="text-sm">
{/* Reasoning content display */}
{((reasoningContent && reasoningContent.trim()) ||
(hasReasoningContent(message) && message.reasoning_content.trim()) ||
(reasoningContent !== undefined && !getContent().trim() && isCurrentlyLoading)) && (
<div className="mb-3">
<button
onClick={() => setIsReasoningExpanded(!isReasoningExpanded)}
className={cn(
"w-full flex items-center gap-2 px-2 py-1 text-xs",
"hover:bg-muted/30 rounded transition-colors duration-200"
)}
>
{reasoningContent !== undefined && !getContent().trim() && isCurrentlyLoading ? (
<Loader2 className="h-3 w-3 text-muted-foreground flex-shrink-0 animate-spin" />
) : (
<Lightbulb className="h-3 w-3 text-muted-foreground flex-shrink-0" />
)}
<span className="text-muted-foreground font-medium flex-1 text-left">
Thinking
</span>
</button>
{isReasoningExpanded && (reasoningContent?.trim() || (hasReasoningContent(message) && message.reasoning_content.trim())) && (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
<div className="whitespace-pre-wrap break-words">
<Streamdown
className='size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0'
parseIncompleteMarkdown={isCurrentlyLoading}
shikiTheme={displayTheme === 'dark' ? 'github-dark' : 'github-light'}
>
{reasoningContent || (hasReasoningContent(message) ? message.reasoning_content : '') || ''}
</Streamdown>
</div>
</div>
)}
</div>
)}
<div className="break-words">
<Streamdown
className='size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0'
parseIncompleteMarkdown={isCurrentlyLoading}
shikiTheme={displayTheme === 'dark' ? 'github-dark' : 'github-light'}
>
{getContent()}
</Streamdown>
+7 -9
View File
@@ -31,7 +31,7 @@ describe('AISettingsProvider', () => {
// Mock the read function to return default settings
const { readAISettings } = await import('@/lib/configUtils');
vi.mocked(readAISettings).mockResolvedValue({
providers: [],
providers: {},
recentlyUsedModels: [],
});
});
@@ -122,13 +122,12 @@ describe('AISettingsProvider', () => {
it('should migrate old settings without recentlyUsedModels', async () => {
const oldSettings = {
providers: [
{
id: 'openrouter',
providers: {
openrouter: {
baseURL: 'https://openrouter.ai/api/v1',
apiKey: 'test-key'
}
],
},
recentlyUsedModels: []
};
@@ -170,13 +169,12 @@ describe('AISettingsProvider', () => {
act(() => {
result.current.updateSettings({
providers: [
{
id: 'test-provider',
providers: {
'test-provider': {
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key'
}
]
}
});
});
+29 -31
View File
@@ -1,6 +1,6 @@
import { useQueryClient } from '@tanstack/react-query';
import { ReactNode, useState, useEffect } from 'react';
import { AISettingsContext, type AISettings, type AIProvider, type AISettingsContextType } from '@/contexts/AISettingsContext';
import { AISettingsContext, type AISettings, type AIConnection, type AISettingsContextType } from '@/contexts/AISettingsContext';
import { useFS } from '@/hooks/useFS';
import { readAISettings, writeAISettings } from '@/lib/configUtils';
@@ -9,7 +9,7 @@ interface AISettingsProviderProps {
}
const DEFAULT_SETTINGS: AISettings = {
providers: [],
providers: {},
recentlyUsedModels: [],
};
@@ -60,40 +60,38 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
}
};
const setProvider = (provider: AIProvider) => {
setSettings(prev => {
const existingIndex = prev.providers.findIndex(p => p.id === provider.id);
if (existingIndex >= 0) {
// Update existing provider
return {
...prev,
providers: prev.providers.map(p =>
p.id === provider.id ? provider : p
),
};
} else {
// Add new provider
return {
...prev,
providers: [...prev.providers, provider],
};
}
});
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
};
const removeProvider = (id: string) => {
const addProvider = (name: string, connection: AIConnection) => {
setSettings(prev => ({
...prev,
providers: prev.providers.filter(provider => provider.id !== id),
providers: {
...prev.providers,
[name]: connection,
},
}));
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
};
const setProviders = (providers: AIProvider[]) => {
const removeProvider = (name: string) => {
setSettings(prev => {
const { [name]: removed, ...rest } = prev.providers;
return {
...prev,
providers: rest,
};
});
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
};
const updateProvider = (name: string, connection: Partial<AIConnection>) => {
setSettings(prev => ({
...prev,
providers,
providers: {
...prev.providers,
[name]: {
...prev.providers[name],
...connection,
},
},
}));
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
};
@@ -122,14 +120,14 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
});
};
const isConfigured = settings.providers.length > 0;
const isConfigured = Object.entries(settings.providers).length > 0;
const contextValue: AISettingsContextType = {
settings,
updateSettings,
setProvider,
addProvider,
removeProvider,
setProviders,
updateProvider,
addRecentlyUsedModel,
isConfigured,
};
+13 -3
View File
@@ -27,11 +27,12 @@ import {
GitBranch,
Download,
Trash2,
Settings,
GitMerge,
} from 'lucide-react';
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
import { GitDialog } from '@/components/GitDialog';
import { AppSettingsDialog } from '@/components/AppSettingsDialog';
import { useNavigate } from 'react-router-dom';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useToast } from '@/hooks/useToast';
@@ -74,8 +75,8 @@ export function ActionsMenu({
const navigate = useNavigate();
const projectsManager = useProjectsManager();
const { toast } = useToast();
const git = useGit();
const { fs } = useFS();
const { git } = useGit();
const isAnyLoading = isLoading || isBuildLoading || isDeployLoading || isDeleting || isExporting;
@@ -233,7 +234,16 @@ export function ActionsMenu({
Git History
</DropdownMenuItem>
<AppSettingsDialog>
<DropdownMenuItem
disabled={isAnyLoading}
className="gap-2"
onSelect={(e) => e.preventDefault()}
>
<Settings className="h-4 w-4" />
Settings
</DropdownMenuItem>
</AppSettingsDialog>
<DropdownMenuItem
onClick={handleExportProject}
+6 -6
View File
@@ -4,7 +4,7 @@ import { type Project } from '@/lib/ProjectsManager';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { ProjectSidebar } from '@/components/ProjectSidebar';
import { Button } from '@/components/ui/button';
import { Menu } from 'lucide-react';
import { Menu, Columns2 } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
interface AppLayoutProps {
@@ -108,7 +108,6 @@ export function AppLayout({
setIsSidebarVisible(false); // Always collapse sidebar on mobile navigation
handleProjectSelect(project);
}}
onClose={() => setIsSidebarVisible(false)}
/>
</div>
</div>
@@ -130,7 +129,8 @@ export function AppLayout({
selectedProject={selectedProject}
onSelectProject={handleProjectSelect}
className="h-screen sticky top-0"
onToggleSidebar={() => setIsSidebarVisible(false)}
showCollapseButton={true}
onCollapse={() => setIsSidebarVisible(false)}
/>
</div>
)}
@@ -138,16 +138,16 @@ export function AppLayout({
{/* Main Content Area */}
<div className="flex-1 flex flex-col bg-background">
<div className="min-h-screen bg-gradient-to-br from-primary/5 to-accent/5 relative">
{/* Show open button when sidebar is collapsed */}
{/* Toggle Button - only show when sidebar is collapsed */}
{showSidebar && !isSidebarVisible && (
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(true)}
className="absolute top-2 left-4 h-8 w-8 p-0 z-10 bg-transparent backdrop-blur-sm hover:bg-transparent text-foreground/70 hover:text-foreground"
aria-label="Open sidebar"
aria-label="Toggle sidebar"
>
<Menu className="h-4 w-4" />
<Columns2 className="h-4 w-4" />
</Button>
)}
-15
View File
@@ -2,7 +2,6 @@ import { ReactNode, useEffect } from 'react';
import { z } from 'zod';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext';
import i18n from '@/lib/i18n';
interface AppProviderProps {
children: ReactNode;
@@ -19,8 +18,6 @@ const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
theme: z.enum(['dark', 'light', 'system']),
relayUrl: z.string().url(),
deployServer: z.string().min(1),
language: z.string().optional(),
filesystemType: z.enum(['lightningfs', 'opfs']),
});
export function AppProvider(props: AppProviderProps) {
@@ -58,9 +55,6 @@ export function AppProvider(props: AppProviderProps) {
// Apply theme effects to document
useApplyTheme(config.theme);
// Apply language effects to i18n
useApplyLanguage(config.language);
return (
<AppContext.Provider value={appContextValue}>
{children}
@@ -107,13 +101,4 @@ function useApplyTheme(theme: Theme) {
mediaQuery.addEventListener('change', handleChange);
return () => mediaQuery.removeEventListener('change', handleChange);
}, [theme]);
}
/**
* Hook to apply language changes to i18n
*/
function useApplyLanguage(language?: string): void {
useEffect(() => {
i18n.changeLanguage(language ?? navigator.language);
}, [language]);
}
+3 -102
View File
@@ -1,11 +1,10 @@
import { useState, useEffect } from 'react';
import { Settings, Save, Database, AlertTriangle } from 'lucide-react';
import { useState } from 'react';
import { Settings, Save } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { useAppContext } from '@/hooks/useAppContext';
import { useToast } from '@/hooks/useToast';
@@ -18,18 +17,6 @@ export function AppSettingsDialog({ children }: AppSettingsDialogProps) {
const { toast } = useToast();
const [open, setOpen] = useState(false);
const [deployServer, setDeployServer] = useState(config.deployServer);
const [filesystemType, setFilesystemType] = useState(config.filesystemType);
const [opfsAvailable, setOpfsAvailable] = useState(false);
// Check OPFS availability on mount
useEffect(() => {
const checkOPFSAvailability = () => {
const available = 'storage' in navigator && !!((navigator.storage as unknown as { getDirectory: () => FileSystemDirectoryHandle }).getDirectory);
setOpfsAvailable(available);
};
checkOPFSAvailability();
}, []);
const handleSave = () => {
// Validate deploy server
@@ -42,42 +29,25 @@ export function AppSettingsDialog({ children }: AppSettingsDialogProps) {
return;
}
// Validate filesystem type
if (filesystemType === 'opfs' && !opfsAvailable) {
toast({
title: "OPFS not available",
description: "OPFS is not supported in your browser. Please use LightningFS instead.",
variant: "destructive",
});
return;
}
// Remove protocol if present
const cleanDeployServer = deployServer.replace(/^https?:\/\//, '');
updateConfig((current) => ({
...current,
deployServer: cleanDeployServer,
filesystemType,
}));
toast({
title: "Settings saved",
description: "Your settings have been updated. The page will refresh to apply the new filesystem.",
description: "Your deployment settings have been updated.",
});
// Refresh the page to apply filesystem changes
setTimeout(() => {
window.location.reload();
}, 1000);
setOpen(false);
};
const handleCancel = () => {
// Reset to current config
setDeployServer(config.deployServer);
setFilesystemType(config.filesystemType);
setOpen(false);
};
@@ -100,75 +70,6 @@ export function AppSettingsDialog({ children }: AppSettingsDialogProps) {
</DialogHeader>
<div className="space-y-6">
{/* Filesystem Settings */}
<Card>
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<Database className="h-5 w-5" />
Filesystem
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label>Filesystem Type</Label>
<RadioGroup
value={filesystemType}
onValueChange={(value) => setFilesystemType(value as 'lightningfs' | 'opfs')}
className="grid grid-cols-1 gap-3"
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="lightningfs" id="lightningfs" />
<Label htmlFor="lightningfs" className="cursor-pointer">
<div className="flex flex-col">
<span className="font-medium">LightningFS (IndexedDB)</span>
<span className="text-sm text-muted-foreground">
Uses IndexedDB for storage. Works in all modern browsers.
</span>
</div>
</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem
value="opfs"
id="opfs"
disabled={!opfsAvailable}
/>
<Label htmlFor="opfs" className={`cursor-pointer ${!opfsAvailable ? 'opacity-50' : ''}`}>
<div className="flex flex-col">
<span className="font-medium flex items-center gap-2">
OPFS (Origin Private File System)
{!opfsAvailable && (
<AlertTriangle className="h-4 w-4 text-orange-500" />
)}
</span>
<span className="text-sm text-muted-foreground">
{opfsAvailable
? "Modern browser API with better performance and larger storage limits."
: "Not available in this browser. Use Chrome, Edge, or Firefox 111+."
}
</span>
</div>
</Label>
</div>
</RadioGroup>
</div>
{!opfsAvailable && filesystemType === 'opfs' && (
<div className="flex items-center gap-2 p-3 bg-orange-50 dark:bg-orange-950/20 rounded-md border border-orange-200 dark:border-orange-800">
<AlertTriangle className="h-4 w-4 text-orange-600 dark:text-orange-400" />
<span className="text-sm text-orange-800 dark:text-orange-200">
OPFS is not available in your browser. Please use LightningFS or upgrade to a modern browser.
</span>
</div>
)}
<div className="text-xs text-muted-foreground">
<p><strong>Note:</strong> Changing the filesystem type will refresh the page and may cause data loss if not properly exported first.</p>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg">Deployment</CardTitle>
-85
View File
@@ -1,85 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { CreditsBadge } from './CreditsBadge';
// Mock the useAICredits hook
vi.mock('@/hooks/useAICredits', () => ({
useAICredits: () => ({
data: { amount: 10.50 },
isLoading: false,
error: null,
}),
}));
// Mock the fetch function
global.fetch = vi.fn();
const mockConnection = {
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
};
describe('CreditsBadge', () => {
it('renders the credits amount', () => {
render(
<TestApp>
<CreditsBadge
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
expect(screen.getByText('$10.50')).toBeInTheDocument();
});
it('calls onOpenDialog when badge is clicked', () => {
const mockCallback = vi.fn();
render(
<TestApp>
<CreditsBadge
providerId="test-provider"
connection={mockConnection}
onOpenDialog={mockCallback}
/>
</TestApp>
);
const badge = screen.getByText('$10.50');
fireEvent.click(badge);
expect(mockCallback).toHaveBeenCalled();
});
it('has proper styling for clickable badge', () => {
render(
<TestApp>
<CreditsBadge
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
const badge = screen.getByText('$10.50');
expect(badge).toHaveClass('cursor-pointer');
expect(badge).toHaveClass('hover:bg-secondary/80');
});
it('does not render dialog directly', () => {
render(
<TestApp>
<CreditsBadge
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
// Dialog should not be rendered by CreditsBadge itself
expect(screen.queryByText('Credits - test-provider')).not.toBeInTheDocument();
});
});
-51
View File
@@ -1,51 +0,0 @@
import { Badge } from '@/components/ui/badge';
import { useAICredits } from '@/hooks/useAICredits';
interface CreditsBadgeProps {
providerId: string;
connection: {
baseURL: string;
apiKey?: string;
nostr?: boolean;
};
className?: string;
onOpenDialog?: () => void;
}
/**
* Displays a clickable credits badge showing the remaining credits for an AI provider
*/
export function CreditsBadge({ providerId, connection, className, onOpenDialog }: CreditsBadgeProps) {
const { data: credits, isLoading, error } = useAICredits(providerId, connection);
// Don't render anything if there's an error (provider doesn't support credits endpoint)
if (error || isLoading) {
return null;
}
// Don't render if no credits data is available
if (!credits) {
return null;
}
// Format the amount as currency
const formattedAmount = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(credits.amount);
return (
<Badge
variant="secondary"
className={`cursor-pointer hover:bg-secondary/80 transition-colors ${className}`}
onClick={(e) => {
e.stopPropagation();
onOpenDialog?.();
}}
>
{formattedAmount}
</Badge>
);
}
-112
View File
@@ -1,112 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { CreditsDialog } from './CreditsDialog';
// Mock the fetch function
global.fetch = vi.fn();
const mockConnection = {
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
};
describe('CreditsDialog', () => {
it('renders dialog when open', () => {
render(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
expect(screen.getByText('Credits')).toBeInTheDocument();
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
expect(screen.getByText('Recent Transactions')).toBeInTheDocument();
});
it('does not render when closed', () => {
render(
<TestApp>
<CreditsDialog
open={false}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
expect(screen.queryByText('Credits')).not.toBeInTheDocument();
});
it('shows payment method options', () => {
render(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
expect(screen.getByText('Payment Method')).toBeInTheDocument();
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
});
it('shows preset amount buttons', () => {
render(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
expect(screen.getByText('$5')).toBeInTheDocument();
expect(screen.getByText('$10')).toBeInTheDocument();
expect(screen.getByText('$25')).toBeInTheDocument();
expect(screen.getByText('$50')).toBeInTheDocument();
expect(screen.getByText('$100')).toBeInTheDocument();
});
it('calls onDialogStateChange callback when dialog state changes', () => {
const mockCallback = vi.fn();
const { rerender } = render(
<TestApp>
<CreditsDialog
open={false}
onOpenChange={mockCallback}
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
// Simulate opening the dialog
rerender(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={mockCallback}
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
expect(screen.getByText('Credits')).toBeInTheDocument();
});
});
-607
View File
@@ -1,607 +0,0 @@
import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import QRCode from 'qrcode';
import { CreditCard, Zap, ExternalLink, RefreshCw, Check, X, Clock, AlertCircle, Copy, RotateCcw, ArrowLeft } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Skeleton } from '@/components/ui/skeleton';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useToast } from '@/hooks/useToast';
import { createAIClient } from '@/lib/ai-client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
interface CreditsDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
providerId: string;
connection: {
baseURL: string;
apiKey?: string;
nostr?: boolean;
};
}
interface Payment {
object: 'payment';
id: string;
status: 'pending' | 'completed' | 'failed' | 'expired';
amount: number;
fee: number;
total: number;
method: 'stripe' | 'lightning';
description: string;
url: string;
created_at: number;
completed_at?: number;
expires_at: number;
}
interface PaymentsResponse {
object: 'list';
data: Payment[];
has_more: boolean;
url: string;
}
interface AddCreditsRequest {
amount: number;
method: 'stripe' | 'lightning';
redirect_url?: string;
}
const PRESET_AMOUNTS = [5, 10, 25, 50, 100];
interface LightningPaymentProps {
invoice: string;
amount: number;
onClose: () => void;
}
function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) {
const [qrDataUrl, setQrDataUrl] = useState<string>('');
const [isWebLNAvailable, setIsWebLNAvailable] = useState(false);
const [isPayingWithWebLN, setIsPayingWithWebLN] = useState(false);
const [showCopiedTooltip, setShowCopiedTooltip] = useState(false);
const { toast } = useToast();
useEffect(() => {
// Generate QR code
QRCode.toDataURL(invoice, {
width: 256,
margin: 2,
color: {
dark: '#000000',
light: '#ffffff',
},
})
.then(setQrDataUrl)
.catch(console.error);
// Check for WebLN availability
setIsWebLNAvailable(typeof window !== 'undefined' && 'webln' in window);
}, [invoice]);
const handleWebLNPay = async () => {
if (!window.webln) return;
try {
setIsPayingWithWebLN(true);
await window.webln.enable();
await window.webln.sendPayment(invoice);
toast({
title: 'Payment sent!',
description: 'Your Lightning payment has been sent successfully.',
});
onClose();
} catch (error) {
console.error('WebLN payment failed:', error);
toast({
title: 'Payment failed',
description: error instanceof Error ? error.message : 'Failed to send Lightning payment',
variant: 'destructive',
});
} finally {
setIsPayingWithWebLN(false);
}
};
const handleCopyInvoice = () => {
navigator.clipboard.writeText(invoice);
setShowCopiedTooltip(true);
setTimeout(() => setShowCopiedTooltip(false), 2000);
};
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(amount);
};
return (
<div className="space-y-4">
<div className="text-center">
<h3 className="text-lg font-semibold mb-2">Lightning Payment</h3>
<p className="text-sm text-muted-foreground">
Pay {formatCurrency(amount)} with Lightning Network
</p>
</div>
{/* QR Code */}
<div className="flex justify-center">
{qrDataUrl ? (
<div className="p-4 bg-white rounded-lg border">
<img src={qrDataUrl} alt="Lightning Invoice QR Code" className="w-48 h-48" />
</div>
) : (
<div className="w-48 h-48 bg-muted rounded-lg flex items-center justify-center">
<RefreshCw className="h-6 w-6 animate-spin" />
</div>
)}
</div>
{/* Payment Buttons */}
<div className="space-y-2">
{isWebLNAvailable && (
<Button
onClick={handleWebLNPay}
disabled={isPayingWithWebLN}
className="w-full"
size="lg"
>
{isPayingWithWebLN && <RefreshCw className="h-4 w-4 mr-2 animate-spin" />}
<Zap className="h-4 w-4 mr-2" />
Pay with WebLN
</Button>
)}
<div className="relative">
<Button
variant="outline"
onClick={handleCopyInvoice}
className="w-full"
size="lg"
>
<Copy className="h-4 w-4 mr-2" />
Copy Invoice
</Button>
{showCopiedTooltip && (
<div className="absolute -top-10 left-1/2 transform -translate-x-1/2 bg-foreground text-background text-xs px-2 py-1 rounded shadow-lg z-10 animate-in fade-in-0 duration-200">
Copied!
<div className="absolute top-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent border-t-foreground"></div>
</div>
)}
</div>
</div>
</div>
);
}
export function CreditsDialog({ open, onOpenChange, providerId, connection }: CreditsDialogProps) {
const { user } = useCurrentUser();
const { toast } = useToast();
const queryClient = useQueryClient();
const [amount, setAmount] = useState<number>(10);
const [paymentMethod, setPaymentMethod] = useState<'stripe' | 'lightning'>('stripe');
const [lightningInvoice, setLightningInvoice] = useState<string | null>(null);
const [refreshingPayments, setRefreshingPayments] = useState<Set<string>>(new Set());
// Query for payment history
const { data: payments, isLoading: isLoadingPayments } = useQuery({
queryKey: ['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId],
queryFn: async (): Promise<Payment[]> => {
const ai = createAIClient(connection, user);
const data = await ai.get('/credits/payments?limit=50') as PaymentsResponse;
return data.data;
},
enabled: open,
retry: false,
refetchOnWindowFocus: false,
});
// Mutation for adding credits
const addCreditsMutation = useMutation({
mutationFn: async (request: AddCreditsRequest): Promise<Payment> => {
const ai = createAIClient(connection, user);
return await ai.post('/credits/add', {
body: request,
}) as Payment;
},
onSuccess: (payment) => {
if (payment.method === 'stripe') {
// Open Stripe checkout in new window
window.open(payment.url, '_blank');
toast({
title: 'Payment initiated',
description: 'Stripe checkout opened in a new window.',
});
} else if (payment.method === 'lightning') {
// Show Lightning payment interface
setLightningInvoice(payment.url);
}
// Refresh payments list
queryClient.invalidateQueries({
queryKey: ['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId],
});
// Refresh credits balance
queryClient.invalidateQueries({
queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId],
});
},
onError: (error: Error) => {
const errorMessage = error?.message || 'Failed to initiate payment';
toast({
title: 'Payment failed',
description: errorMessage,
variant: 'destructive',
});
},
});
// Mutation for checking payment status
const checkPaymentMutation = useMutation({
mutationFn: async (paymentId: string): Promise<Payment> => {
const ai = createAIClient(connection, user);
return await ai.get(`/credits/payments/${paymentId}`) as Payment;
},
onMutate: async (paymentId: string) => {
// Add this payment to the refreshing set
setRefreshingPayments(prev => new Set(prev).add(paymentId));
},
onSuccess: (updatedPayment) => {
// Remove from refreshing set
setRefreshingPayments(prev => {
const newSet = new Set(prev);
newSet.delete(updatedPayment.id);
return newSet;
});
// Update the specific payment in the cache instead of refetching
queryClient.setQueryData<Payment[]>(
['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId],
(oldPayments) => {
if (!oldPayments) return oldPayments;
return oldPayments.map(payment =>
payment.id === updatedPayment.id ? updatedPayment : payment
);
}
);
// If payment completed, refresh credits balance
if (updatedPayment.status === 'completed') {
queryClient.invalidateQueries({
queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId],
});
toast({
title: 'Payment completed!',
description: `${formatCurrency(updatedPayment.amount)} has been added to your account.`,
});
} else if (updatedPayment.status === 'failed') {
toast({
title: 'Payment failed',
description: 'The payment has failed. Please try again.',
variant: 'destructive',
});
} else if (updatedPayment.status === 'expired') {
toast({
title: 'Payment expired',
description: 'The payment has expired. Please create a new payment.',
variant: 'destructive',
});
}
},
onError: (error: Error, paymentId: string) => {
// Remove from refreshing set on error
setRefreshingPayments(prev => {
const newSet = new Set(prev);
newSet.delete(paymentId);
return newSet;
});
const errorMessage = error?.message || 'Failed to check payment status';
toast({
title: 'Refresh failed',
description: errorMessage,
variant: 'destructive',
});
},
});
const handleAddCredits = () => {
if (amount <= 0) {
toast({
title: 'Invalid amount',
description: 'Please enter a valid amount.',
variant: 'destructive',
});
return;
}
const request: AddCreditsRequest = {
amount,
method: paymentMethod,
};
if (paymentMethod === 'stripe') {
request.redirect_url = window.location.origin + '/settings/ai';
}
addCreditsMutation.mutate(request);
};
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(amount);
};
const formatDate = (timestamp: number) => {
const date = new Date(timestamp * 1000);
const now = new Date();
const diffDays = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60 * 24));
if (diffDays === 0) {
return new Intl.DateTimeFormat('en-US', {
hour: '2-digit',
minute: '2-digit',
}).format(date);
} else if (diffDays === 1) {
return 'Yesterday';
} else if (diffDays < 7) {
return new Intl.DateTimeFormat('en-US', {
weekday: 'short',
}).format(date);
} else {
return new Intl.DateTimeFormat('en-US', {
month: 'short',
day: 'numeric',
}).format(date);
}
};
const getStatusIcon = (status: Payment['status']) => {
switch (status) {
case 'completed':
return <Check className="h-4 w-4 text-green-600" />;
case 'failed':
return <X className="h-4 w-4 text-red-600" />;
case 'expired':
return <AlertCircle className="h-4 w-4 text-orange-600" />;
case 'pending':
default:
return <Clock className="h-4 w-4 text-yellow-600" />;
}
};
const getStatusVariant = (status: Payment['status']): "default" | "secondary" | "destructive" | "outline" => {
switch (status) {
case 'completed':
return 'default';
case 'failed':
return 'destructive';
case 'expired':
return 'secondary';
case 'pending':
default:
return 'outline';
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-full max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none">
<DialogHeader className="flex-shrink-0">
<DialogTitle className="flex items-center gap-2 text-lg">
{lightningInvoice ? (
<>
<button
onClick={() => setLightningInvoice(null)}
className="flex items-center gap-2 hover:opacity-70 transition-opacity"
>
<ArrowLeft className="h-5 w-5" />
Back
</button>
</>
) : (
<>
<CreditCard className="h-5 w-5" />
Credits
</>
)}
</DialogTitle>
</DialogHeader>
{/* Lightning Payment Interface */}
{lightningInvoice ? (
<div className="flex-1 overflow-y-auto px-1 -mx-1">
<LightningPayment
invoice={lightningInvoice}
amount={amount}
onClose={() => setLightningInvoice(null)}
/>
</div>
) : (
<div className="flex-1 flex flex-col min-h-0">
{/* Add Credits Form - Fixed size section */}
<div className="flex-shrink-0 space-y-4 px-1 -mx-1">
<div className="space-y-3">
<Label htmlFor="amount" className="text-sm font-medium">Amount (USD)</Label>
<div className="space-y-3">
<Input
id="amount"
type="number"
step="0.01"
value={amount}
onChange={(e) => setAmount(Number(e.target.value))}
placeholder="Enter amount"
className="text-center text-lg font-medium"
/>
<div className="grid grid-cols-5 gap-2">
{PRESET_AMOUNTS.map((preset) => (
<Button
key={preset}
variant={amount === preset ? "default" : "outline"}
size="sm"
onClick={() => setAmount(preset)}
className="text-xs"
>
${preset}
</Button>
))}
</div>
</div>
</div>
<div className="space-y-3">
<Label htmlFor="payment-method" className="text-sm font-medium">Payment Method</Label>
<Select value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="stripe">
<div className="flex items-center gap-2">
<CreditCard className="h-4 w-4" />
Credit Card
</div>
</SelectItem>
<SelectItem value="lightning">
<div className="flex items-center gap-2">
<Zap className="h-4 w-4" />
Lightning
</div>
</SelectItem>
</SelectContent>
</Select>
</div>
<Button
onClick={handleAddCredits}
disabled={amount <= 0 || addCreditsMutation.isPending}
className="w-full h-12 text-base font-medium"
size="lg"
>
{addCreditsMutation.isPending && <RefreshCw className="h-4 w-4 mr-2 animate-spin" />}
{paymentMethod === 'stripe' ? 'Pay with Card' : 'Generate Invoice'}
{amount > 0 && ` - ${formatCurrency(amount)}`}
</Button>
</div>
<div className="flex-shrink-0 px-1 -mx-1 py-4">
<Separator />
</div>
{/* Transaction History - Flexible section */}
<div className="flex-1 min-h-0 flex flex-col px-1 -mx-1">
<div className="flex-shrink-0 mb-4">
<h3 className="text-base font-semibold">Recent Transactions</h3>
</div>
<div className="flex-1 min-h-0 overflow-y-auto">
{isLoadingPayments ? (
<div className="space-y-3">
{Array.from({ length: 3 }).map((_, i) => (
<div key={i} className="p-3 border rounded-lg space-y-2">
<div className="flex items-center gap-2">
<Skeleton className="h-4 w-4 rounded" />
<Skeleton className="h-4 w-24" />
<Skeleton className="h-4 w-16 ml-auto" />
</div>
<Skeleton className="h-3 w-32" />
</div>
))}
</div>
) : !payments || payments.length === 0 ? (
<div className="flex-1 flex items-center justify-center">
<div className="text-center text-muted-foreground">
<CreditCard className="h-10 w-10 mx-auto mb-3 opacity-50" />
<p className="text-sm">No transactions yet</p>
<p className="text-xs">Your payment history will appear here</p>
</div>
</div>
) : (
<div className="space-y-2 pb-2">
{payments.map((payment) => (
<div
key={payment.id}
className="p-3 border rounded-lg space-y-2 hover:bg-muted/30 transition-colors"
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 min-w-0 flex-1">
{getStatusIcon(payment.status)}
<span className="text-sm font-medium truncate">
{payment.method === 'stripe' ? 'Credit Card' : 'Lightning'}
</span>
<Badge variant={getStatusVariant(payment.status)} className="text-xs flex-shrink-0">
{payment.status}
</Badge>
</div>
<div className="text-right flex-shrink-0">
<p className="text-sm font-medium">{formatCurrency(payment.amount)}</p>
{payment.fee > 0 && (
<p className="text-xs text-muted-foreground">
+{formatCurrency(payment.fee)}
</p>
)}
</div>
</div>
<div className="flex items-center justify-between text-xs text-muted-foreground">
<span>{formatDate(payment.created_at)}</span>
{payment.status === 'pending' && (
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => checkPaymentMutation.mutate(payment.id)}
disabled={refreshingPayments.has(payment.id)}
className="h-6 px-2 text-xs"
title="Refresh payment status"
>
<RotateCcw className={`h-3 w-3 ${refreshingPayments.has(payment.id) ? 'animate-spin' : ''}`} />
</Button>
{payment.url && (
<Button
variant="ghost"
size="sm"
onClick={() => {
if (payment.method === 'lightning') {
setLightningInvoice(payment.url);
} else {
window.open(payment.url, '_blank');
}
}}
className="h-6 px-2 text-xs"
>
<ExternalLink className="h-3 w-3 mr-1" />
{payment.method === 'lightning' ? 'Pay' : 'Pay'}
</Button>
)}
</div>
)}
</div>
</div>
))}
</div>
)}
</div>
</div>
</div>
)}
</DialogContent>
</Dialog>
);
}
+28 -240
View File
@@ -34,20 +34,13 @@ import {
RefreshCw,
Settings,
AlertTriangle,
Zap,
} from 'lucide-react';
import { useGitStatus } from '@/hooks/useGitStatus';
import { useGitSettings } from '@/hooks/useGitSettings';
import { useGit } from '@/hooks/useGit';
import { useToast } from '@/hooks/useToast';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostr } from '@nostrify/react';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { cn } from '@/lib/utils';
import { findCredentialsForRepo, getOriginDisplayName } from '@/lib/gitCredentials';
import { nip19 } from 'nostr-tools';
const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev", "gitnostr.com"];
interface GitDialogProps {
projectId: string;
@@ -59,226 +52,26 @@ interface GitDialogProps {
export function GitDialog({ projectId, children, open, onOpenChange }: GitDialogProps) {
const [isPushing, setIsPushing] = useState(false);
const [isPulling, setIsPulling] = useState(false);
const [isPushingToNostr, setIsPushingToNostr] = useState(false);
const [pushResult, setPushResult] = useState<string | null>(null);
const [pullResult, setPullResult] = useState<string | null>(null);
const navigate = useNavigate();
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
const { settings } = useGitSettings();
const { git } = useGit();
const git = useGit();
const { toast } = useToast();
const { user } = useCurrentUser();
const { nostr } = useNostr();
const { mutateAsync: publishEvent } = useNostrPublish();
const projectPath = `/projects/${projectId}`;
const handlePushToNostr = async () => {
if (!user) {
toast({
title: "Cannot push to Nostr",
description: "You must be logged in to push to Nostr",
variant: "destructive",
});
return;
}
if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) {
toast({
title: "Cannot push to Nostr",
description: "Not a git repository or no current branch",
variant: "destructive",
});
return;
}
setIsPushingToNostr(true);
setPushResult(null);
try {
// Check if repo announcement already exists
const existingRepoEvents = await nostr.query([{
kinds: [30617],
authors: [user.pubkey],
'#d': [projectId],
limit: 1,
}], { signal: AbortSignal.timeout(5000) });
if (existingRepoEvents.length > 0) {
throw new Error(`Repository announcement already exists for project "${projectId}". Cannot create duplicate.`);
}
// Create repo announcement event (NIP-34 kind 30617)
const cloneUrls = GRASP_SERVERS.map(server =>
`https://${server}/${nip19.npubEncode(user.pubkey)}/${projectId}.git`
);
const relayUrls = GRASP_SERVERS.map(server => `wss://${server}`);
await publishEvent({
kind: 30617,
content: "",
tags: [
["d", projectId],
["clone", ...cloneUrls],
["relays", ...relayUrls],
],
});
// Get current repository state
const refTags: string[][] = [];
// First check if we have any commits at all
try {
const log = await git.log({ dir: projectPath, depth: 1 });
if (log.length === 0) {
throw new Error('Repository has no commits. Please make at least one commit before publishing to Nostr.');
}
console.log(`Repository has ${log.length} commit(s), latest: ${log[0].oid}`);
} catch (error) {
if (error instanceof Error && error.message.includes('no commits')) {
throw error; // Re-throw our custom error
}
throw new Error('Repository has no commits. Please make at least one commit before publishing to Nostr.');
}
try {
// Get all refs using listRefs
const refs = await git.listRefs({ dir: projectPath });
console.log('Found refs:', refs);
for (const ref of refs) {
try {
const commitId = await git.resolveRef({
dir: projectPath,
ref,
});
if (ref.startsWith('refs/heads/') || ref.startsWith('refs/tags/')) {
refTags.push([ref, commitId]);
}
} catch (error) {
console.warn(`Failed to resolve ref ${ref}:`, error);
}
}
} catch (error) {
console.warn('Failed to list refs, trying alternative approach:', error);
}
// If no refs found, try to get the current branch directly
if (refTags.length === 0) {
try {
const currentBranch = await git.currentBranch({ dir: projectPath });
if (currentBranch) {
const currentCommit = await git.resolveRef({
dir: projectPath,
ref: 'HEAD',
});
refTags.push([`refs/heads/${currentBranch}`, currentCommit]);
console.log(`Added current branch: refs/heads/${currentBranch} -> ${currentCommit}`);
} else {
// Try to get HEAD directly even if no current branch
try {
const headCommit = await git.resolveRef({
dir: projectPath,
ref: 'HEAD',
});
refTags.push(['refs/heads/main', headCommit]); // Assume main branch
console.log(`Added assumed main branch: refs/heads/main -> ${headCommit}`);
} catch (headError) {
console.warn('Failed to resolve HEAD directly:', headError);
}
}
} catch (error) {
console.warn('Failed to get current branch:', error);
}
}
if (refTags.length === 0) {
throw new Error('Could not determine repository state. The repository might not have any commits or branches.');
}
// Get HEAD reference
let headRef: string | undefined;
try {
const currentBranch = await git.currentBranch({ dir: projectPath });
if (currentBranch) {
headRef = `ref: refs/heads/${currentBranch}`;
console.log(`HEAD points to: ${headRef}`);
} else {
// HEAD is detached, use the commit ID directly
const headValue = await git.resolveRef({
dir: projectPath,
ref: 'HEAD',
});
if (headValue) {
headRef = headValue;
console.log(`HEAD is detached at: ${headRef}`);
}
}
} catch (error) {
console.warn('Failed to resolve HEAD:', error);
}
// Create repo state event (NIP-34 kind 30618)
await publishEvent({
kind: 30618,
content: "",
tags: [
["d", projectId],
...refTags,
...(headRef ? [["HEAD", headRef]] : []),
],
});
// Set origin remote to Nostr URL
const nostrUrl = `nostr://${nip19.npubEncode(user.pubkey)}/git.shakespeare.diy/${projectId}`;
try {
// Remove existing origin if it exists
await git.deleteRemote({
dir: projectPath,
remote: 'origin',
});
} catch {
// Ignore if origin doesn't exist
}
await git.addRemote({
dir: projectPath,
remote: 'origin',
url: nostrUrl,
});
// Set nostr.repo config
await git.setConfig({
dir: projectPath,
path: 'nostr.repo',
value: nip19.naddrEncode({
kind: 30617,
pubkey: user.pubkey,
identifier: projectId,
}),
});
toast({
title: "Repository published to Nostr",
description: "Waiting for GRASP servers to update...",
});
setPushResult(`✅ Successfully published repository to Nostr`);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
setPushResult(`❌ Push to Nostr failed: ${errorMessage}`);
toast({
title: "Push to Nostr failed",
description: errorMessage,
variant: "destructive",
});
} finally {
setIsPushingToNostr(false);
}
// Get credentials for the current repository
const getCredentialsForCurrentRepo = () => {
if (!gitStatus?.remotes.length) return null;
const remoteUrl = gitStatus.remotes[0].url; // Use first remote (usually 'origin')
return findCredentialsForRepo(remoteUrl, settings.credentials);
};
const currentCredentials = getCredentialsForCurrentRepo();
const handlePush = async () => {
if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) {
toast({
@@ -313,12 +106,19 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
try {
const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin')
// Prepare authentication if credentials are available
const authOptions = currentCredentials ? {
onAuth: () => ({
username: currentCredentials.username,
password: currentCredentials.password
}),
} : {};
await git.push({
dir: projectPath,
remote: remote.name,
ref: gitStatus.currentBranch,
onAuth: (url) => findCredentialsForRepo(url, settings.credentials),
signer: user?.signer, // For signing if pushing to Nostr
...authOptions,
});
setPushResult(`✅ Successfully pushed ${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} to ${remote.name}/${gitStatus.currentBranch}`);
@@ -367,6 +167,14 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
try {
const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin')
// Prepare authentication if credentials are available
const authOptions = currentCredentials ? {
onAuth: () => ({
username: currentCredentials.username,
password: currentCredentials.password
}),
} : {};
await git.pull({
dir: projectPath,
ref: gitStatus.currentBranch,
@@ -375,7 +183,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
name: 'shakespeare.diy',
email: '[email protected]',
},
onAuth: (url) => findCredentialsForRepo(url, settings.credentials),
...authOptions,
});
setPullResult(`✅ Successfully pulled from ${remote.name}/${gitStatus.currentBranch}`);
@@ -644,7 +452,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
<div className="flex gap-2">
<Button
onClick={handlePull}
disabled={isPulling || isPushing || isPushingToNostr}
disabled={isPulling || isPushing}
variant="outline"
size="sm"
className="flex-1"
@@ -659,7 +467,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
<Button
onClick={handlePush}
disabled={isPushing || isPulling || isPushingToNostr || gitStatus.ahead === 0}
disabled={isPushing || isPulling || gitStatus.ahead === 0}
variant="outline"
size="sm"
className="flex-1"
@@ -674,26 +482,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
</div>
)}
{/* Push to Nostr button when no remote is configured and user is logged in */}
{gitStatus.remotes.length === 0 && user && (
<div className="flex gap-2">
<Button
onClick={handlePushToNostr}
disabled={isPushingToNostr || isPushing || isPulling}
variant="outline"
size="sm"
className="flex-1"
>
{isPushingToNostr ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Zap className="h-4 w-4 mr-2" />
)}
{isPushingToNostr ? 'Publishing to Nostr...' : 'Push to Nostr'}
</Button>
</div>
)}
{/* Operation Results */}
{(pushResult || pullResult) && (
<div className="mt-3 space-y-2">
-52
View File
@@ -1,52 +0,0 @@
import { describe, it, expect } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { LanguagePicker } from './LanguagePicker';
describe('LanguagePicker', () => {
it('renders language picker with default English selection', () => {
render(
<TestApp>
<LanguagePicker />
</TestApp>
);
// Should show the trigger button
expect(screen.getByRole('combobox')).toBeInTheDocument();
});
it('shows language options when opened', async () => {
render(
<TestApp>
<LanguagePicker />
</TestApp>
);
// Click to open the dropdown
const trigger = screen.getByRole('combobox');
fireEvent.click(trigger);
// Should show all language options (using getAllByText since there might be duplicates)
expect(screen.getAllByText('System').length).toBeGreaterThan(0);
expect(screen.getAllByText('English').length).toBeGreaterThan(0);
expect(screen.getAllByText('Portuguese').length).toBeGreaterThan(0);
expect(screen.getAllByText('Chinese').length).toBeGreaterThan(0);
});
it('displays flag emojis for languages', async () => {
render(
<TestApp>
<LanguagePicker />
</TestApp>
);
// Click to open the dropdown
const trigger = screen.getByRole('combobox');
fireEvent.click(trigger);
// Should show flag emojis (using getAllByText since there might be duplicates)
expect(screen.getAllByText('🇺🇸').length).toBeGreaterThan(0);
expect(screen.getAllByText('🇧🇷').length).toBeGreaterThan(0);
expect(screen.getAllByText('🇨🇳').length).toBeGreaterThan(0);
});
});
-53
View File
@@ -1,53 +0,0 @@
import { useTranslation } from 'react-i18next';
import { Languages } from 'lucide-react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useAppContext } from '@/hooks/useAppContext';
interface LanguagePickerProps {
className?: string;
}
export function LanguagePicker({ className }: LanguagePickerProps) {
const { t } = useTranslation();
const { config, updateConfig } = useAppContext();
const handleLanguageChange = (language: string) => {
updateConfig((prev) => ({ ...prev, language: language === 'system' ? undefined : language }));
};
return (
<Select value={config.language ?? 'system'} onValueChange={handleLanguageChange}>
<SelectTrigger className={className}>
<div className="flex items-center gap-2">
<SelectValue />
</div>
</SelectTrigger>
<SelectContent>
<SelectItem value="system">
<div className="flex items-center gap-2">
<Languages className="h-4 w-4" />
{t('systemLanguage')}
</div>
</SelectItem>
<SelectItem value="en">
<div className="flex items-center gap-2">
<span className="text-lg">🇺🇸</span>
{t('english')}
</div>
</SelectItem>
<SelectItem value="pt">
<div className="flex items-center gap-2">
<span className="text-lg">🇧🇷</span>
{t('portuguese')}
</div>
</SelectItem>
<SelectItem value="zh">
<div className="flex items-center gap-2">
<span className="text-lg">🇨🇳</span>
{t('chinese')}
</div>
</SelectItem>
</SelectContent>
</Select>
);
}
-89
View File
@@ -1,89 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
// Mock QRCode
vi.mock('qrcode', () => ({
default: {
toDataURL: vi.fn().mockResolvedValue('data:image/png;base64,mock-qr-code'),
},
}));
// Mock WebLN
const mockWebLN = {
enable: vi.fn().mockResolvedValue(undefined),
sendPayment: vi.fn().mockResolvedValue({ preimage: 'mock-preimage' }),
};
// We need to import the component after mocking
const { CreditsDialog } = await import('./CreditsDialog');
const mockConnection = {
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
};
describe('Lightning Payment', () => {
beforeEach(() => {
vi.clearAllMocks();
// Reset WebLN mock
Object.defineProperty(window, 'webln', {
value: undefined,
writable: true,
});
});
it('shows QR code for Lightning payment', async () => {
render(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
// Should show the normal form initially
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
});
it('shows WebLN button when available', async () => {
// Mock WebLN availability
Object.defineProperty(window, 'webln', {
value: mockWebLN,
writable: true,
});
render(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
// Should show the normal form initially
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
});
it('displays copy invoice button', async () => {
render(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
// Should show the normal form initially
expect(screen.getByText('Payment Method')).toBeInTheDocument();
});
});
-240
View File
@@ -1,240 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { ModelSelector } from './ModelSelector';
// Mock the hooks
vi.mock('@/hooks/useAISettings', () => ({
useAISettings: vi.fn(),
}));
vi.mock('@/hooks/useProviderModels', () => ({
useProviderModels: vi.fn(),
}));
vi.mock('react-router-dom', async (importOriginal) => {
const actual = await importOriginal() as Record<string, unknown>;
return {
...actual,
useNavigate: () => vi.fn(),
};
});
import { useAISettings } from '@/hooks/useAISettings';
import { useProviderModels } from '@/hooks/useProviderModels';
const mockUseAISettings = vi.mocked(useAISettings);
const mockUseProviderModels = vi.mocked(useProviderModels);
describe('ModelSelector', () => {
const mockOnChange = vi.fn();
const mockAddRecentlyUsedModel = vi.fn();
beforeEach(() => {
vi.clearAllMocks();
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels: [] },
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
});
mockUseProviderModels.mockReturnValue({
models: [],
isLoading: false,
error: null,
refetch: vi.fn(),
});
});
it('hides recently used section when less than 5 models and all recently used are available', async () => {
// Setup: 3 available models, 2 recently used models that are both available
const availableModels = [
{ fullId: 'provider1/model1', provider: 'provider1', id: 'model1' },
{ fullId: 'provider1/model2', provider: 'provider1', id: 'model2' },
{ fullId: 'provider2/model3', provider: 'provider2', id: 'model3' },
];
const recentlyUsedModels = ['provider1/model1', 'provider1/model2'];
mockUseProviderModels.mockReturnValue({
models: availableModels,
isLoading: false,
error: null,
refetch: vi.fn(),
});
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels },
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="" onChange={mockOnChange} />
</TestApp>
);
// Open the dropdown
const trigger = screen.getByRole('combobox');
fireEvent.click(trigger);
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('provider1')).toBeInTheDocument();
});
// Recently used section should NOT be visible
expect(screen.queryByText('Recently Used')).not.toBeInTheDocument();
});
it('shows recently used section when less than 5 models but some recently used are not available', async () => {
// Setup: 3 available models, 2 recently used models where 1 is not available
const availableModels = [
{ fullId: 'provider1/model1', provider: 'provider1', id: 'model1' },
{ fullId: 'provider1/model2', provider: 'provider1', id: 'model2' },
{ fullId: 'provider2/model3', provider: 'provider2', id: 'model3' },
];
const recentlyUsedModels = ['provider1/model1', 'provider3/model4']; // model4 not in available
mockUseProviderModels.mockReturnValue({
models: availableModels,
isLoading: false,
error: null,
refetch: vi.fn(),
});
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels },
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="" onChange={mockOnChange} />
</TestApp>
);
// Open the dropdown
const trigger = screen.getByRole('combobox');
fireEvent.click(trigger);
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('provider1')).toBeInTheDocument();
});
// Recently used section SHOULD be visible
expect(screen.getByText('Recently Used')).toBeInTheDocument();
});
it('shows recently used section when 5 or more models are available', async () => {
// Setup: 5 available models, 2 recently used models that are both available
const availableModels = [
{ fullId: 'provider1/model1', provider: 'provider1', id: 'model1' },
{ fullId: 'provider1/model2', provider: 'provider1', id: 'model2' },
{ fullId: 'provider2/model3', provider: 'provider2', id: 'model3' },
{ fullId: 'provider2/model4', provider: 'provider2', id: 'model4' },
{ fullId: 'provider3/model5', provider: 'provider3', id: 'model5' },
];
const recentlyUsedModels = ['provider1/model1', 'provider1/model2'];
mockUseProviderModels.mockReturnValue({
models: availableModels,
isLoading: false,
error: null,
refetch: vi.fn(),
});
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels },
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="" onChange={mockOnChange} />
</TestApp>
);
// Open the dropdown
const trigger = screen.getByRole('combobox');
fireEvent.click(trigger);
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('provider1')).toBeInTheDocument();
});
// Recently used section SHOULD be visible
expect(screen.getByText('Recently Used')).toBeInTheDocument();
});
it('hides recently used section when no recently used models exist', async () => {
const availableModels = [
{ fullId: 'provider1/model1', provider: 'provider1', id: 'model1' },
{ fullId: 'provider1/model2', provider: 'provider1', id: 'model2' },
];
mockUseProviderModels.mockReturnValue({
models: availableModels,
isLoading: false,
error: null,
refetch: vi.fn(),
});
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels: [] }, // No recently used models
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="" onChange={mockOnChange} />
</TestApp>
);
// Open the dropdown
const trigger = screen.getByRole('combobox');
fireEvent.click(trigger);
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('provider1')).toBeInTheDocument();
});
// Recently used section should NOT be visible
expect(screen.queryByText('Recently Used')).not.toBeInTheDocument();
});
});
+35 -61
View File
@@ -1,6 +1,5 @@
import { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -24,9 +23,8 @@ export function ModelSelector({
onChange,
className,
disabled = false,
placeholder,
placeholder = "Select or enter a model...",
}: ModelSelectorProps) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const [isCustomInput, setIsCustomInput] = useState(false);
const [customValue, setCustomValue] = useState('');
@@ -34,8 +32,6 @@ export function ModelSelector({
const { models, isLoading, error, refetch } = useProviderModels();
const navigate = useNavigate();
const defaultPlaceholder = t('selectOrEnterModel');
const recentlyUsedModels = useMemo(() => settings.recentlyUsedModels || [], [settings.recentlyUsedModels]);
// Group models by provider
@@ -50,29 +46,6 @@ export function ModelSelector({
return groups;
}, [models]);
// Determine if we should show the "Recently Used" section
const shouldShowRecentlyUsed = useMemo(() => {
// If no recently used models, don't show the section
if (recentlyUsedModels.length === 0) {
return false;
}
// If there are 5 or more total provider models, always show recently used
if (models.length >= 5) {
return true;
}
// If less than 5 total provider models, check if all recently used models
// are contained within the available provider models
const availableModelIds = new Set(models.map(model => model.fullId));
const allRecentlyUsedAreAvailable = recentlyUsedModels.every(model =>
availableModelIds.has(model)
);
// Hide recently used section if all recently used models are already available
return !allRecentlyUsedAreAvailable;
}, [recentlyUsedModels, models]);
// Don't auto-initialize with recently used models
// Let the parent component handle initialization
@@ -152,24 +125,48 @@ export function ModelSelector({
disabled={disabled}
>
<span className="w-full truncate">
{value || placeholder || defaultPlaceholder}
{value || placeholder}
</span>
<ChevronDown className="size-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-96 p-0" align="end">
<Command>
{isConfigured && <CommandInput placeholder={t('searchModels')} className="h-9" />}
{isConfigured && <CommandInput placeholder="Search models..." className="h-9" />}
<CommandList className="max-h-[300px]">
{/* Custom model option and manage providers */}
<CommandGroup>
{isConfigured && (
<CommandItem
value="__custom_model_option__"
onSelect={() => handleSelect('__custom__')}
className="cursor-pointer"
>
<Edit3 className="mr-2 h-4 w-4" />
Enter custom model...
</CommandItem>
)}
<CommandItem
value="__manage_providers_option__"
onSelect={() => handleSelect('__manage_providers__')}
className="cursor-pointer"
>
<Settings className="mr-2 h-4 w-4" />
Manage providers...
</CommandItem>
</CommandGroup>
<CommandSeparator />
<CommandEmpty>
<div className="py-6 text-center text-sm text-muted-foreground">
<p>{t('noModelsFound')}</p>
<p className="mt-2 text-xs">{t('tryCustomModel')}</p>
<p>No models found.</p>
<p className="mt-2 text-xs">Try using a custom model instead.</p>
</div>
</CommandEmpty>
{shouldShowRecentlyUsed && (
<CommandGroup heading={t('recentlyUsed')}>
{recentlyUsedModels.length > 0 && (
<CommandGroup heading="Recently Used">
{recentlyUsedModels.map((model) => (
<CommandItem
key={model}
@@ -189,11 +186,11 @@ export function ModelSelector({
</CommandGroup>
)}
{shouldShowRecentlyUsed && <CommandSeparator />}
{recentlyUsedModels.length > 0 && <CommandSeparator />}
{/* Loading state */}
{isLoading && (
<CommandGroup heading={t('loading')}>
<CommandGroup heading="Loading Models...">
<div className="px-2 py-1.5">
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
@@ -206,7 +203,7 @@ export function ModelSelector({
{/* Error state */}
{error && !isLoading && (
<CommandGroup heading={t('errorLoadingModels')}>
<CommandGroup heading="Error Loading Models">
<div className="px-2 py-1.5 text-sm text-muted-foreground">
<div className="flex items-start gap-2">
<AlertCircle className="h-4 w-4 text-destructive flex-shrink-0 mt-0.5" />
@@ -219,7 +216,7 @@ export function ModelSelector({
className="h-7 text-xs"
>
<RefreshCw className="h-3 w-3 mr-1" />
{t('retry')}
Retry
</Button>
</div>
</div>
@@ -251,29 +248,6 @@ export function ModelSelector({
</CommandGroup>
</div>
))}
{/* Custom model option and manage providers - moved to bottom */}
<CommandSeparator />
<CommandGroup>
{isConfigured && (
<CommandItem
value="__custom_model_option__"
onSelect={() => handleSelect('__custom__')}
className="cursor-pointer"
>
<Edit3 className="mr-2 h-4 w-4" />
{t('enterCustomModel')}
</CommandItem>
)}
<CommandItem
value="__manage_providers_option__"
onSelect={() => handleSelect('__manage_providers__')}
className="cursor-pointer"
>
<Settings className="mr-2 h-4 w-4" />
{t('manageProviders')}
</CommandItem>
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
+3 -32
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useRef } from 'react';
import { NostrEvent, NostrFilter, NPool, NRelay1 } from '@nostrify/nostrify';
import { NostrEvent, NPool, NRelay1 } from '@nostrify/nostrify';
import { NostrContext } from '@nostrify/react';
import { useQueryClient } from '@tanstack/react-query';
import { useAppContext } from '@/hooks/useAppContext';
@@ -8,19 +8,6 @@ interface NostrProviderProps {
children: React.ReactNode;
}
const GIT_KINDS = [
30617, // NIP-34 Repository Announcement
30618, // NIP-34 Commit Announcement
1617, // NIP-34 Patch
1621, // NIP-34 Issue
];
const GIT_RELAYS = [
'wss://git.shakespeare.diy/',
'wss://relay.ngit.dev/',
'wss://gitnostr.com/',
];
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
const { children } = props;
const { config, presetRelays } = useAppContext();
@@ -46,28 +33,12 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
return new NRelay1(url);
},
reqRouter(filters) {
const routes = new Map<string, NostrFilter[]>();
routes.set(relayUrl.current, filters);
if (filters.every((f) => f.kinds?.every((k) => GIT_KINDS.includes(k)))) {
// If all filters are git-related, route to all git relays
for (const url of GIT_RELAYS) {
routes.set(url, filters);
}
}
return routes;
return new Map([[relayUrl.current, filters]]);
},
eventRouter(event: NostrEvent) {
eventRouter(_event: NostrEvent) {
// Publish to the selected relay
const allRelays = new Set<string>([relayUrl.current]);
// If it's a git-related event, also publish to the git relays
if (GIT_KINDS.includes(event.kind)) {
for (const url of GIT_RELAYS) {
allRelays.add(url);
}
}
// Also publish to the preset relays, capped to 5
for (const { url } of (presetRelays ?? [])) {
allRelays.add(url);
-59
View File
@@ -1,59 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { OnboardingDialog } from './OnboardingDialog';
import { TestApp } from '@/test/TestApp';
// Mock the hooks
vi.mock('@/hooks/useAISettings', () => ({
useAISettings: () => ({
settings: { providers: [], recentlyUsedModels: [] },
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
updateSettings: vi.fn(),
isConfigured: false,
}),
}));
vi.mock('@/hooks/useCurrentUser', () => ({
useCurrentUser: () => ({ user: null }),
}));
vi.mock('@/hooks/useLoginActions', () => ({
useLoginActions: () => ({ nsec: vi.fn() }),
}));
vi.mock('@/hooks/useProviderModels', () => ({
useProviderModels: () => ({
models: [],
isLoading: false,
error: null,
refetch: vi.fn(),
}),
}));
describe('OnboardingDialog', () => {
it('renders welcome step when open', () => {
render(
<TestApp>
<OnboardingDialog open={true} onOpenChange={vi.fn()} />
</TestApp>
);
expect(screen.getAllByText('Welcome to Shakespeare!')).toHaveLength(2); // Title and heading
expect(screen.getByText(/Your AI-powered development assistant/)).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Get Started/i })).toBeInTheDocument();
});
it('does not render when closed', () => {
render(
<TestApp>
<OnboardingDialog open={false} onOpenChange={vi.fn()} />
</TestApp>
);
expect(screen.queryByText('Welcome to Shakespeare!')).not.toBeInTheDocument();
});
});
-341
View File
@@ -1,341 +0,0 @@
import { Decimal } from 'decimal.js';
import { useState, useEffect } from 'react';
import { generateSecretKey } from 'nostr-tools';
import { nip19 } from 'nostr-tools';
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useAISettings } from '@/hooks/useAISettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useLoginActions } from '@/hooks/useLoginActions';
import { useProviderModels } from '@/hooks/useProviderModels';
import { CreditsDialog } from '@/components/CreditsDialog';
interface OnboardingDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
type OnboardingStep = 'welcome' | 'model-selection' | 'conclusion';
const SHAKESPEARE_PROVIDER = {
id: "shakespeare",
baseURL: "https://ai.shakespeare.diy/v1",
nostr: true,
};
export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) {
const [step, setStep] = useState<OnboardingStep>('welcome');
const [selectedModel, setSelectedModel] = useState<string>('');
const [isSettingUp, setIsSettingUp] = useState(false);
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
const { setProvider, addRecentlyUsedModel } = useAISettings();
const { user } = useCurrentUser();
const login = useLoginActions();
const { models, isLoading: isLoadingModels } = useProviderModels();
// Filter models to only show Shakespeare provider models
const shakespeareModels = models.filter(model => model.provider === 'shakespeare');
const handleGetStarted = async () => {
setIsSettingUp(true);
try {
// If user is not logged in, generate and login with secret key
if (!user) {
const secretKey = generateSecretKey();
const nsec = nip19.nsecEncode(secretKey);
login.nsec(nsec);
}
// Add Shakespeare provider to their config
setProvider(SHAKESPEARE_PROVIDER);
// Move to model selection
setStep('model-selection');
} catch (error) {
console.error('Failed to set up user:', error);
} finally {
setIsSettingUp(false);
}
};
const handleModelSelect = (modelFullId: string) => {
setSelectedModel(modelFullId);
};
const handleContinue = () => {
if (!selectedModel) return;
// Add model to recently used
addRecentlyUsedModel(selectedModel);
// Find the selected model to check if it's free
const model = shakespeareModels.find(m => m.fullId === selectedModel);
const isFreeModel = !model?.pricing || (
model.pricing.prompt.equals(0) && model.pricing.completion.equals(0)
);
if (isFreeModel) {
// Free model, go straight to conclusion
setStep('conclusion');
} else {
// Paid model, show credits dialog
setShowCreditsDialog(true);
}
};
const handleCreditsDialogClose = () => {
setShowCreditsDialog(false);
setStep('conclusion');
};
const handleFinish = () => {
onOpenChange(false);
};
const formatPrice = (price: Decimal | undefined) => {
if (!price) return 'unknown';
if (price.equals(0)) return 'Free';
// Convert from per-token to per-1M tokens and format with $ prefix
const pricePerMillion = price.times(1_000_000);
return '$' + pricePerMillion.toFixed(2).toString().replace(/\.00$/, '') + '/M tokens';
};
// Reset state when dialog opens/closes
useEffect(() => {
if (open) {
setStep('welcome');
setSelectedModel('');
setIsSettingUp(false);
setShowCreditsDialog(false);
}
}, [open]);
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl max-h-[80vh] overflow-hidden">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
{step === 'model-selection' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('welcome')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
<span className="text-xl">
{step === 'welcome' && 'Welcome to Shakespeare!'}
{step === 'model-selection' && 'Choose Your AI Model'}
{step === 'conclusion' && "You're All Set!"}
</span>
</DialogTitle>
</DialogHeader>
<div className="flex-1 overflow-hidden">
{step === 'welcome' && (
<div className="text-center space-y-6 py-4">
<div className="text-6xl mb-4">🎭</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Welcome to Shakespeare!
</h2>
<p className="text-lg text-muted-foreground max-w-md mx-auto">
Your AI-powered development assistant for building custom Nostr applications.
Simply describe what you want to build, and AI will help you create it.
</p>
</div>
<div className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 max-w-lg mx-auto">
<div className="text-center space-y-2">
<div className="text-2xl">💡</div>
<p className="text-sm text-muted-foreground">AI-Powered Development</p>
</div>
<div className="text-center space-y-2">
<div className="text-2xl">⚡</div>
<p className="text-sm text-muted-foreground">Nostr Integration</p>
</div>
<div className="text-center space-y-2">
<div className="text-2xl">🚀</div>
<p className="text-sm text-muted-foreground">Instant Preview</p>
</div>
</div>
<Button
onClick={handleGetStarted}
disabled={isSettingUp}
size="lg"
className="gap-2"
>
{isSettingUp ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white" />
Setting up...
</>
) : (
<>
<Sparkles className="h-4 w-4" />
Get Started
</>
)}
</Button>
</div>
</div>
)}
{step === 'model-selection' && (
<div className="space-y-4">
<div className="text-center space-y-2">
<p className="text-muted-foreground">
Choose an AI model to power your development experience.
Different models offer various capabilities and pricing.
</p>
</div>
<ScrollArea className="h-96">
<div className="space-y-3 p-1">
{isLoadingModels ? (
<>
{Array.from({ length: 3 }).map((_, i) => (
<Card key={i} className="p-4">
<div className="space-y-3">
<div className="flex items-center justify-between">
<Skeleton className="h-5 w-32" />
<Skeleton className="h-5 w-16" />
</div>
<Skeleton className="h-4 w-full" />
<div className="flex gap-2">
<Skeleton className="h-6 w-20" />
<Skeleton className="h-6 w-24" />
</div>
</div>
</Card>
))}
</>
) : shakespeareModels.length === 0 ? (
<Card className="p-6 text-center">
<div className="space-y-2">
<Bot className="h-8 w-8 mx-auto text-muted-foreground" />
<p className="text-muted-foreground">
No models available. Please check your connection and try again.
</p>
</div>
</Card>
) : (
shakespeareModels.map((model) => {
const isSelected = selectedModel === model.fullId;
const isFree = model.pricing?.prompt.equals(0) && model.pricing?.completion.equals(0);
return (
<Card
key={model.fullId}
className={`cursor-pointer transition-all hover:shadow-md ${
isSelected ? 'ring-2 ring-primary' : ''
}`}
onClick={() => handleModelSelect(model.fullId)}
>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-base font-semibold">
{model.name ?? model.id}
</CardTitle>
<div className="flex items-center gap-2">
{isFree && (
<Badge variant="secondary" className="text-xs">
Free
</Badge>
)}
{isSelected && (
<div className="h-5 w-5 rounded-full bg-primary flex items-center justify-center">
<Check className="h-3 w-3 text-primary-foreground" />
</div>
)}
</div>
</div>
</CardHeader>
<CardContent className="pt-0">
{model.description && (
<p className="text-sm text-muted-foreground mb-3">
{model.description}
</p>
)}
<div className="flex items-center gap-4 text-xs text-muted-foreground">
{model.pricing && (
<>
<span>Input: {formatPrice(model.pricing.prompt)}</span>
<span>Output: {formatPrice(model.pricing.completion)}</span>
</>
)}
{model.contextLength && (
<span>Context: {model.contextLength.toLocaleString()} tokens</span>
)}
</div>
</CardContent>
</Card>
);
})
)}
</div>
</ScrollArea>
<div className="flex justify-end gap-2 pt-4 border-t">
<Button
onClick={handleContinue}
disabled={!selectedModel}
className="gap-2"
>
Continue
<ArrowRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
{step === 'conclusion' && (
<div className="text-center space-y-6 py-8">
<div className="text-5xl mb-4">🎉</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold">Now you're ready to build!</h2>
<p className="text-lg text-muted-foreground max-w-md mx-auto">
Your AI assistant is configured and ready to help.
Just enter your prompt to start building amazing Nostr applications.
</p>
</div>
<div className="bg-muted/50 rounded-lg p-4 max-w-md mx-auto">
<p className="text-sm text-muted-foreground italic">
"Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies..."
</p>
</div>
<Button onClick={handleFinish} size="lg" className="gap-2">
<Sparkles className="h-4 w-4" />
Start Building
</Button>
</div>
)}
</div>
</DialogContent>
</Dialog>
{/* Credits Dialog */}
{showCreditsDialog && selectedModel && (
<CreditsDialog
open={showCreditsDialog}
onOpenChange={(open) => {
if (!open) {
handleCreditsDialogClose();
}
}}
providerId="shakespeare"
connection={SHAKESPEARE_PROVIDER}
/>
)}
</>
);
}
-145
View File
@@ -1,145 +0,0 @@
import { render, screen, fireEvent } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { ProjectSidebar } from './ProjectSidebar';
import { useProjects } from '@/hooks/useProjects';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { TestApp } from '@/test/TestApp';
// Mock the hooks
vi.mock('@/hooks/useProjects');
vi.mock('@/hooks/useLocalStorage');
vi.mock('@/hooks/useProjectSessionStatus', () => ({
useProjectSessionStatus: () => ({ hasRunningSessions: false })
}));
vi.mock('react-router-dom', async (importOriginal) => {
const actual = await importOriginal() as Record<string, unknown>;
return {
...actual,
useNavigate: () => vi.fn()
};
});
vi.mock('@tanstack/react-query', async (importOriginal) => {
const actual = await importOriginal() as Record<string, unknown>;
return {
...actual,
useQueryClient: () => ({
invalidateQueries: vi.fn(),
resetQueries: vi.fn()
})
};
});
// Mock window.open for help button test
const mockWindowOpen = vi.fn();
Object.defineProperty(window, 'open', {
value: mockWindowOpen,
writable: true
});
const mockUseProjects = vi.mocked(useProjects);
const mockUseLocalStorage = vi.mocked(useLocalStorage);
describe('ProjectSidebar', () => {
beforeEach(() => {
mockUseProjects.mockReturnValue({
data: [],
isLoading: false,
error: null
} as unknown as ReturnType<typeof useProjects>);
mockUseLocalStorage.mockReturnValue([[], vi.fn()]);
});
it('renders sidebar header with logo', () => {
render(
<TestApp>
<ProjectSidebar
selectedProject={null}
onSelectProject={vi.fn()}
/>
</TestApp>
);
expect(screen.getByText('🎭')).toBeInTheDocument();
expect(screen.getByText('Shakespeare')).toBeInTheDocument();
});
it('shows collapse button when onToggleSidebar is provided', () => {
const mockToggle = vi.fn();
render(
<TestApp>
<ProjectSidebar
selectedProject={null}
onSelectProject={vi.fn()}
onToggleSidebar={mockToggle}
/>
</TestApp>
);
const collapseButton = screen.getByLabelText('Collapse sidebar');
expect(collapseButton).toBeInTheDocument();
fireEvent.click(collapseButton);
expect(mockToggle).toHaveBeenCalledTimes(1);
});
it('does not show collapse button when onToggleSidebar is not provided', () => {
render(
<TestApp>
<ProjectSidebar
selectedProject={null}
onSelectProject={vi.fn()}
/>
</TestApp>
);
expect(screen.queryByLabelText('Collapse sidebar')).not.toBeInTheDocument();
});
it('renders settings and help buttons at the bottom', () => {
render(
<TestApp>
<ProjectSidebar
selectedProject={null}
onSelectProject={vi.fn()}
/>
</TestApp>
);
expect(screen.getByText('Settings')).toBeInTheDocument();
expect(screen.getByLabelText('Help')).toBeInTheDocument();
});
it('shows new project button', () => {
render(
<TestApp>
<ProjectSidebar
selectedProject={null}
onSelectProject={vi.fn()}
/>
</TestApp>
);
expect(screen.getByText('New Project')).toBeInTheDocument();
});
it('opens help documentation when help button is clicked', () => {
render(
<TestApp>
<ProjectSidebar
selectedProject={null}
onSelectProject={vi.fn()}
/>
</TestApp>
);
const helpButton = screen.getByLabelText('Help');
fireEvent.click(helpButton);
expect(mockWindowOpen).toHaveBeenCalledWith(
'https://soapbox.pub/shakespeare-resources/',
'_blank'
);
});
});
+33 -66
View File
@@ -1,14 +1,13 @@
import React, { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } from 'lucide-react';
import { Plus, Folder, GitBranch, Settings, Loader2, ChevronDown, Star, Columns2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { LoginArea } from '@/components/auth/LoginArea';
import { useProjects } from '@/hooks/useProjects';
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { Project } from '@/lib/ProjectsManager';
import { cn } from '@/lib/utils';
import { useQueryClient } from '@tanstack/react-query';
@@ -77,44 +76,26 @@ interface ProjectSidebarProps {
selectedProject: Project | null;
onSelectProject: (project: Project | null) => void;
className?: string;
onToggleSidebar?: () => void;
onClose?: () => void;
showCollapseButton?: boolean;
onCollapse?: () => void;
}
export function ProjectSidebar({
selectedProject,
onSelectProject,
className,
onToggleSidebar,
onClose
showCollapseButton = false,
onCollapse
}: ProjectSidebarProps) {
const { t } = useTranslation();
const queryClient = useQueryClient();
const { data: projects = [], isLoading, error } = useProjects();
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
const isMobile = useIsMobile();
const navigate = useNavigate();
// Custom navigate function that closes sidebar on mobile
const navigateAndClose = (path: string) => {
navigate(path);
if (isMobile && onClose) {
onClose();
}
};
const handleNewProject = () => {
onSelectProject(null);
navigateAndClose('/');
};
const handleToggleSidebar = () => {
if (onToggleSidebar) {
onToggleSidebar();
} else if (onClose && isMobile) {
onClose();
}
navigate('/');
};
useEffect(() => {
@@ -131,7 +112,7 @@ export function ProjectSidebar({
<div className="flex px-4 h-12 border-b border-sidebar-border bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10">
<div className="flex items-center justify-between w-full">
<button
onClick={() => navigateAndClose('/')}
onClick={() => navigate('/')}
className="flex items-center gap-3 hover:opacity-80 transition-opacity text-left"
>
<span className="text-2xl">🎭</span>
@@ -139,23 +120,28 @@ export function ProjectSidebar({
Shakespeare
</h1>
</button>
{(onToggleSidebar || (onClose && isMobile)) && (
<div className="flex items-center gap-1">
<div className="flex items-center gap-1">
{/* Collapse button - shown when showCollapseButton is true */}
{showCollapseButton && onCollapse && (
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
onClick={handleToggleSidebar}
aria-label={(onClose && isMobile) ? t('closeSidebar') : t('collapseSidebar')}
className="h-8 w-8 p-0 hover:bg-primary/10"
onClick={onCollapse}
aria-label="Collapse sidebar"
>
{(onClose && isMobile) ? (
<X className="h-4 w-4 text-primary/60 hover:text-primary" />
) : (
<Columns2 className="h-4 w-4 text-primary/60 hover:text-primary" />
)}
<Columns2 className="h-4 w-4 text-primary/60 hover:text-primary" />
</Button>
</div>
)}
)}
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
onClick={() => navigate('/settings')}
>
<Settings className="h-4 w-4 text-primary/60 hover:text-primary" />
</Button>
</div>
</div>
</div>
@@ -169,7 +155,7 @@ export function ProjectSidebar({
className="flex-1 flex items-center justify-center px-3 py-2 text-sm font-medium text-primary-foreground rounded-l-md hover:bg-white/10 transition-colors"
>
<Plus className="h-4 w-4 mr-2" />
{t('newProject')}
New Project
</button>
<div className="w-px bg-white/20" />
<DropdownMenu>
@@ -180,11 +166,11 @@ export function ProjectSidebar({
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem
onClick={() => navigateAndClose('/clone')}
onClick={() => navigate('/clone')}
className="flex items-center gap-2 w-full"
>
<GitBranch className="h-4 w-4" />
{t('importRepository')}
Import Repository
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -206,8 +192,8 @@ export function ProjectSidebar({
) : projects.length === 0 ? (
<div className="text-center p-6 text-muted-foreground">
<Folder className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">{t('noProjectsYet')}</p>
<p className="text-xs">{t('createFirstProject')}</p>
<p className="text-sm">No projects yet</p>
<p className="text-xs">Create your first project to get started</p>
</div>
) : (
<div className="space-y-1">
@@ -225,28 +211,9 @@ export function ProjectSidebar({
</div>
</div>
{/* Settings and Help at Bottom */}
<div className="p-2 border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto">
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="sm"
className="flex-1 h-9 justify-start gap-2 text-sidebar-foreground dark:hover:text-sidebar-primary hover:bg-primary/10 dark:hover:bg-sidebar-accent/30 transition-all duration-200"
onClick={() => navigateAndClose('/settings')}
>
<Settings className="h-4 w-4 transition-colors duration-200" />
{t('settings')}
</Button>
<Button
variant="ghost"
size="sm"
className="h-9 w-9 p-0 text-sidebar-foreground dark:hover:text-sidebar-primary hover:bg-primary/10 dark:hover:bg-sidebar-accent/30 transition-all duration-200"
onClick={() => window.open('https://soapbox.pub/shakespeare-resources/', '_blank')}
aria-label={t('help')}
>
<HelpCircle className="h-4 w-4 transition-colors duration-200" />
</Button>
</div>
{/* Account Selector at Bottom */}
<div className="p-4 border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto">
<LoginArea className="w-full" />
</div>
</div>
);
+26 -55
View File
@@ -1,9 +1,8 @@
import { useState, useEffect } from 'react';
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react';
import { Menu, Columns2, Bot, GitBranch, Database } from 'lucide-react';
import { ProjectSidebar } from '@/components/ProjectSidebar';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useIsMobile } from '@/hooks/useIsMobile';
@@ -19,54 +18,31 @@ interface SettingsItem {
href: string;
}
// Define settings items as a function to get fresh translations
const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [
{
id: 'preferences',
title: t('preferences'),
description: t('preferencesDescription'),
icon: Settings2,
href: '/settings/preferences',
},
const settingsItems: SettingsItem[] = [
{
id: 'ai',
title: t('aiSettings'),
description: t('aiSettingsDescription'),
title: 'AI Settings',
description: 'Configure AI providers and API keys',
icon: Bot,
href: '/settings/ai',
},
{
id: 'git',
title: t('gitSettings'),
description: t('gitSettingsDescription'),
title: 'Git Settings',
description: 'Configure Git credentials for HTTP authentication',
icon: GitBranch,
href: '/settings/git',
},
{
id: 'nostr',
title: t('nostrSettings'),
description: t('nostrSettingsDescription'),
icon: Wifi,
href: '/settings/nostr',
},
{
id: 'data',
title: t('dataSettings'),
description: t('dataSettingsDescription'),
title: 'Data',
description: 'Export files and manage local data',
icon: Database,
href: '/settings/data',
},
{
id: 'about',
title: t('aboutShakespeare'),
description: t('aboutShakespeareDescription'),
icon: Info,
href: '/settings/about',
},
];
export function SettingsLayout() {
const { t } = useTranslation();
const navigate = useNavigate();
const location = useLocation();
const isMobile = useIsMobile();
@@ -85,7 +61,7 @@ export function SettingsLayout() {
// Set initial sidebar state based on projects and device type
if (!hasSetInitialState && !isMobile) {
// On desktop, show sidebar if there are projects
setIsSidebarVisible(true);
setIsSidebarVisible(projectList.length > 0);
setHasSetInitialState(true);
} else if (!hasSetInitialState && isMobile) {
// On mobile, always start hidden
@@ -114,25 +90,24 @@ export function SettingsLayout() {
};
// Get current settings page
const settingsItems = getSettingsItems(t);
const currentPath = location.pathname;
const currentSettingsId = settingsItems.find(item => item.href === currentPath)?.id;
if (isMobile) {
return (
<div className="min-h-dvh bg-background">
<div className="min-h-dvh bg-white">
{/* Mobile Header */}
<header className="h-12 border-b bg-background px-4 py-3 flex items-center justify-between">
<header className="h-12 border-b bg-white px-4 py-3 flex items-center justify-between">
<div className="flex items-center space-x-2">
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
aria-label={t('toggleSidebar')}
aria-label="Toggle sidebar"
>
<Menu className="h-4 w-4" />
</Button>
<h1 className="text-lg font-semibold">{t('settings')}</h1>
<h1 className="text-lg font-semibold">Settings</h1>
</div>
</header>
@@ -150,7 +125,6 @@ export function SettingsLayout() {
setIsSidebarVisible(false);
handleProjectSelect(project);
}}
onClose={() => setIsSidebarVisible(false)}
/>
</div>
</div>
@@ -163,7 +137,7 @@ export function SettingsLayout() {
// Desktop 3-column layout
return (
<div className="h-screen flex bg-background overflow-hidden">
<div className="h-screen flex bg-white overflow-hidden">
{/* Left Column - Projects Sidebar (optionally hidden) */}
{isSidebarVisible && (
<div className="w-80 border-r bg-sidebar flex-shrink-0">
@@ -171,29 +145,26 @@ export function SettingsLayout() {
selectedProject={null}
onSelectProject={handleProjectSelect}
className="h-full"
onToggleSidebar={() => setIsSidebarVisible(false)}
/>
</div>
)}
{/* Middle Column - Settings Navigation */}
<div className="w-96 border-r bg-background flex flex-col flex-shrink-0">
<div className="w-96 border-r bg-white flex flex-col flex-shrink-0">
{/* Header with toggle button */}
<div className="h-12 px-4 py-2 border-b flex-shrink-0">
<div className="flex items-center gap-3">
{!isSidebarVisible && (
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(true)}
className="h-8 w-8 p-0"
aria-label={t('openSidebar')}
>
<Menu className="h-4 w-4" />
</Button>
)}
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
className="h-8 w-8 p-0"
aria-label="Toggle sidebar"
>
{isSidebarVisible ? <Columns2 className="h-4 w-4" /> : <Menu className="h-4 w-4" />}
</Button>
<h1 className="text-xl font-bold flex items-center gap-2">
{t('settings')}
Settings
</h1>
</div>
</div>
@@ -235,7 +206,7 @@ export function SettingsLayout() {
</div>
{/* Right Column - Settings Content - Scrollable */}
<ScrollArea className="flex-1 bg-background">
<ScrollArea className="flex-1 bg-white">
<div className="max-w-4xl">
<Outlet />
</div>
+1 -204
View File
@@ -1,5 +1,5 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent, act } from '@testing-library/react';
import { render, screen, fireEvent } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { ChatPane } from './ChatPane';
@@ -8,15 +8,9 @@ vi.mock('@/hooks/useAISettings', () => ({
useAISettings: () => ({
isConfigured: true,
settings: {
providers: [],
recentlyUsedModels: ['gpt-4'],
},
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
updateSettings: vi.fn(),
}),
}));
@@ -65,204 +59,7 @@ vi.mock('@/hooks/useProviderModels', () => ({
}),
}));
vi.mock('@/hooks/useToast', () => ({
useToast: () => ({
toast: vi.fn(),
}),
}));
describe('ChatPane', () => {
describe('Placeholder switching', () => {
it('shows "Please select a model" placeholder when providerModel is empty', () => {
// Create a test that doesn't require modifying mocks
// Instead, we'll test the existing behavior which shows the placeholder when configured
render(
<TestApp>
<ChatPane projectId="test-project" />
</TestApp>
);
const textarea = screen.getByPlaceholderText(/Ask me to add features/);
expect(textarea).toBeInTheDocument();
});
it('shows "Ask me to add features" placeholder when providerModel is set', () => {
render(
<TestApp>
<ChatPane projectId="test-project" />
</TestApp>
);
const textarea = screen.getByPlaceholderText(/Ask me to add features/);
expect(textarea).toBeInTheDocument();
});
});
describe('Drag and drop functionality', () => {
it('handles dropping a single valid file', () => {
render(
<TestApp>
<ChatPane projectId="test-project" />
</TestApp>
);
const chatContainer = screen.getByPlaceholderText(/Ask me to add features/).closest('div')?.parentElement;
expect(chatContainer).toBeInTheDocument();
const validFile = new File(['test content'], 'test.txt', { type: 'text/plain' });
// Simulate drag and drop events
act(() => {
if (chatContainer) {
fireEvent.dragEnter(chatContainer, {
dataTransfer: { files: [] },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
});
fireEvent.dragOver(chatContainer, {
dataTransfer: { files: [validFile] },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
});
fireEvent.drop(chatContainer, {
dataTransfer: { files: [validFile] },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
});
}
});
// Verify the drop was handled (no errors thrown)
expect(chatContainer).toBeInTheDocument();
});
it('handles dropping multiple valid files', () => {
render(
<TestApp>
<ChatPane projectId="test-project" />
</TestApp>
);
const chatContainer = screen.getByPlaceholderText(/Ask me to add features/).closest('div')?.parentElement;
expect(chatContainer).toBeInTheDocument();
const files = [
new File(['content1'], 'file1.txt', { type: 'text/plain' }),
new File(['content2'], 'file2.txt', { type: 'text/plain' }),
];
// Simulate drag and drop events
act(() => {
if (chatContainer) {
fireEvent.dragEnter(chatContainer, {
dataTransfer: { files: [] },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
});
fireEvent.dragOver(chatContainer, {
dataTransfer: { files },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
});
fireEvent.drop(chatContainer, {
dataTransfer: { files },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
});
}
});
// Verify the drop was handled (no errors thrown)
expect(chatContainer).toBeInTheDocument();
});
it('handles dropping an unsupported file type', () => {
// Test that the drop handler exists and doesn't throw errors
render(
<TestApp>
<ChatPane projectId="test-project" />
</TestApp>
);
const chatContainer = screen.getByPlaceholderText(/Ask me to add features/).closest('div')?.parentElement;
expect(chatContainer).toBeInTheDocument();
const unsupportedFile = new File(['malicious content'], 'virus.exe', { type: 'application/x-executable' });
// Simulate drag and drop events - should not throw errors
act(() => {
if (chatContainer) {
fireEvent.dragEnter(chatContainer, {
dataTransfer: { files: [] },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
});
fireEvent.dragOver(chatContainer, {
dataTransfer: { files: [unsupportedFile] },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
});
fireEvent.drop(chatContainer, {
dataTransfer: { files: [unsupportedFile] },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
});
}
});
// Test passes if no errors are thrown during drop
expect(chatContainer).toBeInTheDocument();
});
it('adds visual drag-over state during drag operations', () => {
render(
<TestApp>
<ChatPane projectId="test-project" />
</TestApp>
);
const chatContainer = screen.getByPlaceholderText(/Ask me to add features/).closest('div')?.parentElement;
expect(chatContainer).toBeInTheDocument();
const _file = new File(['test content'], 'test.txt', { type: 'text/plain' });
// Simulate drag enter - should not throw errors
act(() => {
if (chatContainer) {
fireEvent.dragEnter(chatContainer, {
dataTransfer: { files: [] },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
});
}
});
// Test passes if no errors are thrown during drag operations
expect(chatContainer).toBeInTheDocument();
// Simulate drag leave
act(() => {
if (chatContainer) {
fireEvent.dragLeave(chatContainer, {
dataTransfer: { files: [] },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
relatedTarget: null, // Simulate leaving the container
});
}
});
// Test passes if no errors are thrown during drag operations
expect(chatContainer).toBeInTheDocument();
});
});
it('handles image paste from clipboard', async () => {
render(
<TestApp>
+31 -79
View File
@@ -1,6 +1,5 @@
import { useState, useRef, useEffect, forwardRef, useImperativeHandle, useMemo, useCallback } from 'react';
import { useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Skeleton } from '@/components/ui/skeleton';
@@ -33,13 +32,13 @@ import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool';
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
import { ShellTool } from '@/lib/tools/ShellTool';
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
import { Git } from '@/lib/git';
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
import { Tool } from '@/lib/tools/Tool';
import OpenAI from 'openai';
import { makeSystemPrompt } from '@/lib/system';
import { assistantContentEmpty } from '@/lib/ai-messages';
import { saveFileToTmp } from '@/lib/fileUtils';
import { useGit } from '@/hooks/useGit';
interface ChatPaneProps {
projectId: string;
@@ -68,12 +67,10 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
isBuildLoading: externalIsBuildLoading,
isDeployLoading: externalIsDeployLoading
}, ref) => {
const { t } = useTranslation();
const [input, setInput] = useState('');
const [systemPrompt, setSystemPrompt] = useState('');
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
const [isDragOver, setIsDragOver] = useState(false);
const [scrolledProjects] = useState(() => new Set<string>());
// Use external state if provided, otherwise default to false
@@ -94,13 +91,13 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const [searchParams, setSearchParams] = useSearchParams();
const { fs } = useFS();
const { git } = useGit();
const { user, metadata } = useCurrentUser();
const { models } = useProviderModels();
// Initialize AI chat with tools
const cwd = `/projects/${projectId}`;
const customTools = useMemo(() => {
const git = new Git(fs);
const baseTools = {
git_commit: new GitCommitTool(fs, cwd, git),
text_editor_view: new TextEditorViewTool(fs, cwd),
@@ -129,7 +126,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
return baseTools;
}, [fs, git, cwd, user, projectId]);
}, [fs, cwd, user, projectId]);
// Convert tools to OpenAI format
const tools = useMemo(() => {
@@ -298,6 +295,18 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
}, [projectId, scrolledProjects]);
// Also scroll on initial mount if we have a projectId
useEffect(() => {
if (projectId && !scrolledProjects.has(projectId)) {
const timer = setTimeout(() => {
scrollToBottom();
scrolledProjects.add(projectId);
}, 100);
return () => clearTimeout(timer);
}
}, []); // Empty dependency array = runs on mount
const handleFileSelect = (file: File) => {
setAttachedFiles(prev => [...prev, file]);
};
@@ -306,49 +315,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
setAttachedFiles(prev => prev.filter(file => file !== fileToRemove));
};
// Drag and drop handlers
const handleDragEnter = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(true);
};
const handleDragOver = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
if (!isDragOver) {
setIsDragOver(true);
}
};
const handleDragLeave = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
// Only reset drag state if we're actually leaving the container
// This prevents flickering when dragging over child elements
const container = e.currentTarget;
const relatedTarget = e.relatedTarget as Node;
if (!container.contains(relatedTarget)) {
setIsDragOver(false);
}
};
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(false);
if (isLoading || !providerModel.trim()) return;
const files = Array.from(e.dataTransfer.files);
if (files.length === 0) return;
// Add all files without validation
setAttachedFiles(prev => [...prev, ...files]);
};
const handleSend = async () => {
if ((!input.trim() && attachedFiles.length === 0) || isLoading || !providerModel.trim()) return;
@@ -463,12 +429,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<div className="text-center space-y-4 max-w-md mx-auto p-6">
<div className="text-4xl mb-4">🤖</div>
<div>
<h3 className="text-lg font-semibold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">{t('aiNotConfigured')}</h3>
<h3 className="text-lg font-semibold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">AI Assistant Not Configured</h3>
<p className="text-sm text-muted-foreground mb-4">
{t('configureAI')}
Please configure your AI settings to start building with AI assistance.
</p>
<p className="text-sm text-muted-foreground">
{t('useMenuForAI')}
Use the menu in the top bar to access AI Settings.
</p>
</div>
</div>
@@ -491,16 +457,16 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<div className="text-6xl mb-6">🎭</div>
<div>
<h3 className="text-xl font-semibold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
{t('welcomeToShakespeare')}
Welcome to Shakespeare
</h3>
<p className="text-muted-foreground mb-6 leading-relaxed">
{t('aiAssistantReady')}
Your AI-powered development assistant is ready to help you build, edit, and enhance your project.
</p>
<div className="space-y-2 text-sm text-muted-foreground">
<p>{t('askMeFeatures')}</p>
<p>{t('requestEdits')}</p>
<p>{t('getHelp')}</p>
<p>{t('buildDeploy')}</p>
<p>💡 Ask me to add new features</p>
<p>📝 Request file edits and improvements</p>
<p>🔧 Get help with debugging and optimization</p>
<p>🚀 Build and deploy your project</p>
</div>
</div>
</div>
@@ -535,12 +501,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
);
})}
{streamingMessage && (
streamingMessage.content || streamingMessage.reasoning_content ? (
streamingMessage.content ? (
<AIMessageItem
key="streaming-message"
message={streamingMessage}
isCurrentlyLoading={isLoading}
reasoningContent={streamingMessage.reasoning_content}
/>
) : (
!(streamingMessage?.tool_calls?.[0]?.type === 'function') && (
@@ -559,7 +524,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<div className="flex items-center gap-2 px-2 py-1 text-xs text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin flex-shrink-0" />
<span className="font-medium">
{t('running')} {streamingMessage.tool_calls?.[0]?.function?.name || 'tool'}...
Running {streamingMessage.tool_calls?.[0]?.function?.name || 'tool'}...
</span>
</div>
</div>
@@ -583,26 +548,17 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<div className="border-t p-4">
{/* Chat Input Container */}
<div
className={`flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${
isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
}`}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
<div className="flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all">
<Textarea
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onFocus={handleFirstInteraction}
placeholder={providerModel.trim() ? t('askToAddFeatures') : t('selectModelFirst')}
placeholder={providerModel.trim() ? "Ask me to add features, edit files, or build your project..." : "Please select a model to start chatting..."}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isLoading || !providerModel.trim()}
rows={1}
aria-label="Chat message input"
style={{
height: 'auto',
minHeight: '96px'
@@ -639,11 +595,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</div>
</TooltipTrigger>
<TooltipContent>
<p>{t('contextUsage', {
tokens: lastInputTokens.toLocaleString(),
total: currentModel.contextLength.toLocaleString(),
percentage: contextUsagePercentage.toFixed(1)
})}</p>
<p>Context usage: {lastInputTokens.toLocaleString()} / {currentModel.contextLength.toLocaleString()} tokens ({contextUsagePercentage.toFixed(1)}%)</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
@@ -659,7 +611,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</div>
</TooltipTrigger>
<TooltipContent>
<p>{t('totalCostSession')}</p>
<p>Total cost for this chat session</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
@@ -672,7 +624,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
onChange={setProviderModel}
className="w-full"
disabled={isLoading}
placeholder={t('chooseModel')}
placeholder="Choose a model..."
/>
</div>
+4 -6
View File
@@ -1,5 +1,4 @@
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { CardContent, CardHeader, CardTitle } from '@/components/ui/card';
@@ -16,7 +15,6 @@ interface FileEditorProps {
}
export function FileEditor({ filePath, content, onSave, isLoading, projectId }: FileEditorProps) {
const { t } = useTranslation();
const [editedContent, setEditedContent] = useState(content);
const [isSaving, setIsSaving] = useState(false);
const [hasChanges, setHasChanges] = useState(false);
@@ -101,7 +99,7 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
<CardTitle className={cn("text-sm sm:text-base truncate flex-1 mr-2", gitStatusClasses)}>{filePath}</CardTitle>
<div className="flex items-center space-x-1 sm:space-x-2">
{hasChanges && (
<span className="text-xs sm:text-sm text-muted-foreground hidden sm:inline">{t('unsavedChanges')}</span>
<span className="text-xs sm:text-sm text-muted-foreground hidden sm:inline">Unsaved changes</span>
)}
<Button
onClick={handleSave}
@@ -112,19 +110,19 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
{isSaving ? (
<>
<Loader2 className="mr-1 sm:mr-2 h-4 w-4 animate-spin" />
<span className="hidden sm:inline">{t('saving')}</span>
<span className="hidden sm:inline">Saving...</span>
</>
) : (
<>
<Save className="sm:mr-2 h-4 w-4" />
<span className="hidden sm:inline">{t('save')}</span>
<span className="hidden sm:inline">Save</span>
</>
)}
</Button>
</div>
</div>
<div className="text-xs text-muted-foreground mt-1">
{t('languageLabel')}: {getLanguageFromPath(filePath)}
Language: {getLanguageFromPath(filePath)}
</div>
</CardHeader>
+3 -5
View File
@@ -1,5 +1,4 @@
import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useFS } from '@/hooks/useFS';
import { useGitStatus } from '@/hooks/useGitStatus';
@@ -23,7 +22,6 @@ interface FileNode {
}
export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProps) {
const { t } = useTranslation();
const [tree, setTree] = useState<FileNode[]>([]);
const [filteredTree, setFilteredTree] = useState<FileNode[]>([]);
const [isLoading, setIsLoading] = useState(true);
@@ -181,7 +179,7 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
for (const node of nodes) {
if (node.type === 'file') {
const fileNameMatch = node.name.toLowerCase().includes(searchTermLower);
if (fileNameMatch) {
results.push(node);
}
@@ -298,7 +296,7 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
<div className="relative">
<Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
placeholder={t('searchFiles')}
placeholder="Search files..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-8"
@@ -315,7 +313,7 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
</div>
) : filteredTree.length === 0 ? (
<div className="text-center text-sm text-muted-foreground py-4">
{searchTerm ? t('noFilesFoundSearch') : t('noFilesFound')}
{searchTerm ? 'No files found matching your search' : 'No files found'}
</div>
) : (
filteredTree.map(node => renderNode(node))
+28 -175
View File
@@ -1,27 +1,18 @@
import { encodeBase64 } from '@std/encoding/base64';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useFS } from '@/hooks/useFS';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { FolderOpen, ArrowLeft, X, Bug, Copy, Check } from 'lucide-react';
import { FolderOpen, ArrowLeft } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { FileTree } from './FileTree';
import { FileEditor } from './FileEditor';
// Get iframe domain from environment variable
const IFRAME_DOMAIN = import.meta.env.VITE_IFRAME_DOMAIN || 'local-shakespeare.dev';
interface PreviewPaneProps {
projectId: string;
activeTab: 'preview' | 'code';
@@ -48,7 +39,7 @@ interface JSONRPCResponse {
statusText: string;
headers: Record<string, string>;
body: string | null;
}
};
error?: {
code: number;
message: string;
@@ -57,14 +48,7 @@ interface JSONRPCResponse {
id: number;
}
interface ConsoleMessage {
id: number;
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
message: string;
}
export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
const { t } = useTranslation();
const [selectedFile, setSelectedFile] = useState<string | null>(null);
const [fileContent, setFileContent] = useState<string>('');
const [isLoading, setIsLoading] = useState(false);
@@ -74,8 +58,6 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
const [currentPath, setCurrentPath] = useState('/');
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
const [historyIndex, setHistoryIndex] = useState(0);
const [consoleMessages, setConsoleMessages] = useState<ConsoleMessage[]>([]);
const [copiedMessageId, setCopiedMessageId] = useState<number | null>(null);
const iframeRef = useRef<HTMLIFrameElement>(null);
const { fs } = useFS();
const projectsManager = useProjectsManager();
@@ -145,7 +127,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
const navigateToPath = useCallback((path: string) => {
if (iframeRef.current) {
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
const baseUrl = `https://${projectId}.local-shakespeare.dev`;
const newUrl = `${baseUrl}${path}`;
iframeRef.current.src = newUrl;
setCurrentPath(path);
@@ -166,7 +148,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
setCurrentPath(path);
if (iframeRef.current) {
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
const baseUrl = `https://${projectId}.local-shakespeare.dev`;
const newUrl = `${baseUrl}${path}`;
iframeRef.current.src = newUrl;
}
@@ -181,7 +163,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
setCurrentPath(path);
if (iframeRef.current) {
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
const baseUrl = `https://${projectId}.local-shakespeare.dev`;
const newUrl = `${baseUrl}${path}`;
iframeRef.current.src = newUrl;
}
@@ -191,46 +173,18 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
const sendResponse = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
console.log(`Sending response to iframe:`, message);
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
const targetOrigin = `https://${projectId}.local-shakespeare.dev`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
}
}, [projectId]);
const sendError = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
const targetOrigin = `https://${projectId}.local-shakespeare.dev`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
}
}, [projectId]);
const handleConsoleMessage = useCallback((message: {
jsonrpc: '2.0';
method: 'console';
params: {
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
message: string;
};
}) => {
const { params } = message;
// Normalize level to ensure it's one of our supported types
let normalizedLevel: ConsoleMessage['level'] = 'log';
if (['log', 'warn', 'error', 'info', 'debug'].includes(params.level)) {
normalizedLevel = params.level as ConsoleMessage['level'];
}
const newConsoleMessage: ConsoleMessage = {
id: Date.now(),
level: normalizedLevel,
message: params.message,
};
setConsoleMessages(prev => [...prev, newConsoleMessage]);
// Log to parent console for debugging with appropriate level
console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`);
}, []);
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
const { params, id } = request;
const { request: fetchRequest } = params;
@@ -240,7 +194,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
try {
// Parse the URL and validate origin
const url = new URL(fetchRequest.url);
const expectedOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
const expectedOrigin = `https://${projectId}.local-shakespeare.dev`;
if (url.origin !== expectedOrigin) {
console.log(`Invalid origin: ${url.origin}, expected: ${expectedOrigin}`);
@@ -336,7 +290,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
// Verify origin for security
const expectedOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
const expectedOrigin = `https://${projectId}.local-shakespeare.dev`;
if (event.origin !== expectedOrigin) {
console.log(`Ignoring message from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`);
return;
@@ -346,14 +300,12 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
console.log('Received message from iframe:', message);
if (message.jsonrpc === '2.0' && message.method === 'fetch') {
handleFetch(message);
} else if (message.jsonrpc === '2.0' && message.method === 'console') {
handleConsoleMessage(message);
}
};
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, [handleFetch, handleConsoleMessage, projectId]);
}, [handleFetch, projectId]);
useEffect(() => {
if (selectedFile) {
@@ -398,123 +350,24 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
}
};
const ConsoleDropdown = () => {
const getLevelColor = (level: ConsoleMessage['level']) => {
switch (level) {
case 'error': return 'text-red-500';
case 'warn': return 'text-yellow-500';
case 'info': return 'text-blue-500';
case 'debug': return 'text-gray-500';
default: return 'text-gray-400';
}
};
const getLevelIcon = (level: ConsoleMessage['level']) => {
switch (level) {
case 'error': return '!';
case 'warn': return '⚠';
case 'info': return 'ℹ';
case 'debug': return '🔍';
default: return '•';
}
};
const clearConsole = () => {
setConsoleMessages([]);
};
const copyMessageToClipboard = async (msg: ConsoleMessage) => {
try {
// Create a formatted string with all message details
const formattedMessage = `[${msg.level.toUpperCase()}] ${msg.message}`;
await navigator.clipboard.writeText(formattedMessage);
setCopiedMessageId(msg.id);
// Reset the copied state after 2 seconds
setTimeout(() => {
setCopiedMessageId(null);
}, 2000);
} catch (error) {
console.error('Failed to copy message to clipboard:', error);
}
};
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm" className="h-8 w-8 p-0 relative">
<Bug className="h-4 w-4" />
{consoleMessages.some(msg => msg.level === 'error') && (
<span className="absolute bottom-0 left-0 h-2 w-2 bg-red-500 rounded-full"></span>
)}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-96 max-w-96 max-h-96 overflow-x-hidden">
<div className="flex items-center justify-between p-2 border-b">
<span className="font-medium text-sm">Console Output ({consoleMessages.length})</span>
<Button variant="ghost" size="sm" onClick={clearConsole}>
<X className="h-3 w-3" />
</Button>
</div>
<ScrollArea className="h-80 w-full max-w-full overflow-x-hidden">
<div className="space-y-1 p-2 w-full max-w-full overflow-x-hidden">
{consoleMessages.length === 0 ? (
<div className="text-center text-muted-foreground text-sm py-4">
No console messages
</div>
) : (
consoleMessages.map((msg) => (
<div
key={msg.id}
className={`text-xs font-mono p-2 rounded ${getLevelColor(msg.level)} bg-muted/50 group relative w-full overflow-hidden`}
>
<div className="flex items-start justify-between w-full">
<div className="whitespace-pre-wrap break-all flex-1 pr-2 overflow-x-hidden">{getLevelIcon(msg.level)} {msg.message}</div>
<Button
variant="ghost"
size="sm"
onClick={() => copyMessageToClipboard(msg)}
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex-shrink-0"
>
{copiedMessageId === msg.id ? (
<Check className="h-3 w-3 text-green-500" />
) : (
<Copy className="h-3 w-3" />
)}
</Button>
</div>
</div>
))
)}
</div>
</ScrollArea>
</DropdownMenuContent>
</DropdownMenu>
);
};
return (
<div className="h-full">
<Tabs value={activeTab} className="h-full">
<TabsContent value="preview" className="h-full mt-0">
{hasBuiltProject ? (
<div className="h-full w-full flex flex-col">
<div className="flex items-center border-b w-full">
<BrowserAddressBar
currentPath={currentPath}
onNavigate={navigateToPath}
onRefresh={refreshIframe}
onBack={goBack}
onForward={goForward}
canGoBack={historyIndex > 0}
canGoForward={historyIndex < navigationHistory.length - 1}
extraContent={<ConsoleDropdown />}
/>
</div>
<BrowserAddressBar
currentPath={currentPath}
onNavigate={navigateToPath}
onRefresh={refreshIframe}
onBack={goBack}
onForward={goForward}
canGoBack={historyIndex > 0}
canGoForward={historyIndex < navigationHistory.length - 1}
/>
<iframe
ref={iframeRef}
src={`https://${projectId}.${IFRAME_DOMAIN}${currentPath}`}
src={`https://${projectId}.local-shakespeare.dev${currentPath}`}
className="w-full flex-1 border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin"
@@ -523,9 +376,9 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
) : (
<div className="h-full flex items-center justify-center bg-muted">
<div className="text-center">
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
<h3 className="text-lg font-semibold mb-2">Project Preview</h3>
<p className="text-muted-foreground mb-4">
{t('buildProjectToSeePreview')}
Build your project to see the preview here
</p>
</div>
</div>
@@ -539,7 +392,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
<>
<div className="p-3 border-b bg-gradient-to-r from-primary/5 to-accent/5">
<div className="flex items-center justify-between">
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">{t('fileExplorer')}</h3>
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">File Explorer</h3>
<GitStatusIndicator projectId={projectId} />
</div>
</div>
@@ -566,7 +419,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
<ArrowLeft className="h-4 w-4" />
</Button>
<h3 className="font-semibold flex-1 truncate bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
{selectedFile ? selectedFile.split('/').pop() : t('fileEditor')}
{selectedFile ? selectedFile.split('/').pop() : 'File Editor'}
</h3>
<GitStatusIndicator projectId={projectId} />
</div>
@@ -584,7 +437,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
<div className="text-center">
<FolderOpen className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
<p className="text-muted-foreground">
{t('selectFileFromExplorer')}
Select a file from the explorer to edit
</p>
<Button
variant="outline"
@@ -592,7 +445,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
onClick={() => setMobileCodeView('explorer')}
className="mt-4"
>
{t('openFileExplorer')}
Open File Explorer
</Button>
</div>
</div>
@@ -606,7 +459,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
<div className="w-1/3 border-r">
<div className="p-4 border-b bg-gradient-to-r from-primary/5 to-accent/5">
<div className="flex items-center justify-between">
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">{t('fileExplorer')}</h3>
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">File Explorer</h3>
<GitStatusIndicator projectId={projectId} />
</div>
</div>
@@ -635,7 +488,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
<div className="h-full flex items-center justify-center">
<div className="text-center">
<p className="text-muted-foreground">
{t('selectFileFromExplorer')}
Select a file from the explorer to edit
</p>
</div>
</div>
-57
View File
@@ -1,57 +0,0 @@
import { ChevronsUpDown, Monitor, Moon, Sun } from "lucide-react";
import { useTranslation } from 'react-i18next';
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useTheme } from "@/hooks/useTheme";
import { type Theme } from "@/contexts/AppContext";
export function ThemePicker() {
const { t } = useTranslation();
const { theme, setTheme } = useTheme();
const themeOptions: { value: Theme; label: string; icon: React.ComponentType<{ className?: string }> }[] = [
{ value: "system", label: t('system'), icon: Monitor },
{ value: "light", label: t('light'), icon: Sun },
{ value: "dark", label: t('dark'), icon: Moon },
];
const currentTheme = themeOptions.find(option => option.value === theme);
const CurrentIcon = currentTheme?.icon || Monitor;
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="w-full justify-between">
<div className="flex items-center gap-2">
<CurrentIcon className="h-4 w-4" />
<span>{currentTheme?.label || t('system')}</span>
</div>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-[180px]">
{themeOptions.map((option) => {
const Icon = option.icon;
return (
<DropdownMenuItem
key={option.value}
onClick={() => setTheme(option.value)}
className="flex items-center gap-2"
>
<Icon className="h-4 w-4" />
<span>{option.label}</span>
{theme === option.value && (
<div className="ml-auto h-2 w-2 rounded-full bg-primary" />
)}
</DropdownMenuItem>
);
})}
</DropdownMenuContent>
</DropdownMenu>
);
}
+1 -1
View File
@@ -43,8 +43,8 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
const setIsOpen = onOpenChange || setInternalOpen;
const [isRollingBack, setIsRollingBack] = useState<string | null>(null);
const [expandedCommits, setExpandedCommits] = useState<Set<string>>(new Set());
const git = useGit();
const { fs } = useFS();
const { git } = useGit();
const { toast } = useToast();
const loadGitHistory = useCallback(async () => {
@@ -1,65 +0,0 @@
import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import { AccountSwitcher } from './AccountSwitcher';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
// Mock the hooks
vi.mock('@/hooks/useLoggedInAccounts');
vi.mock('react-router-dom', () => ({
useNavigate: () => vi.fn()
}));
// Mock the RelaySelector component
vi.mock('@/components/RelaySelector', () => ({
RelaySelector: ({ className }: { className?: string }) => (
<div data-testid="relay-selector" className={className}>Relay Selector</div>
)
}));
const mockUseLoggedInAccounts = vi.mocked(useLoggedInAccounts);
describe('AccountSwitcher', () => {
it('renders account switcher with dropdown trigger', () => {
mockUseLoggedInAccounts.mockReturnValue({
authors: [{
id: 'user1',
pubkey: 'pubkey1',
metadata: { name: 'Test User' }
}],
currentUser: {
id: 'user1',
pubkey: 'pubkey1',
metadata: { name: 'Test User' }
},
otherUsers: [],
setLogin: vi.fn(),
removeLogin: vi.fn(),
isLoading: false
});
render(<AccountSwitcher onAddAccountClick={vi.fn()} />);
// Should show the user's name
expect(screen.getByText('Test User')).toBeInTheDocument();
// Should show dropdown trigger button
expect(screen.getByRole('button')).toBeInTheDocument();
});
it('returns null when no current user', () => {
mockUseLoggedInAccounts.mockReturnValue({
authors: [],
currentUser: undefined,
otherUsers: [],
setLogin: vi.fn(),
removeLogin: vi.fn(),
isLoading: false
});
const { container } = render(<AccountSwitcher onAddAccountClick={vi.fn()} />);
expect(container.firstChild).toBeNull();
});
});
+23 -39
View File
@@ -1,7 +1,7 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { ChevronDown, LogOut, UserIcon, UserPlus, Settings, HelpCircle } from 'lucide-react';
import { ChevronDown, LogOut, UserIcon, UserPlus } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
@@ -10,9 +10,9 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu.tsx';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
import { RelaySelector } from '@/components/RelaySelector';
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
import { genUserName } from '@/lib/genUserName';
import { useNavigate } from 'react-router-dom';
interface AccountSwitcherProps {
onAddAccountClick: () => void;
@@ -20,7 +20,6 @@ interface AccountSwitcherProps {
export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
const { currentUser, otherUsers, setLogin, removeLogin } = useLoggedInAccounts();
const navigate = useNavigate();
if (!currentUser) return null;
@@ -43,42 +42,27 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
</button>
</DropdownMenuTrigger>
<DropdownMenuContent className='w-56 p-2 animate-scale-in'>
{otherUsers.length > 0 && (
<>
<div className='font-medium text-sm px-2 py-1.5'>Switch Account</div>
{otherUsers.map((user) => (
<DropdownMenuItem
key={user.id}
onClick={() => setLogin(user.id)}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
>
<Avatar className='w-8 h-8'>
<AvatarImage src={user.metadata.picture} alt={getDisplayName(user)} />
<AvatarFallback>{getDisplayName(user)?.charAt(0) || <UserIcon />}</AvatarFallback>
</Avatar>
<div className='flex-1 truncate'>
<p className='text-sm font-medium'>{getDisplayName(user)}</p>
</div>
{user.id === currentUser.id && <div className='w-2 h-2 rounded-full bg-primary'></div>}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
</>
)}
<DropdownMenuItem
onClick={() => navigate('/settings')}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
>
<Settings className='w-4 h-4' />
<span>Settings</span>
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => window.open('https://soapbox.pub/shakespeare-resources/', '_blank')}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
>
<HelpCircle className='w-4 h-4' />
<span>Help</span>
</DropdownMenuItem>
<div className='font-medium text-sm px-2 py-1.5'>Switch Relay</div>
<RelaySelector className="w-full" />
<DropdownMenuSeparator />
<div className='font-medium text-sm px-2 py-1.5'>Switch Account</div>
{otherUsers.map((user) => (
<DropdownMenuItem
key={user.id}
onClick={() => setLogin(user.id)}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
>
<Avatar className='w-8 h-8'>
<AvatarImage src={user.metadata.picture} alt={getDisplayName(user)} />
<AvatarFallback>{getDisplayName(user)?.charAt(0) || <UserIcon />}</AvatarFallback>
</Avatar>
<div className='flex-1 truncate'>
<p className='text-sm font-medium'>{getDisplayName(user)}</p>
</div>
{user.id === currentUser.id && <div className='w-2 h-2 rounded-full bg-primary'></div>}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={onAddAccountClick}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
-116
View File
@@ -1,116 +0,0 @@
import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import { LoginArea } from './LoginArea';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
// Mock the hooks
vi.mock('@/hooks/useLoggedInAccounts');
vi.mock('@/hooks/useAppContext', () => ({
useAppContext: () => ({
config: { relayUrl: 'wss://relay.damus.io' },
updateConfig: vi.fn(),
presetRelays: [
{ name: 'Damus', url: 'wss://relay.damus.io' }
]
})
}));
// Mock the components
vi.mock('./AccountSwitcher', () => ({
AccountSwitcher: ({ onAddAccountClick }: { onAddAccountClick: () => void }) => (
<div data-testid="account-switcher">
<button onClick={onAddAccountClick}>Add Account</button>
</div>
)
}));
// Mock react-router-dom
vi.mock('react-router-dom', () => ({
useNavigate: () => vi.fn()
}));
vi.mock('@/components/RelaySelector', () => ({
RelaySelector: ({ className }: { className?: string }) => (
<div data-testid="relay-selector" className={className}>Relay Selector</div>
)
}));
vi.mock('./SimpleLoginDialog', () => ({
default: ({ isOpen }: { isOpen: boolean; onClose: () => void }) =>
isOpen ? <div data-testid="login-dialog">Login Dialog</div> : null
}));
vi.mock('./SimpleSignupDialog', () => ({
default: ({ isOpen }: { isOpen: boolean; onClose: () => void }) =>
isOpen ? <div data-testid="signup-dialog">Signup Dialog</div> : null
}));
const mockUseLoggedInAccounts = vi.mocked(useLoggedInAccounts);
describe('LoginArea', () => {
it('shows AccountSwitcher when user is logged in', () => {
mockUseLoggedInAccounts.mockReturnValue({
authors: [{
id: 'user1',
pubkey: 'pubkey1',
metadata: { name: 'Test User' }
}],
currentUser: {
id: 'user1',
pubkey: 'pubkey1',
metadata: { name: 'Test User' }
},
otherUsers: [],
setLogin: vi.fn(),
removeLogin: vi.fn(),
isLoading: false
});
render(<LoginArea />);
expect(screen.getByTestId('account-switcher')).toBeInTheDocument();
});
it('maintains consistent layout structure whether logged in or not', () => {
// Test logged out state
mockUseLoggedInAccounts.mockReturnValue({
authors: [],
currentUser: undefined,
otherUsers: [],
setLogin: vi.fn(),
removeLogin: vi.fn(),
isLoading: false
});
const { rerender } = render(<LoginArea />);
const loggedOutContainer = screen.getByRole('button');
expect(loggedOutContainer).toHaveClass('flex', 'items-center', 'gap-3', 'p-3', 'rounded-full');
// Test logged in state
mockUseLoggedInAccounts.mockReturnValue({
authors: [{
id: 'user1',
pubkey: 'pubkey1',
metadata: { name: 'Test User' }
}],
currentUser: {
id: 'user1',
pubkey: 'pubkey1',
metadata: { name: 'Test User' }
},
otherUsers: [],
setLogin: vi.fn(),
removeLogin: vi.fn(),
isLoading: false
});
rerender(<LoginArea />);
// Both states should maintain similar structure
expect(screen.getByTestId('account-switcher')).toBeInTheDocument();
});
});
+22 -67
View File
@@ -2,31 +2,20 @@
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { User, UserPlus, ChevronDown, Settings, HelpCircle } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu.tsx';
import { Avatar, AvatarFallback } from '@/components/ui/avatar.tsx';
import SimpleLoginDialog from './SimpleLoginDialog';
import SimpleSignupDialog from './SimpleSignupDialog';
import { User, UserPlus } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx';
import LoginDialog from './LoginDialog';
import SignupDialog from './SignupDialog';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
import { AccountSwitcher } from './AccountSwitcher';
import { cn } from '@/lib/utils';
import { useNavigate } from 'react-router-dom';
export interface LoginAreaProps {
className?: string;
}
export function LoginArea({ className }: LoginAreaProps) {
const { t } = useTranslation();
const { currentUser } = useLoggedInAccounts();
const navigate = useNavigate();
const [loginDialogOpen, setLoginDialogOpen] = useState(false);
const [signupDialogOpen, setSignupDialogOpen] = useState(false);
@@ -40,68 +29,34 @@ export function LoginArea({ className }: LoginAreaProps) {
{currentUser ? (
<AccountSwitcher onAddAccountClick={() => setLoginDialogOpen(true)} />
) : (
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<button className='flex items-center gap-3 p-3 rounded-full hover:bg-accent transition-all w-full text-foreground'>
<Avatar className='w-10 h-10'>
<AvatarFallback>
<User className='w-5 h-5 text-muted-foreground' />
</AvatarFallback>
</Avatar>
<div className='flex-1 text-left truncate'>
<p className='font-medium text-sm truncate'>{t('anonymous')}</p>
</div>
<ChevronDown className='w-4 h-4 text-muted-foreground' />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent className='w-56 p-2 animate-scale-in'>
<DropdownMenuItem
onClick={() => navigate('/settings')}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
>
<Settings className='w-4 h-4' />
<span>{t('settings')}</span>
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => window.open('https://soapbox.pub/shakespeare-resources/', '_blank')}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
>
<HelpCircle className='w-4 h-4' />
<span>{t('help')}</span>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => setSignupDialogOpen(true)}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
>
<UserPlus className='w-4 h-4' />
<span>{t('signUp')}</span>
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setLoginDialogOpen(true)}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
>
<User className='w-4 h-4' />
<span>{t('logIn')}</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<div className="flex gap-3 justify-center">
<Button
onClick={() => setLoginDialogOpen(true)}
className='flex items-center gap-2 px-4 py-2 rounded-full bg-primary text-primary-foreground w-full font-medium transition-all hover:bg-primary/90 animate-scale-in'
>
<User className='w-4 h-4' />
<span className='truncate'>Log in</span>
</Button><Button
onClick={() => setSignupDialogOpen(true)}
variant="outline"
className="flex items-center gap-2 px-4 py-2 rounded-full font-medium transition-all"
>
<UserPlus className="w-4 h-4" />
<span>Sign Up</span>
</Button>
</div>
)}
<SimpleLoginDialog
<LoginDialog
isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)}
onLogin={handleLogin}
onSignup={() => setSignupDialogOpen(true)}
/>
<SimpleSignupDialog
<SignupDialog
isOpen={signupDialogOpen}
onClose={() => setSignupDialogOpen(false)}
onLogin={() => {
setSignupDialogOpen(false);
setLoginDialogOpen(true);
}}
/>
</div>
);
-285
View File
@@ -1,285 +0,0 @@
import React, { useState, useEffect } from 'react';
import { Cloud } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
// Alert components removed as they're not used in the simplified design
import { useLoginActions } from '@/hooks/useLoginActions';
import { cn } from '@/lib/utils';
// Only using key-add step now
interface SimpleLoginDialogProps {
isOpen: boolean;
onClose: () => void;
onLogin: () => void;
onSignup?: () => void;
}
const validateNsec = (nsec: string) => {
return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec);
};
const validateBunkerUri = (uri: string) => {
return uri.startsWith('bunker://');
};
const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
isOpen,
onClose,
onLogin,
onSignup
}) => {
// Removed step state - we only have one step now
const [isLoading, setIsLoading] = useState(false);
const [nsec, setNsec] = useState('');
const [bunkerUri, setBunkerUri] = useState('');
const [activeTab, setActiveTab] = useState<'nsec' | 'bunker'>('nsec');
const [errors, setErrors] = useState<{
nsec?: string;
bunker?: string;
extension?: string;
}>({});
const login = useLoginActions();
// Reset state when dialog opens/closes
useEffect(() => {
if (isOpen) {
setIsLoading(false);
setNsec('');
setBunkerUri('');
setActiveTab('nsec');
setErrors({});
}
}, [isOpen]);
const handleExtensionLogin = async () => {
setIsLoading(true);
setErrors(prev => ({ ...prev, extension: undefined }));
try {
if (!('nostr' in window)) {
throw new Error('Nostr extension not found. Please install a NIP-07 extension.');
}
await login.extension();
onLogin();
onClose();
} catch (e: unknown) {
const error = e as Error;
setErrors(prev => ({
...prev,
extension: error instanceof Error ? error.message : 'Extension login failed'
}));
} finally {
setIsLoading(false);
}
};
const handleKeyLogin = () => {
if (!nsec.trim()) {
setErrors(prev => ({ ...prev, nsec: 'Please enter your secret key' }));
return;
}
if (!validateNsec(nsec)) {
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
return;
}
setIsLoading(true);
setErrors({});
setTimeout(() => {
try {
login.nsec(nsec);
onLogin();
onClose();
} catch {
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
setIsLoading(false);
}
}, 50);
};
const handleBunkerLogin = async () => {
if (!bunkerUri.trim()) {
setErrors(prev => ({ ...prev, bunker: 'Please enter a bunker URI' }));
return;
}
if (!validateBunkerUri(bunkerUri)) {
setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' }));
return;
}
setIsLoading(true);
setErrors(prev => ({ ...prev, bunker: undefined }));
try {
await login.bunker(bunkerUri);
onLogin();
onClose();
setBunkerUri('');
} catch {
setErrors(prev => ({
...prev,
bunker: 'Failed to connect to bunker. Please check the URI.'
}));
} finally {
setIsLoading(false);
}
};
const handleSignupClick = () => {
onClose();
if (onSignup) {
onSignup();
}
};
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-sm">
<DialogHeader>
<DialogTitle className="text-center">Log in</DialogTitle>
</DialogHeader>
<div className="flex flex-col items-center space-y-6 py-6">
<div className="text-center">
<h3 className="font-semibold mb-2">Welcome back to Shakespeare</h3>
<p className="text-sm text-muted-foreground">Sign in to your existing account</p>
</div>
<div className="w-40 h-40 flex items-center justify-center">
<div className="w-40 h-40 bg-primary/10 rounded-full flex items-center justify-center">
<span className="text-8xl">🔑</span>
</div>
</div>
<div className="w-full space-y-4">
{/* Tab selector */}
<div className="flex space-x-1 bg-muted rounded-lg p-1">
<button
onClick={() => setActiveTab('nsec')}
className={cn(
"flex-1 px-3 py-2 text-sm font-medium rounded-md transition-colors",
activeTab === 'nsec'
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground"
)}
>
Secret Key
</button>
<button
onClick={() => setActiveTab('bunker')}
className={cn(
"flex-1 px-3 py-2 text-sm font-medium rounded-md transition-colors",
activeTab === 'bunker'
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground"
)}
>
Bunker
</button>
</div>
{activeTab === 'nsec' && (
<div className="space-y-4">
<div className="space-y-2">
<Input
type="password"
value={nsec}
onChange={(e) => {
setNsec(e.target.value);
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
}}
placeholder="nsec1..."
className={errors.nsec ? 'border-red-500' : ''}
/>
{errors.nsec && (
<p className="text-sm text-red-500">{errors.nsec}</p>
)}
</div>
<Button
size="lg"
onClick={handleKeyLogin}
disabled={isLoading || !nsec.trim()}
className="w-full"
>
{isLoading ? 'Verifying...' : 'Add Key'}
</Button>
</div>
)}
{activeTab === 'bunker' && (
<div className="space-y-4">
<div className="space-y-2">
<Input
value={bunkerUri}
onChange={(e) => {
setBunkerUri(e.target.value);
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
}}
placeholder="bunker://"
className={errors.bunker ? 'border-red-500' : ''}
/>
{errors.bunker && (
<p className="text-sm text-red-500">{errors.bunker}</p>
)}
</div>
<Button
size="lg"
onClick={handleBunkerLogin}
disabled={isLoading || !bunkerUri.trim()}
className="w-full"
>
<Cloud className="w-4 h-4 mr-2" />
{isLoading ? 'Connecting...' : 'Connect'}
</Button>
</div>
)}
<div className="relative">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t"></div>
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-background px-2 text-muted-foreground">or</span>
</div>
</div>
{/* Extension indicator - only show if extension is detected */}
{window.nostr && (
<div className="rounded-lg bg-muted p-3">
<p className="text-xs text-center">
<button
onClick={handleExtensionLogin}
className="text-blue-500 hover:underline"
disabled={isLoading}
>
Sign in with browser extension
</button>
</p>
</div>
)}
<div className="flex justify-center space-x-2 text-xs">
<span className="text-muted-foreground">New to Shakespeare?</span>
<button
onClick={handleSignupClick}
className="text-blue-500 hover:underline"
>
Create Account
</button>
</div>
</div>
</div>
</DialogContent>
</Dialog>
);
};
export default SimpleLoginDialog;
-263
View File
@@ -1,263 +0,0 @@
import React, { useState, useEffect, useMemo } from 'react';
import { Download, UserPlus } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { toast } from '@/hooks/useToast';
import { useLoginActions } from '@/hooks/useLoginActions';
import { generateSecretKey, nip19 } from 'nostr-tools';
import { cn } from '@/lib/utils';
type Step = 'key' | 'keygen';
interface SimpleSignupDialogProps {
isOpen: boolean;
onClose: () => void;
onComplete?: () => void;
onLogin?: () => void;
}
const SimpleSignupDialog: React.FC<SimpleSignupDialogProps> = ({
isOpen,
onClose,
onComplete,
onLogin
}) => {
const [step, setStep] = useState<Step>('key');
const [isLoading, setIsLoading] = useState(false);
const [downloaded, setDownloaded] = useState(false);
const login = useLoginActions();
// Generate key once and keep it stable
const secretKey = useMemo(() => generateSecretKey(), []);
const nsec = useMemo(() => nip19.nsecEncode(secretKey), [secretKey]);
// Reset state when dialog opens/closes
useEffect(() => {
if (isOpen) {
// Always start with key generation as the default experience
setStep('key');
setIsLoading(false);
setDownloaded(false);
}
}, [isOpen]);
const handleExtensionSignup = async () => {
setIsLoading(true);
try {
if (!('nostr' in window)) {
throw new Error('Nostr extension not found. Please install a NIP-07 extension.');
}
await login.extension();
onClose();
if (onComplete) {
setTimeout(() => {
onComplete();
}, 600);
}
} catch (e: unknown) {
const error = e as Error;
toast({
title: 'Extension signup failed',
description: error instanceof Error ? error.message : 'Extension signup failed',
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
};
const handleDownload = () => {
try {
const blob = new Blob([nsec], { type: 'text/plain; charset=utf-8' });
const url = globalThis.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'secret-key.txt';
a.style.display = 'none';
document.body.appendChild(a);
a.click();
globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a);
setDownloaded(true);
toast({
title: 'Secret Key Saved!',
description: 'Your key has been safely stored.',
});
} catch {
toast({
title: 'Download failed',
description: 'Could not download the key file. Please copy it manually.',
variant: 'destructive',
});
}
};
const handleNext = async () => {
setIsLoading(true);
try {
login.nsec(nsec);
// Mark signup completion time for fallback welcome modal
localStorage.setItem('signup_completed', Date.now().toString());
onClose();
if (onComplete) {
setTimeout(() => {
onComplete();
}, 600);
}
} catch {
toast({
title: 'Login Failed',
description: 'Failed to login with the generated key. Please try again.',
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
};
const handleLoginClick = () => {
onClose();
if (onLogin) {
onLogin();
}
};
if (step === 'key') {
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-sm">
<DialogHeader>
<DialogTitle className="text-center">Sign up</DialogTitle>
</DialogHeader>
<div className="flex flex-col items-center space-y-6 py-6">
<div className="text-center">
<h3 className="font-semibold mb-2">Welcome to Shakespeare</h3>
<p className="text-sm text-muted-foreground">Create your account to get started</p>
</div>
<div className="w-40 h-40 flex items-center justify-center">
<div className="w-40 h-40 bg-primary/10 rounded-full flex items-center justify-center">
<span className="text-8xl">🔑</span>
</div>
</div>
<div className="flex flex-col space-y-3 w-full">
<Button
size="lg"
onClick={() => setStep('keygen')}
className="w-full"
>
<UserPlus className="w-4 h-4 mr-2" />
Create New Account
</Button>
<Button
variant="outline"
onClick={handleLoginClick}
className="w-full"
>
I already have an account
</Button>
</div>
{/* Extension indicator - only show if extension is detected */}
{window.nostr && (
<>
<div className="relative w-full">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t"></div>
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-background px-2 text-muted-foreground">or</span>
</div>
</div>
<div className="rounded-lg bg-muted p-3 w-full">
<p className="text-xs text-center">
<button
onClick={handleExtensionSignup}
className="text-blue-500 hover:underline"
disabled={isLoading}
>
Sign up with browser extension
</button>
</p>
</div>
</>
)}
</div>
</DialogContent>
</Dialog>
);
}
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-sm">
<DialogHeader>
<DialogTitle className="text-center">Your new key</DialogTitle>
</DialogHeader>
<div className="flex flex-col items-center space-y-6 py-6">
<div className="w-40 h-40 flex items-center justify-center">
<div className="w-40 h-40 bg-primary/10 rounded-full flex items-center justify-center">
<span className="text-8xl">🔑</span>
</div>
</div>
<div className="w-full space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium">Secret Key</label>
<Input
type="password"
value={nsec}
readOnly
className="font-mono"
/>
</div>
<div className="rounded-xl bg-muted p-4">
<p className="text-xs text-justify">
Back up your secret key in a secure place. If lost, your account cannot be recovered.
Never share your secret key with anyone.
</p>
</div>
<div className="flex space-x-3 justify-center">
<Button
variant="outline"
size="lg"
onClick={handleDownload}
className="flex-1"
>
<Download className="w-4 h-4 mr-2" />
Download key
</Button>
<Button
size="lg"
onClick={handleNext}
disabled={!downloaded || isLoading}
className={cn(
"flex-1",
!downloaded && "opacity-50 cursor-not-allowed"
)}
title={!downloaded ? "Download your key to continue" : ""}
>
{isLoading ? 'Setting up...' : 'Next'}
</Button>
</div>
</div>
</div>
</DialogContent>
</Dialog>
);
};
export default SimpleSignupDialog;
+3 -9
View File
@@ -3,7 +3,6 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { ChevronLeft, ChevronRight, RefreshCw } from 'lucide-react';
import { cn } from '@/lib/utils';
import { ReactNode } from 'react';
interface BrowserAddressBarProps {
currentPath?: string;
@@ -14,7 +13,6 @@ interface BrowserAddressBarProps {
canGoBack?: boolean;
canGoForward?: boolean;
className?: string;
extraContent?: ReactNode;
}
export function BrowserAddressBar({
@@ -26,19 +24,18 @@ export function BrowserAddressBar({
canGoBack = false,
canGoForward = false,
className,
extraContent,
}: BrowserAddressBarProps) {
const [inputValue, setInputValue] = useState(currentPath);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
let path = inputValue.trim();
// Ensure path starts with /
if (!path.startsWith('/')) {
path = '/' + path;
}
onNavigate?.(path);
};
@@ -48,7 +45,7 @@ export function BrowserAddressBar({
return (
<div className={cn(
"flex items-center gap-1 p-2 border-b bg-background w-full",
"flex items-center gap-1 p-2 border-b bg-background",
className
)}>
{/* Navigation buttons */}
@@ -94,9 +91,6 @@ export function BrowserAddressBar({
className="h-8 bg-muted/50 border-muted-foreground/20 focus:bg-background"
/>
</form>
{/* Extra content */}
{extraContent}
</div>
);
}
+1 -3
View File
@@ -65,9 +65,7 @@ export function FileAttachment({
size="sm"
onClick={handleButtonClick}
disabled={disabled}
className="h-8 w-8 p-0 rounded-full hover:bg-muted/50 dark:hover:text-sidebar-primary"
aria-label="Attach files"
data-testid="paperclip-button"
className="h-8 w-8 p-0 rounded-full hover:bg-muted/50"
>
<Paperclip className="h-4 w-4" />
</Button>
-48
View File
@@ -1,48 +0,0 @@
import * as React from "react"
import { Eye, EyeOff } from "lucide-react"
import { cn } from "@/lib/utils"
const PasswordInput = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>(
({ className, ...props }, ref) => {
const [showPassword, setShowPassword] = React.useState(false)
const [isFocused, setIsFocused] = React.useState(false)
return (
<div className={cn("relative", className)}>
<input
type={showPassword ? "text" : "password"}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 pr-10 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
isFocused && "ring-2 ring-ring ring-offset-2"
)}
ref={ref}
onFocus={(e) => {
setIsFocused(true)
props.onFocus?.(e)
}}
onBlur={(e) => {
setIsFocused(false)
props.onBlur?.(e)
}}
{...props}
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 rounded-sm disabled:cursor-not-allowed disabled:opacity-50"
disabled={props.disabled}
aria-label={showPassword ? "Hide password" : "Show password"}
>
{showPassword ? (
<EyeOff className="h-4 w-4" />
) : (
<Eye className="h-4 w-4" />
)}
</button>
</div>
)
}
)
PasswordInput.displayName = "PasswordInput"
export { PasswordInput }
+5 -6
View File
@@ -1,23 +1,22 @@
import { createContext } from 'react';
export interface AIProvider {
id: string;
export interface AIConnection {
baseURL: string;
apiKey?: string;
nostr?: boolean;
}
export interface AISettings {
providers: AIProvider[];
providers: Record<string, AIConnection>;
recentlyUsedModels: string[];
}
export interface AISettingsContextType {
settings: AISettings;
updateSettings: (settings: Partial<AISettings>) => void;
setProvider: (provider: AIProvider) => void;
removeProvider: (id: string) => void;
setProviders: (providers: AIProvider[]) => void;
addProvider: (name: string, connection: AIConnection) => void;
removeProvider: (name: string) => void;
updateProvider: (name: string, connection: Partial<AIConnection>) => void;
addRecentlyUsedModel: (modelId: string) => void;
isConfigured: boolean;
}
-5
View File
@@ -1,7 +1,6 @@
import { createContext } from "react";
export type Theme = "dark" | "light" | "system";
export type FilesystemType = "lightningfs" | "opfs";
export interface AppConfig {
/** Current theme */
@@ -10,10 +9,6 @@ export interface AppConfig {
relayUrl: string;
/** Deploy server domain (e.g., "shakespeare.wtf") */
deployServer: string;
/** Selected language */
language?: string;
/** Filesystem type to use */
filesystemType: FilesystemType;
}
export interface AppContextType {
+1 -4
View File
@@ -18,7 +18,6 @@ interface UseAIChatSessionOptions {
interface StreamingMessage {
role: 'assistant';
content: string;
reasoning_content?: string;
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
}
@@ -69,18 +68,16 @@ export function useAIChat({
setStreamingMessage({
role: 'assistant',
content: '',
reasoning_content: '',
});
}
}
}, [projectId]);
useSessionSubscription('streamingUpdate', (updatedProjectId: string, content: string, reasoningContent?: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => {
useSessionSubscription('streamingUpdate', (updatedProjectId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => {
if (updatedProjectId === projectId) {
setStreamingMessage({
role: 'assistant',
content,
reasoning_content: reasoningContent,
tool_calls: toolCalls
});
}
-72
View File
@@ -1,72 +0,0 @@
import { useQuery } from '@tanstack/react-query';
import { z } from 'zod';
import { createAIClient } from '@/lib/ai-client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
// Zod schemas for the two possible response formats
const creditsResponseV1Schema = z.object({
object: z.literal('credits'),
amount: z.number(),
});
const creditsResponseV2Schema = z.object({
data: z.object({
total_credits: z.number(),
total_usage: z.number(),
}),
});
// Union schema to handle both response formats
const creditsResponseSchema = z.union([creditsResponseV1Schema, creditsResponseV2Schema]);
// Normalized response type (always in V1 format)
export interface CreditsResponse {
object: 'credits';
amount: number;
}
/**
* Custom hook to fetch AI provider credits
* @param providerId - The ID of the AI provider
* @param connection - The AI connection configuration
* @returns Query result with credits information
*/
export function useAICredits(providerId: string, connection: {
baseURL: string;
apiKey?: string;
nostr?: boolean;
}) {
const { user } = useCurrentUser();
return useQuery({
queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId],
queryFn: async (): Promise<CreditsResponse> => {
try {
const ai = createAIClient(connection, user);
const data = await ai.get('/credits');
// Validate and normalize the response
const parsed = creditsResponseSchema.parse(data);
// Convert V2 format to V1 format if needed
if ('data' in parsed) {
return {
object: 'credits',
amount: parsed.data.total_credits - parsed.data.total_usage,
};
}
// Already in V1 format
return parsed;
} catch (error) {
if (error instanceof Error && !error.message.includes('Connection error')) {
console.error('Error fetching AI credits:', error);
}
throw error;
}
},
retry: false, // Don't retry as not all providers support this endpoint
refetchOnWindowFocus: false,
staleTime: 5 * 60 * 1000, // 5 minutes
});
}
+71 -227
View File
@@ -63,12 +63,12 @@ describe('useAIProjectId', () => {
it('should return not configured when AI settings are not configured', () => {
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels: [] },
settings: { providers: {}, recentlyUsedModels: [] },
isConfigured: false,
updateSettings: vi.fn(),
setProvider: vi.fn(),
addProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
updateProvider: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -80,13 +80,12 @@ describe('useAIProjectId', () => {
it('should throw error when trying to generate ID without configuration', async () => {
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels: [] },
settings: { providers: {}, recentlyUsedModels: [] },
isConfigured: false,
updateSettings: vi.fn(),
setProvider: vi.fn(),
addProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
updateProvider: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -100,17 +99,16 @@ describe('useAIProjectId', () => {
it('should throw error when prompt is empty', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
providers: {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
},
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
addProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
updateProvider: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -124,17 +122,16 @@ describe('useAIProjectId', () => {
it('should have configured status when providers are available', () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
providers: {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
},
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
addProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
updateProvider: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -147,17 +144,16 @@ describe('useAIProjectId', () => {
it('should successfully generate project ID', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
providers: {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
},
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
addProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
updateProvider: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -166,46 +162,50 @@ describe('useAIProjectId', () => {
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('test-project-name');
expect(mockParseProviderModel).toHaveBeenCalledWith('openai/gpt-4', [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
]);
expect(mockParseProviderModel).toHaveBeenCalledWith('openai/gpt-4', {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
});
expect(mockCreateAIClient).toHaveBeenCalledWith(
{ apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
undefined
);
});
it('should fallback to untitled when project exists', async () => {
it('should retry with new names when project exists', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
providers: {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
},
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
addProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
updateProvider: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
// Mock AI response - returns a project name that already exists
const mockCompletion = {
// Mock multiple responses - first one exists, second one is unique
const mockCompletion1 = {
choices: [{ message: { content: 'existing-project' } }]
};
const mockCompletion2 = {
choices: [{ message: { content: 'unique-project' } }]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValueOnce(mockCompletion)
create: vi.fn()
.mockResolvedValueOnce(mockCompletion1)
.mockResolvedValueOnce(mockCompletion2)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
// Mock getProject - first call returns project (exists), second returns null (untitled is available)
// Mock getProject - first call returns project (exists), second returns null (unique)
const mockGetProject = vi.fn()
.mockResolvedValueOnce({ id: 'existing-project', name: 'Existing Project', path: '/projects/existing-project', lastModified: new Date() })
.mockResolvedValueOnce(null);
@@ -219,33 +219,38 @@ describe('useAIProjectId', () => {
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('untitled');
expect(projectId).toBe('unique-project');
expect(mockGetProject).toHaveBeenCalledTimes(2);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'existing-project');
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'untitled');
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'unique-project');
// Should have called AI only once
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
// Should have called AI twice - once for initial name, once for retry
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(2);
// Second call should include the "already taken" message
const mockCreate = mockOpenAI.chat.completions.create as ReturnType<typeof vi.fn>;
const secondCallArgs = mockCreate.mock.calls[1][0];
expect(secondCallArgs.messages).toHaveLength(3);
expect(secondCallArgs.messages[2].content).toContain('already taken');
});
it('should fallback to untitled-1 when untitled exists', async () => {
it('should throw error after maximum iterations', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
providers: {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
},
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
addProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
updateProvider: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
// Mock AI to return a project name that already exists
// Mock AI to always return the same name
const mockCompletion = {
choices: [{ message: { content: 'taken-project' } }]
};
@@ -258,11 +263,13 @@ describe('useAIProjectId', () => {
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
// Mock getProject - taken-project exists, untitled exists, untitled-1 is available
const mockGetProject = vi.fn()
.mockResolvedValueOnce({ id: 'taken-project', name: 'Taken Project', path: '/projects/taken-project', lastModified: new Date() })
.mockResolvedValueOnce({ id: 'untitled', name: 'Untitled', path: '/projects/untitled', lastModified: new Date() })
.mockResolvedValueOnce(null);
// Mock getProject to always return a project (project always exists)
const mockGetProject = vi.fn().mockResolvedValue({
id: 'taken-project',
name: 'Taken Project',
path: '/projects/taken-project',
lastModified: new Date()
});
const mockProjectsManager = {
getProject: mockGetProject,
@@ -271,189 +278,26 @@ describe('useAIProjectId', () => {
const { result } = renderHook(() => useAIProjectId());
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
await expect(result.current.generateProjectId('openai/gpt-4', 'A social media app for developers'))
.rejects.toThrow('Failed to generate a unique project name after 3 attempts');
expect(projectId).toBe('untitled-1');
expect(mockGetProject).toHaveBeenCalledTimes(3);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'taken-project');
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'untitled');
expect(mockGetProject).toHaveBeenNthCalledWith(3, 'untitled-1');
// Should have called AI only once
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
});
it('should fallback to untitled when AI generates too long name', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
// Mock AI to return a very long project name (over 50 characters)
const mockCompletion = {
choices: [{ message: { content: 'this-is-a-very-long-project-name-that-exceeds-the-maximum-allowed-length-limit' } }]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
// Mock getProject - untitled is available
const mockGetProject = vi.fn().mockResolvedValue(null);
const mockProjectsManager = {
getProject: mockGetProject,
} as unknown as ProjectsManager;
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
const { result } = renderHook(() => useAIProjectId());
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('untitled');
expect(mockGetProject).toHaveBeenCalledTimes(1);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'untitled');
// Should have called AI only once
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
});
it('should fallback to untitled when AI generates invalid name', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
// Mock AI to return an invalid project name (doesn't match regex)
const mockCompletion = {
choices: [{ message: { content: 'Invalid Project Name!' } }]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
// Mock getProject - untitled is available
const mockGetProject = vi.fn().mockResolvedValue(null);
const mockProjectsManager = {
getProject: mockGetProject,
} as unknown as ProjectsManager;
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
const { result } = renderHook(() => useAIProjectId());
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('untitled');
expect(mockGetProject).toHaveBeenCalledTimes(1);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'untitled');
// Should have called AI only once
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
});
it('should fallback to untitled-2 when untitled and untitled-1 exist', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
// Mock AI to return a project name that already exists
const mockCompletion = {
choices: [{ message: { content: 'taken-project' } }]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
// Mock getProject - taken-project exists, untitled exists, untitled-1 exists, untitled-2 is available
const mockGetProject = vi.fn()
.mockResolvedValueOnce({ id: 'taken-project', name: 'Taken Project', path: '/projects/taken-project', lastModified: new Date() })
.mockResolvedValueOnce({ id: 'untitled', name: 'Untitled', path: '/projects/untitled', lastModified: new Date() })
.mockResolvedValueOnce({ id: 'untitled-1', name: 'Untitled 1', path: '/projects/untitled-1', lastModified: new Date() })
.mockResolvedValueOnce(null);
const mockProjectsManager = {
getProject: mockGetProject,
} as unknown as ProjectsManager;
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
const { result } = renderHook(() => useAIProjectId());
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('untitled-2');
expect(mockGetProject).toHaveBeenCalledTimes(4);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'taken-project');
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'untitled');
expect(mockGetProject).toHaveBeenNthCalledWith(3, 'untitled-1');
expect(mockGetProject).toHaveBeenNthCalledWith(4, 'untitled-2');
// Should have called AI only once
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(3);
});
it('should handle loading state correctly', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
providers: {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
},
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
addProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
updateProvider: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
+45 -32
View File
@@ -38,45 +38,58 @@ export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
{ role: 'user' as const, content: prompt }
];
// Try once to generate a project name
const completion = await openai.chat.completions.create({
model,
messages,
temperature: 1,
});
let iterations = 0;
const maxIterations = 3;
const projectId = completion.choices[0]?.message?.content?.trim();
if (!projectId) {
throw new Error('Failed to generate project name');
}
while (iterations < maxIterations) {
iterations++;
const completion = await openai.chat.completions.create({
model,
messages,
temperature: 1,
});
const projectName = completion.choices[0]?.message?.content?.trim();
if (!projectName) {
throw new Error('Failed to generate project name');
}
// Convert the name into kebab-case
const projectId = projectName
.toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with hyphens
.replace(/[^a-z0-9-]/g, '') // Remove invalid characters
.replace(/-+/g, '-') // Replace multiple hyphens with a single hyphen
.replace(/^-+|-+$/g, ''); // Trim hyphens from start and end
if (!projectId) {
throw new Error('Generated project ID is empty after formatting');
}
// Validate the generated ID
const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
if (!validIdRegex.test(projectId)) {
throw new Error('Generated project ID is invalid');
}
// Validate the generated ID directly (no conversion)
const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
if (projectId.length <= 50 && validIdRegex.test(projectId)) {
// Check if project exists
const existingProject = await projectsManager.getProject(projectId);
if (existingProject === null) {
// Valid and unique project ID
return projectId;
if (existingProject !== null) {
// Add user message indicating the name is already taken
messages.push({
role: 'user',
content: `The name "${projectName}" (project ID: ${projectId}) is already taken. Please generate another unique name.`
});
continue; // Try again with updated conversation
}
// If we reach here, the project ID is valid and unique
return projectId;
}
// If we reach here, either the regex failed or the project already exists
// Fall back to "untitled" with number suffixes
let fallbackId = 'untitled';
let counter = 1;
// Check if base "untitled" exists
let existingProject = await projectsManager.getProject(fallbackId);
// Keep incrementing until we find an available name
while (existingProject !== null) {
fallbackId = `untitled-${counter}`;
existingProject = await projectsManager.getProject(fallbackId);
counter++;
}
return fallbackId;
// If we've exceeded max iterations, throw an error
throw new Error(`Failed to generate a unique project name after ${maxIterations} attempts`);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Failed to generate project ID';
onError?.(errorMessage);
+9 -43
View File
@@ -5,40 +5,22 @@ import { useFS } from './useFS';
import { useGitSettings } from './useGitSettings';
import { Git } from '@/lib/git';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import type { NPool } from '@nostrify/nostrify';
// Mock the dependencies
vi.mock('./useFS');
vi.mock('./useGitSettings');
vi.mock('@nostrify/react', () => ({
useNostr: vi.fn(),
}));
vi.mock('@/lib/git');
const mockUseFS = vi.mocked(useFS);
const mockUseGitSettings = vi.mocked(useGitSettings);
const MockGit = vi.mocked(Git);
// Import the mocked useNostr after mocking
import { useNostr } from '@nostrify/react';
const mockUseNostr = vi.mocked(useNostr);
describe('useGit', () => {
const mockFS = {} as JSRuntimeFS;
const mockNostr = {
req: vi.fn(),
query: vi.fn(),
event: vi.fn(),
group: vi.fn(),
relay: vi.fn(),
relays: new Map(),
close: vi.fn(),
} as unknown as NPool;
beforeEach(() => {
vi.clearAllMocks();
mockUseFS.mockReturnValue({ fs: mockFS });
mockUseNostr.mockReturnValue({ nostr: mockNostr });
});
it('creates Git instance with default CORS proxy', () => {
@@ -54,14 +36,9 @@ describe('useGit', () => {
isConfigured: false,
});
const { result } = renderHook(() => useGit());
renderHook(() => useGit());
expect(MockGit).toHaveBeenCalledWith({
fs: mockFS,
nostr: mockNostr,
corsProxy: 'https://cors.isomorphic-git.org',
});
expect(result.current).toEqual({ git: expect.any(Object) });
expect(MockGit).toHaveBeenCalledWith(mockFS, 'https://cors.isomorphic-git.org');
});
it('creates Git instance with custom CORS proxy', () => {
@@ -77,17 +54,14 @@ describe('useGit', () => {
isConfigured: false,
});
const { result } = renderHook(() => useGit());
renderHook(() => useGit());
expect(MockGit).toHaveBeenCalledWith({
fs: mockFS,
nostr: mockNostr,
corsProxy: 'https://custom-cors.example.com',
});
expect(result.current).toEqual({ git: expect.any(Object) });
expect(MockGit).toHaveBeenCalledWith(mockFS, 'https://custom-cors.example.com');
});
it('recreates Git instance when CORS proxy changes', () => {
const { rerender } = renderHook(() => useGit());
// First render with default proxy
mockUseGitSettings.mockReturnValue({
settings: {
@@ -101,12 +75,8 @@ describe('useGit', () => {
isConfigured: false,
});
const { rerender } = renderHook(() => useGit());
expect(MockGit).toHaveBeenCalledWith({
fs: mockFS,
nostr: mockNostr,
corsProxy: 'https://cors.isomorphic-git.org',
});
rerender();
expect(MockGit).toHaveBeenCalledWith(mockFS, 'https://cors.isomorphic-git.org');
// Second render with custom proxy
mockUseGitSettings.mockReturnValue({
@@ -122,10 +92,6 @@ describe('useGit', () => {
});
rerender();
expect(MockGit).toHaveBeenLastCalledWith({
fs: mockFS,
nostr: mockNostr,
corsProxy: 'https://custom-cors.example.com',
});
expect(MockGit).toHaveBeenLastCalledWith(mockFS, 'https://custom-cors.example.com');
});
});
+4 -7
View File
@@ -1,22 +1,19 @@
import { useMemo } from 'react';
import { Git } from '@/lib/git';
import { useFS } from '@/hooks/useFS';
import { useNostr } from '@nostrify/react';
import { useGitSettings } from '@/hooks/useGitSettings';
/**
* Hook that provides a Git instance configured with the virtual filesystem
* and configurable CORS proxy for GitHub/GitLab repositories.
*/
export function useGit(): { git: Git } {
export function useGit() {
const { fs } = useFS();
const { nostr } = useNostr();
const { settings } = useGitSettings();
const { corsProxy } = settings;
const git = useMemo(() => {
return new Git({ fs, nostr, corsProxy });
}, [fs, nostr, corsProxy]);
return new Git(fs, settings.corsProxy);
}, [fs, settings.corsProxy]);
return { git };
return git;
}
-157
View File
@@ -1,157 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { useGitHubOAuth } from './useGitHubOAuth';
import { TestApp } from '@/test/TestApp';
// Mock environment variables for testing
vi.stubEnv('VITE_GITHUB_OAUTH_CLIENT_ID', '********************');
vi.stubEnv('VITE_GITHUB_OAUTH_CLIENT_SECRET', '****************************************');
// Mock crypto.subtle for PKCE testing
const mockCryptoSubtle = {
digest: vi.fn(),
};
const mockCrypto = {
getRandomValues: vi.fn(),
randomUUID: vi.fn(),
subtle: mockCryptoSubtle,
};
Object.defineProperty(global, 'crypto', {
value: mockCrypto,
writable: true,
});
// Mock btoa for base64 encoding
global.btoa = vi.fn((str: string) => Buffer.from(str, 'binary').toString('base64'));
describe('useGitHubOAuth PKCE', () => {
beforeEach(() => {
vi.clearAllMocks();
localStorage.clear();
// Setup crypto mocks
mockCrypto.getRandomValues.mockImplementation((array: Uint8Array) => {
// Fill with predictable values for testing
for (let i = 0; i < array.length; i++) {
array[i] = i % 256;
}
return array;
});
mockCrypto.randomUUID.mockReturnValue('test-state-uuid');
// Mock SHA-256 digest to return predictable hash
mockCryptoSubtle.digest.mockResolvedValue(
new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32])
);
});
afterEach(() => {
localStorage.clear();
});
it('should validate state parameter in callback', async () => {
// Setup stored state
localStorage.setItem('github_oauth_state', 'correct-state');
localStorage.setItem('github_oauth_code_verifier', 'test-verifier');
const { result } = renderHook(() => useGitHubOAuth(), {
wrapper: TestApp,
});
// Mock fetch for token exchange and user info (using corsproxy.io URLs)
const mockFetch = vi.fn()
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ access_token: 'test-token' }),
})
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ login: 'testuser' }),
});
global.fetch = mockFetch;
let success: boolean | undefined;
await act(async () => {
success = await result.current.handleCallback('test-code', 'correct-state');
});
expect(success).toBe(true);
expect(localStorage.getItem('github_oauth_state')).toBeNull();
expect(localStorage.getItem('github_oauth_code_verifier')).toBeNull();
});
it('should reject invalid state parameter', async () => {
localStorage.setItem('github_oauth_state', 'correct-state');
localStorage.setItem('github_oauth_code_verifier', 'test-verifier');
const { result } = renderHook(() => useGitHubOAuth(), {
wrapper: TestApp,
});
let success: boolean | undefined;
await act(async () => {
success = await result.current.handleCallback('test-code', 'wrong-state');
});
expect(success).toBe(false);
expect(result.current.error).toBe('Invalid OAuth state parameter');
// Should clean up on error
expect(localStorage.getItem('github_oauth_state')).toBeNull();
expect(localStorage.getItem('github_oauth_code_verifier')).toBeNull();
});
it('should reject missing code verifier', async () => {
localStorage.setItem('github_oauth_state', 'correct-state');
// Don't set code verifier
const { result } = renderHook(() => useGitHubOAuth(), {
wrapper: TestApp,
});
let success: boolean | undefined;
await act(async () => {
success = await result.current.handleCallback('test-code', 'correct-state');
});
expect(success).toBe(false);
expect(result.current.error).toBe('PKCE code verifier not found. Please restart the OAuth flow.');
});
it('should include code_verifier in token request', async () => {
localStorage.setItem('github_oauth_state', 'correct-state');
localStorage.setItem('github_oauth_code_verifier', 'test-verifier');
const { result } = renderHook(() => useGitHubOAuth(), {
wrapper: TestApp,
});
const mockFetch = vi.fn()
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ access_token: 'test-token' }),
})
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ login: 'testuser' }),
});
global.fetch = mockFetch;
await act(async () => {
await result.current.handleCallback('test-code', 'correct-state');
});
// Check that the token request includes the code verifier
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('corsproxy.io/?url=https://github.com/login/oauth/access_token'),
expect.objectContaining({
method: 'POST',
body: expect.stringContaining('"code_verifier":"test-verifier"'),
})
);
});
});
+19 -73
View File
@@ -25,28 +25,7 @@ export function useGitHubOAuth() {
import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET
);
// Generate a cryptographically secure random string for PKCE code verifier
const generateCodeVerifier = (): string => {
const array = new Uint8Array(32);
crypto.getRandomValues(array);
return btoa(String.fromCharCode(...array))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
};
// Create SHA-256 hash of the code verifier for PKCE code challenge
const generateCodeChallenge = async (codeVerifier: string): Promise<string> => {
const encoder = new TextEncoder();
const data = encoder.encode(codeVerifier);
const digest = await crypto.subtle.digest('SHA-256', data);
return btoa(String.fromCharCode(...new Uint8Array(digest)))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
};
const initiateOAuth = useCallback(async () => {
const initiateOAuth = useCallback(() => {
const clientId = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID;
if (!clientId) {
@@ -54,36 +33,19 @@ export function useGitHubOAuth() {
return;
}
try {
// Generate PKCE parameters
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
// Generate a random state parameter for security
const state = crypto.randomUUID();
localStorage.setItem('github_oauth_state', state);
// Generate a random state parameter for security
const state = crypto.randomUUID();
// Redirect to GitHub OAuth
const params = new URLSearchParams({
client_id: clientId,
redirect_uri: window.location.origin + '/',
scope: 'repo',
state: state,
});
// Store both state and code verifier for later use
localStorage.setItem('github_oauth_state', state);
localStorage.setItem('github_oauth_code_verifier', codeVerifier);
// Redirect to GitHub OAuth with PKCE parameters
const params = new URLSearchParams({
client_id: clientId,
redirect_uri: window.location.origin + '/oauth/github',
scope: 'repo',
state: state,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
});
window.location.href = `https://github.com/login/oauth/authorize?${params.toString()}`;
} catch (error) {
console.error('Failed to initiate OAuth with PKCE:', error);
setState(prev => ({
...prev,
error: 'Failed to generate PKCE parameters. Please try again.'
}));
}
window.location.href = `https://github.com/login/oauth/authorize?${params.toString()}`;
}, []);
const handleCallback = useCallback(async (code: string, state: string) => {
@@ -96,15 +58,8 @@ export function useGitHubOAuth() {
throw new Error('Invalid OAuth state parameter');
}
// Get the stored code verifier for PKCE
const codeVerifier = localStorage.getItem('github_oauth_code_verifier');
if (!codeVerifier) {
throw new Error('PKCE code verifier not found. Please restart the OAuth flow.');
}
// Clean up stored values
// Clean up stored state
localStorage.removeItem('github_oauth_state');
localStorage.removeItem('github_oauth_code_verifier');
const clientId = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID;
const clientSecret = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET;
@@ -113,22 +68,18 @@ export function useGitHubOAuth() {
throw new Error('GitHub OAuth credentials not configured');
}
// Exchange code for access token with PKCE code verifier
const tokenRequestBody = {
client_id: clientId,
client_secret: clientSecret,
code: code,
redirect_uri: window.location.origin + '/oauth/github',
code_verifier: codeVerifier,
};
// Exchange code for access token
const tokenResponse = await fetch('https://corsproxy.io/?url=https://github.com/login/oauth/access_token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(tokenRequestBody),
body: JSON.stringify({
client_id: clientId,
client_secret: clientSecret,
code: code,
}),
});
if (!tokenResponse.ok) {
@@ -165,11 +116,6 @@ export function useGitHubOAuth() {
return true;
} catch (error) {
console.error('GitHub OAuth error:', error);
// Clean up any remaining OAuth data on error
localStorage.removeItem('github_oauth_state');
localStorage.removeItem('github_oauth_code_verifier');
setState(prev => ({
...prev,
isLoading: false,
+1 -1
View File
@@ -40,7 +40,7 @@ interface GitStatus {
}
export function useGitStatus(projectId: string | null) {
const { git } = useGit();
const git = useGit();
return useQuery({
queryKey: ['git-status', projectId],
+1 -1
View File
@@ -1,6 +1,6 @@
import { useEffect, useState } from "react"
const MOBILE_BREAKPOINT = 1080;
const MOBILE_BREAKPOINT = 768;
export function useIsMobile(): boolean {
const [isMobile, setIsMobile] = useState(window.innerWidth < MOBILE_BREAKPOINT);
+1 -2
View File
@@ -14,7 +14,7 @@ export function useLoggedInAccounts() {
const { nostr } = useNostr();
const { logins, setLogin, removeLogin } = useNostrLogin();
const { data: authors = [], isLoading } = useQuery({
const { data: authors = [] } = useQuery({
queryKey: ['logins', logins.map((l) => l.id).join(';')],
queryFn: async ({ signal }) => {
const events = await nostr.query(
@@ -52,6 +52,5 @@ export function useLoggedInAccounts() {
otherUsers,
setLogin,
removeLogin,
isLoading,
};
}
+1 -5
View File
@@ -1,7 +1,6 @@
import { useMemo } from 'react';
import { ProjectsManager } from '@/lib/ProjectsManager';
import { useFS } from '@/hooks/useFS';
import { useGit } from './useGit';
/**
* Hook that provides a ProjectsManager instance.
@@ -9,11 +8,8 @@ import { useGit } from './useGit';
*/
export function useProjectsManager() {
const { fs } = useFS();
const { git } = useGit();
const projectsManager = useMemo(() => {
return new ProjectsManager({ fs, git });
}, [fs, git]);
const projectsManager = useMemo(() => new ProjectsManager(fs), [fs]);
return projectsManager;
}
+5 -14
View File
@@ -7,10 +7,9 @@ import { createAIClient } from '@/lib/ai-client';
interface ProviderModel {
id: string;
name?: string;
name: string;
provider: string;
fullId: string; // provider/model format
description?: string;
/** Maximum size of context window, if available */
contextLength?: number;
/** Pricing information, if available */
@@ -39,13 +38,12 @@ export function useProviderModels(): ModelFetchResult {
isLoading,
refetch,
} = useQuery({
queryKey: ['provider-models', settings.providers],
queryKey: ['provider-models'],
queryFn: async () => {
const errors: string[] = [];
// Fetch models from each configured provider in parallel
const providerPromises = settings.providers.map(async (provider) => {
const { id: providerKey, ...connection } = provider;
const providerPromises = Object.entries(settings.providers).map(async ([providerKey, connection]) => {
try {
const openai = createAIClient(connection, user);
@@ -59,18 +57,11 @@ export function useProviderModels(): ModelFetchResult {
const providerModels = response.data.map((model) => {
const providerModel: ProviderModel = {
id: model.id,
name: model.id,
provider: providerKey,
fullId: `${providerKey}/${model.id}`,
};
if ('name' in model && typeof model.name === 'string') {
providerModel.name = model.name;
}
if ('description' in model && typeof model.description === 'string') {
providerModel.description = model.description;
}
if ('context_length' in model && typeof model.context_length === 'number') {
providerModel.contextLength = model.context_length;
}
@@ -127,7 +118,7 @@ export function useProviderModels(): ModelFetchResult {
return allModels;
},
enabled: settings.providers.length > 0,
enabled: Object.keys(settings.providers).length > 0,
staleTime: 5 * 60 * 1000, // Cache for 5 minutes
retry: false, // Don't retry on failure
});
-24
View File
@@ -1,24 +0,0 @@
import { useEffect, useState } from "react";
export function useSystemTheme() {
const getSystemTheme = (): "dark" | "light" =>
window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
const [theme, setTheme] = useState<"dark" | "light">(getSystemTheme);
useEffect(() => {
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
const handler = (event: MediaQueryListEvent): void => {
setTheme(event.matches ? "dark" : "light");
};
// Attach listener
mediaQuery.addEventListener("change", handler);
// Cleanup
return () => mediaQuery.removeEventListener("change", handler);
}, []);
return theme;
}
+1 -12
View File
@@ -1,26 +1,15 @@
import { type Theme } from "@/contexts/AppContext";
import { useAppContext } from "@/hooks/useAppContext";
import { useSystemTheme } from "./useSystemTheme";
/**
* Hook to get and set the active theme
* @returns Theme context with theme and setTheme
*/
export function useTheme(): {
theme: Theme;
systemTheme: "light" | "dark";
displayTheme: "light" | "dark";
setTheme: (theme: Theme) => void;
} {
export function useTheme(): { theme: Theme; setTheme: (theme: Theme) => void } {
const { config, updateConfig } = useAppContext();
const systemTheme = useSystemTheme();
const displayTheme = config.theme === 'system' ? systemTheme : config.theme;
return {
theme: config.theme,
systemTheme,
displayTheme,
setTheme: (theme: Theme) => {
updateConfig((currentConfig) => ({
...currentConfig,
-2
View File
@@ -1,2 +0,0 @@
// Re-export useTranslation from react-i18next for consistency
export { useTranslation } from 'react-i18next';
-4
View File
@@ -247,10 +247,6 @@
max-height: 100dvh;
}
pre.shiki {
background-color: transparent !important;
}
/* Fallback for browsers that don't support dvh */
@supports not (height: 100dvh) {
.h-dvh {
+48 -4
View File
@@ -28,8 +28,17 @@ describe('DotAI', () => {
});
describe('readLastSessionHistory', () => {
it('should return null when AI is not enabled', async () => {
// Mock isEnabled to return false
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(false);
const result = await dotAI.readLastSessionHistory();
expect(result).toBeNull();
});
it('should return null when history directory does not exist', async () => {
// Mock historyDirExists to return false
// Mock isEnabled to return true but historyDirExists to return false
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false);
const result = await dotAI.readLastSessionHistory();
@@ -37,7 +46,8 @@ describe('DotAI', () => {
});
it('should return null when no session files exist', async () => {
// Mock historyDirExists to return true
// Mock isEnabled and historyDirExists to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock readdir to return empty array
@@ -48,7 +58,8 @@ describe('DotAI', () => {
});
it('should return messages and session name from most recent file', async () => {
// Mock historyDirExists to return true
// Mock isEnabled and historyDirExists to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock readdir to return session files
@@ -73,7 +84,8 @@ describe('DotAI', () => {
});
it('should handle malformed JSON lines gracefully', async () => {
// Mock historyDirExists to return true
// Mock isEnabled and historyDirExists to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock readdir to return session files
@@ -95,7 +107,24 @@ invalid json line
});
describe('setHistory', () => {
it('should not save when AI is not enabled', async () => {
// Mock isEnabled to return false
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(false);
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'user', content: 'Hello' },
{ role: 'assistant', content: 'Hi there!' }
];
await dotAI.setHistory('test-session', messages);
// Verify writeFile was not called
expect(mockFS.writeFile).not.toHaveBeenCalled();
});
it('should create history directory if it does not exist', async () => {
// Mock isEnabled to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
// Mock historyDirExists to return false initially
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false);
// Mock setupAiHistoryDir
@@ -112,6 +141,8 @@ invalid json line
});
it('should write messages as JSONL format', async () => {
// Mock isEnabled to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
// Mock historyDirExists to return true
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
@@ -130,6 +161,8 @@ invalid json line
});
it('should handle empty messages array', async () => {
// Mock isEnabled to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
// Mock historyDirExists to return true
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
@@ -143,6 +176,8 @@ invalid json line
});
it('should handle write errors gracefully', async () => {
// Mock isEnabled to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
// Mock historyDirExists to return true
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock writeFile to throw an error
@@ -155,6 +190,9 @@ invalid json line
});
it('should validate tool messages have matching tool_call_id', async () => {
// Mock isEnabled to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
const validMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'user', content: 'Hello' },
{
@@ -211,6 +249,9 @@ invalid json line
});
it('should validate multiple tool messages correctly', async () => {
// Mock isEnabled to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
const validMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'user', content: 'Hello' },
{
@@ -230,6 +271,9 @@ invalid json line
});
it('should allow tool messages to reference tool calls from the most recent assistant message', async () => {
// Mock isEnabled to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
const validMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'user', content: 'First request' },
{
+53 -10
View File
@@ -1,4 +1,4 @@
import { join } from "path-browserify";
import { join } from "@std/path";
import type OpenAI from "openai";
import type { JSRuntimeFS } from "./JSRuntime";
@@ -31,7 +31,45 @@ export class DotAI {
return filename;
}
/** Check if AI history should be enabled based on the new criteria */
async isEnabled(): Promise<boolean> {
// Check if .ai directory exists
try {
const stat = await this.fs.stat(join(this.workingDir, ".ai"));
if (stat.isDirectory()) {
return true;
}
} catch {
// Continue to next check
}
// Check if .ai/ or .ai is gitignored
try {
const gitignorePath = join(this.workingDir, ".gitignore");
const gitignoreContent = await this.fs.readFile(gitignorePath, "utf8");
const lines = gitignoreContent.split("\n").map((line) => line.trim());
// Check for .ai/ or .ai patterns (ignore comments and empty lines)
for (const line of lines) {
if (line.startsWith("#") || line === "") {
continue;
}
// Check for various .ai patterns
if (
line === ".ai" || line === ".ai/" || line === "/.ai" ||
line === "/.ai/" ||
line === ".ai/*" || line === "/.ai/*"
) {
return true;
}
}
} catch {
// .gitignore doesn't exist or can't be read
}
return false;
}
/** Check if the history directory exists */
async historyDirExists(): Promise<boolean> {
@@ -51,7 +89,11 @@ export class DotAI {
// Validate messages before saving
this.validateMessages(messages);
// Always create the .ai directory and write session history
// Only save if history should be enabled based on the new criteria
if (!(await this.isEnabled())) {
return;
}
// Create the history directory if it doesn't exist
if (!(await this.historyDirExists())) {
await this.setupAiHistoryDir();
@@ -163,9 +205,6 @@ export class DotAI {
// Ensure .ai directory exists
await this.fs.mkdir(aiDir, { recursive: true });
// Ensure .ai/ is gitignored
await this.ensureAiGitignored();
// Write the model
await this.fs.writeFile(modelPath, model.trim() + "\n");
} catch (error) {
@@ -206,6 +245,13 @@ export class DotAI {
* Write parameters to .ai/PARAMETERS file
*/
async writeAiParameters(parameters: Record<string, string>): Promise<void> {
// Check if we should create the .ai directory based on the same logic as MODEL
const shouldCreate = await this.isEnabled();
if (!shouldCreate) {
return;
}
const aiDir = join(this.workingDir, ".ai");
const parametersPath = join(aiDir, "PARAMETERS");
@@ -213,9 +259,6 @@ export class DotAI {
// Ensure .ai directory exists
await this.fs.mkdir(aiDir, { recursive: true });
// Ensure .ai/ is gitignored
await this.ensureAiGitignored();
// Format parameters as key=value pairs
const lines = Object.entries(parameters).map(([key, value]) =>
`${key}=${value}`
@@ -247,8 +290,8 @@ export class DotAI {
sessionName: string;
} | null> {
try {
// Check if history directory exists
if (!(await this.historyDirExists())) {
// Check if AI history is enabled for this project
if (!(await this.isEnabled()) || !(await this.historyDirExists())) {
return null;
}
-2
View File
@@ -20,14 +20,12 @@ export interface JSRuntimeFS {
stat(path: string): Promise<{
isDirectory(): boolean;
isFile(): boolean;
isSymbolicLink?(): boolean;
size?: number;
mtimeMs?: number;
}>;
lstat(path: string): Promise<{
isDirectory(): boolean;
isFile(): boolean;
isSymbolicLink?(): boolean;
size?: number;
mtimeMs?: number;
}>;
-441
View File
@@ -1,441 +0,0 @@
import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime';
/**
* OPFS (Origin Private File System) adapter that implements JSRuntimeFS interface
* This makes OPFS compatible with the unified filesystem interface
*/
export class OPFSAdapter implements JSRuntimeFS {
private root: Promise<FileSystemDirectoryHandle>;
constructor() {
// Check if OPFS is available
if (!('storage' in navigator) ||
typeof (navigator.storage as unknown as { getDirectory: () => Promise<FileSystemDirectoryHandle> }).getDirectory !== 'function') {
throw new Error('OPFS is not supported in this browser or environment');
}
// Get the root directory handle for OPFS
this.root = (navigator.storage as unknown as { getDirectory: () => Promise<FileSystemDirectoryHandle> }).getDirectory();
}
/**
* Special method to handle Git-specific read operations more robustly
* This helps with isomorphic-git compatibility
*/
private async readFileForGit(path: string): Promise<Uint8Array> {
try {
// Guard against undefined path
if (!path || typeof path !== 'string') {
const error = new Error('ENOENT: no such file or directory, open \'undefined\'') as NodeJS.ErrnoException;
error.code = 'ENOENT';
error.errno = -2;
error.syscall = 'open';
error.path = path || 'undefined';
throw error;
}
const fileHandle = await this.getFileHandle(path);
const file = await fileHandle.getFile();
const arrayBuffer = await file.arrayBuffer();
return new Uint8Array(arrayBuffer);
} catch (error) {
// Enhanced error handling for Git operations
console.error(`Git read operation failed for path: ${path}`, error);
// Create a more detailed error that isomorphic-git can handle
const gitError = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
gitError.code = 'ENOENT';
gitError.errno = -2;
gitError.syscall = 'open';
gitError.path = path;
// Preserve original error information by adding it to the message
if (error instanceof Error) {
gitError.message = `${gitError.message}: ${error.message}`;
}
throw gitError;
}
}
async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, encoding: 'utf8'): Promise<string>;
async readFile(path: string, encoding: string): Promise<string>;
async readFile(path: string, encoding?: string): Promise<string | Uint8Array>;
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
try {
// Debug logging to see what's being called
console.log(`OPFSAdapter.readFile called with path:`, path, `encoding:`, encoding);
// Simple path validation like LightningFS
if (!path || typeof path !== 'string') {
throw new Error('ENOENT: no such file or directory');
}
// Use special Git handling for Git object files
if (path.includes('.git/objects/') || path.includes('.git/')) {
return await this.readFileForGit(path);
}
const fileHandle = await this.getFileHandle(path);
const file = await fileHandle.getFile();
if (encoding === 'utf8') {
const text = await file.text();
return text;
} else if (encoding) {
// For other encodings, we might need additional handling
const text = await file.text();
return text;
} else {
// Return as Uint8Array by default
const arrayBuffer = await file.arrayBuffer();
return new Uint8Array(arrayBuffer);
}
} catch (error) {
console.error(`OPFSAdapter.readFile failed for path: ${path}`, error);
// Convert to Node.js style error for consistency
if (error instanceof Error && (error.message.includes('NotFound') || error.name === 'NotFoundError')) {
const nodeError = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
nodeError.code = 'ENOENT';
nodeError.errno = -2;
nodeError.syscall = 'open';
nodeError.path = path;
throw nodeError;
}
throw error;
}
}
async writeFile(path: string, data: string | Uint8Array, _encoding?: string): Promise<void> {
const fileHandle = await this.getFileHandle(path, { create: true });
const writable = await fileHandle.createWritable();
if (typeof data === 'string') {
await writable.write(data);
} else {
await writable.write(data);
}
await writable.close();
}
async readdir(path: string): Promise<string[]>;
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
try {
console.log(`OPFSAdapter.readdir called with path:`, path, `options:`, options);
const dirHandle = await this.getDirectoryHandle(path);
const entries: string[] = [];
const directoryEntries: DirectoryEntry[] = [];
// Use asyncIterator to iterate through directory entries
const dirIterator = (dirHandle as unknown as { values: () => AsyncIterableIterator<FileSystemHandle> }).values();
let result = await dirIterator.next();
while (!result.done) {
const entry = result.value;
if (options?.withFileTypes) {
directoryEntries.push({
name: entry.name,
isDirectory: () => entry.kind === 'directory',
isFile: () => entry.kind === 'file',
});
} else {
entries.push(entry.name);
}
result = await dirIterator.next();
}
return options?.withFileTypes ? directoryEntries : entries;
} catch (error) {
console.error(`OPFSAdapter.readdir failed for path: ${path}`, error);
throw error;
}
}
async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {
try {
console.log(`OPFSAdapter.mkdir called with path:`, path, `options:`, options);
// Guard against undefined path
if (!path || typeof path !== 'string') {
const error = new Error('ENOENT: no such file or directory, mkdir \'undefined\'') as NodeJS.ErrnoException;
error.code = 'ENOENT';
error.errno = -2;
error.syscall = 'mkdir';
error.path = path || 'undefined';
throw error;
}
if (options?.recursive) {
await this.createDirectoriesRecursive(path);
} else {
const parentPath = this.getParentPath(path);
const dirName = this.getBaseName(path);
const parentHandle = await this.getDirectoryHandle(parentPath);
await parentHandle.getDirectoryHandle(dirName, { create: true });
}
} catch (error) {
console.error(`OPFSAdapter.mkdir failed for path: ${path}`, error);
// Convert to Node.js style error for consistency
let mkdirError: NodeJS.ErrnoException;
if (error instanceof Error && (error.message.includes('NotFound') || error.name === 'NotFoundError')) {
// Parent directory doesn't exist
mkdirError = new Error(`ENOENT: no such file or directory, mkdir '${path}'`) as NodeJS.ErrnoException;
mkdirError.code = 'ENOENT';
mkdirError.errno = -2;
} else {
// Other errors
mkdirError = new Error(`EACCES: permission denied, mkdir '${path}'`) as NodeJS.ErrnoException;
mkdirError.code = 'EACCES';
mkdirError.errno = -13;
}
mkdirError.syscall = 'mkdir';
mkdirError.path = path;
// Preserve original error information by adding it to the message
if (error instanceof Error) {
mkdirError.message = `${mkdirError.message}: ${error.message}`;
}
throw mkdirError;
}
}
async stat(path: string): Promise<{
isDirectory(): boolean;
isFile(): boolean;
size?: number;
mtimeMs?: number;
}> {
try {
console.log(`OPFSAdapter.stat called with path:`, path);
const fileHandle = await this.getFileHandle(path);
const file = await fileHandle.getFile();
return {
isDirectory: () => false,
isFile: () => true,
size: file.size,
mtimeMs: file.lastModified,
};
} catch (fileError) {
// If not a file, try as directory
try {
await this.getDirectoryHandle(path);
return {
isDirectory: () => true,
isFile: () => false,
};
} catch (dirError) {
// Throw ENOENT error to match Node.js fs convention
const error = new Error(`ENOENT: no such file or directory, stat '${path}'`) as NodeJS.ErrnoException;
error.code = 'ENOENT';
error.errno = -2;
error.syscall = 'stat';
error.path = path;
console.error(`OPFSAdapter.stat failed for path: ${path}`, { fileError, dirError });
throw error;
}
}
}
async lstat(path: string): Promise<{
isDirectory(): boolean;
isFile(): boolean;
size?: number;
mtimeMs?: number;
}> {
// OPFS doesn't have symbolic links, so lstat is the same as stat
return this.stat(path);
}
async unlink(path: string): Promise<void> {
const parentPath = this.getParentPath(path);
const fileName = this.getBaseName(path);
const parentHandle = await this.getDirectoryHandle(parentPath);
await parentHandle.removeEntry(fileName);
}
async rmdir(path: string): Promise<void> {
const parentPath = this.getParentPath(path);
const dirName = this.getBaseName(path);
const parentHandle = await this.getDirectoryHandle(parentPath);
await parentHandle.removeEntry(dirName, { recursive: true });
}
async rename(oldPath: string, newPath: string): Promise<void> {
// OPFS doesn't have a native rename operation, so we need to copy and delete
await this.copyRecursive(oldPath, newPath);
await this.unlinkRecursive(oldPath);
}
async readlink(_path: string): Promise<string> {
// OPFS doesn't support symbolic links
throw new Error('Symbolic links are not supported in OPFS');
}
async symlink(_target: string, _path: string): Promise<void> {
// OPFS doesn't support symbolic links
throw new Error('Symbolic links are not supported in OPFS');
}
// Helper methods
private async getDirectoryHandle(path: string, options?: { create?: boolean }): Promise<FileSystemDirectoryHandle> {
if (path === '/' || path === '') {
return this.root;
}
const parts = path.split('/').filter(Boolean);
let currentHandle = await this.root;
for (const part of parts) {
try {
currentHandle = await currentHandle.getDirectoryHandle(part, options);
} catch (error) {
if (!options?.create) {
// Convert OPFS error to ENOENT for consistency
const errorWithCode = new Error(`ENOENT: no such file or directory, scandir '${path}'`) as NodeJS.ErrnoException;
errorWithCode.code = 'ENOENT';
errorWithCode.errno = -2;
errorWithCode.syscall = 'scandir';
errorWithCode.path = path;
throw errorWithCode;
}
throw error;
}
}
return currentHandle;
}
private async getFileHandle(path: string, options?: { create?: boolean }): Promise<FileSystemFileHandle> {
// Guard against undefined path
if (!path || typeof path !== 'string') {
const error = new Error('ENOENT: no such file or directory, open \'undefined\'') as NodeJS.ErrnoException;
error.code = 'ENOENT';
error.errno = -2;
error.syscall = 'open';
error.path = path || 'undefined';
throw error;
}
const parentPath = this.getParentPath(path);
const fileName = this.getBaseName(path);
const parentHandle = await this.getDirectoryHandle(parentPath);
try {
return parentHandle.getFileHandle(fileName, options);
} catch (error) {
if (!options?.create) {
// Convert OPFS error to ENOENT for consistency
const errorWithCode = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
errorWithCode.code = 'ENOENT';
errorWithCode.errno = -2;
errorWithCode.syscall = 'open';
errorWithCode.path = path;
throw errorWithCode;
}
throw error;
}
}
private getParentPath(path: string): string {
const parts = path.split('/').filter(Boolean);
parts.pop(); // Remove the last part
return parts.length > 0 ? `/${parts.join('/')}` : '/';
}
private getBaseName(path: string): string {
const parts = path.split('/').filter(Boolean);
return parts[parts.length - 1] || '';
}
private async createDirectoriesRecursive(path: string): Promise<void> {
try {
// Guard against undefined path
if (!path || typeof path !== 'string') {
const error = new Error('ENOENT: no such file or directory, mkdir \'undefined\'') as NodeJS.ErrnoException;
error.code = 'ENOENT';
error.errno = -2;
error.syscall = 'mkdir';
error.path = path || 'undefined';
throw error;
}
const parts = path.split('/').filter(Boolean);
let currentHandle = await this.root;
for (const part of parts) {
try {
currentHandle = await currentHandle.getDirectoryHandle(part, { create: true });
} catch (error) {
console.error(`Failed to create directory part '${part}' in path '${path}':`, error);
// Convert to proper Node.js error
const mkdirError = new Error(`ENOENT: no such file or directory, mkdir '${path}'`) as NodeJS.ErrnoException;
mkdirError.code = 'ENOENT';
mkdirError.errno = -2;
mkdirError.syscall = 'mkdir';
mkdirError.path = path;
if (error instanceof Error) {
mkdirError.message = `${mkdirError.message}: ${error.message}`;
}
throw mkdirError;
}
}
} catch (error) {
console.error(`OPFSAdapter.createDirectoriesRecursive failed for path: ${path}`, error);
throw error;
}
}
private async copyRecursive(source: string, destination: string): Promise<void> {
const sourceStat = await this.stat(source);
if (sourceStat.isFile()) {
// Copy file
const sourceHandle = await this.getFileHandle(source);
const file = await sourceHandle.getFile();
const destHandle = await this.getFileHandle(destination, { create: true });
const writable = await destHandle.createWritable();
await writable.write(file);
await writable.close();
} else if (sourceStat.isDirectory()) {
// Copy directory
await this.mkdir(destination, { recursive: true });
const entries = await this.readdir(source);
for (const entry of entries) {
const sourceEntry = source === '/' ? `/${entry}` : `${source}/${entry}`;
const destEntry = destination === '/' ? `/${entry}` : `${destination}/${entry}`;
await this.copyRecursive(sourceEntry, destEntry);
}
}
}
private async unlinkRecursive(path: string): Promise<void> {
const stat = await this.stat(path);
if (stat.isFile()) {
await this.unlink(path);
} else if (stat.isDirectory()) {
const entries = await this.readdir(path);
for (const entry of entries) {
const entryPath = path === '/' ? `/${entry}` : `${path}/${entry}`;
await this.unlinkRecursive(entryPath);
}
// Remove the directory itself
const parentPath = this.getParentPath(path);
const dirName = this.getBaseName(path);
const parentHandle = await this.getDirectoryHandle(parentPath);
await parentHandle.removeEntry(dirName);
}
}
}
-698
View File
@@ -1,698 +0,0 @@
import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime';
/**
* Simple OPFS (Origin Private File System) adapter that implements JSRuntimeFS interface
* This version is designed to work with isomorphic-git with minimal interference
*/
export class OPFSAdapterSimple implements JSRuntimeFS {
private root: Promise<FileSystemDirectoryHandle>;
private debugMode: boolean = false;
constructor(options?: { debug?: boolean }) {
this.debugMode = options?.debug || false;
// Check if OPFS is available
if (!('storage' in navigator) ||
typeof (navigator.storage as unknown as { getDirectory: () => Promise<FileSystemDirectoryHandle> }).getDirectory !== 'function') {
throw new Error('OPFS is not supported in this browser or environment');
}
// Get the root directory handle for OPFS
this.root = (navigator.storage as unknown as { getDirectory: () => Promise<FileSystemDirectoryHandle> }).getDirectory();
if (this.debugMode) {
console.log('OPFSAdapterSimple initialized with debug mode enabled');
}
}
private log(...args: unknown[]) {
if (this.debugMode) {
console.log('[OPFSAdapter]', ...args);
}
}
private logError(...args: unknown[]) {
if (this.debugMode) {
console.error('[OPFSAdapter]', ...args);
}
}
async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, encoding: 'utf8'): Promise<string>;
async readFile(path: string, encoding: string): Promise<string>;
async readFile(path: string, encoding?: string): Promise<string | Uint8Array>;
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
this.log(`readFile called: path="${path}", encoding="${encoding}", type: ${typeof encoding}`);
try {
// Basic path validation - handle isomorphic-git calling with undefined paths
// Note: isomorphic-git sometimes calls readFile with undefined paths to test filesystem capabilities
if (!path || typeof path !== 'string' || path === 'undefined') {
this.log(`Filesystem capability test with invalid path: ${path} (type: ${typeof path}) - this is normal`);
const error = new Error(`ENOENT: no such file or directory, open '${path || 'undefined'}'`) as NodeJS.ErrnoException;
error.code = 'ENOENT';
error.errno = -2;
error.syscall = 'open';
error.path = path || 'undefined';
throw error;
}
const fileHandle = await this.getFileHandle(path);
const file = await fileHandle.getFile();
this.log(`File found: size=${file.size}, type="${file.type}", lastModified=${file.lastModified}`);
// Additional validation for Git files
if (path.includes('.git/') && file.size === 0) {
this.logError(`Warning: Git file is empty: ${path}`);
}
// Handle encoding parameter exactly like LightningFS
// Key insight: isomorphic-git sometimes passes options objects as encoding parameter
// We need to distinguish between text files (config, refs, etc.) and binary files (pack, index, objects)
// Git binary files that should ALWAYS be returned as Uint8Array
const isGitBinaryFile = path.includes('.git/objects/pack/') ||
(path.includes('.git/objects/') && !path.includes('.git/objects/info/')) ||
path.endsWith('.pack') ||
path.endsWith('.idx') ||
path.includes('.git/index');
// Git text files that should be returned as text when no explicit binary encoding is requested
const isGitTextFile = path.includes('.git/config') ||
path.includes('.git/HEAD') ||
path.includes('.git/refs/') ||
path.includes('.git/logs/') ||
path.includes('.git/info/') ||
path.includes('.git/hooks/') ||
path.includes('.git/description');
// Determine if we should return text:
// 1. Explicit utf8 encoding request
// 2. Git text files (unless explicit binary encoding)
// 3. Non-Git files (unless explicit binary encoding)
const shouldReturnText = (encoding === 'utf8' && typeof encoding === 'string') ||
(!isGitBinaryFile && (isGitTextFile || !path.includes('.git/'))) ||
(isGitTextFile && typeof encoding !== 'string');
this.log(`File type analysis: isGitBinaryFile=${isGitBinaryFile}, isGitTextFile=${isGitTextFile}, shouldReturnText=${shouldReturnText}, encoding type=${typeof encoding}`);
if (shouldReturnText) {
const text = await file.text();
this.log(`Returning text content for encoding "${encoding}", length=${text.length}`);
return text;
} else {
// No encoding or undefined, return as Uint8Array (binary data)
let arrayBuffer: ArrayBuffer;
try {
arrayBuffer = await file.arrayBuffer();
if (!arrayBuffer) {
throw new Error('ArrayBuffer is null or undefined');
}
} catch (bufferError) {
this.logError(`Failed to get ArrayBuffer for ${path}:`, bufferError);
throw new Error(`Failed to read binary data from file: ${path}`);
}
// Create a proper Uint8Array that behaves like Node.js Buffer/Uint8Array
// This is critical for isomorphic-git compatibility
let uint8Array: Uint8Array;
try {
uint8Array = new Uint8Array(arrayBuffer);
// For Git pack files and other binary Git objects, we need to be extra careful
// isomorphic-git expects very specific behavior from these arrays
if (path.includes('.git/')) {
// Create a fresh Uint8Array to avoid any browser-specific quirks
const gitCompatibleArray = new Uint8Array(uint8Array.length);
gitCompatibleArray.set(uint8Array);
// Ensure the array has proper prototype and methods
// Some isomorphic-git operations check for specific array methods
if (!gitCompatibleArray.slice || typeof gitCompatibleArray.slice !== 'function') {
this.logError(`Uint8Array missing slice method for Git file: ${path}`);
}
if (!gitCompatibleArray.subarray || typeof gitCompatibleArray.subarray !== 'function') {
this.logError(`Uint8Array missing subarray method for Git file: ${path}`);
}
uint8Array = gitCompatibleArray;
}
// Validate the array before returning
if (!uint8Array || uint8Array.length === undefined) {
throw new Error(`Invalid Uint8Array created for file: ${path}`);
}
this.log(`Returning binary content: ${uint8Array.length} bytes, constructor: ${uint8Array.constructor.name}, isGitFile: ${path.includes('.git/')}`);
return uint8Array;
} catch (arrayError) {
this.logError(`Failed to create Uint8Array for ${path}:`, arrayError);
throw new Error(`Failed to create binary array from file: ${path}`);
}
}
} catch (error) {
this.logError(`readFile failed for path="${path}":`, error);
// Enhanced error handling for isomorphic-git compatibility
let finalError: Error & NodeJS.ErrnoException;
if (error instanceof Error && (error.message.includes('NotFound') || error.name === 'NotFoundError')) {
finalError = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
finalError.code = 'ENOENT';
finalError.errno = -2;
finalError.syscall = 'open';
finalError.path = path;
} else if (error instanceof Error) {
// Wrap any other error to ensure it has required properties
finalError = error as NodeJS.ErrnoException;
if (!finalError.code) finalError.code = 'EIO';
if (!finalError.errno) finalError.errno = -5;
if (!finalError.syscall) finalError.syscall = 'read';
if (!finalError.path) finalError.path = path;
} else {
// Convert non-Error objects to proper Error
finalError = new Error(String(error)) as NodeJS.ErrnoException;
finalError.code = 'EIO';
finalError.errno = -5;
finalError.syscall = 'read';
finalError.path = path;
}
// Ensure the error has the original error information
if (error instanceof Error && error !== finalError) {
// finalError.cause = error; // Not available in older TypeScript
finalError.stack = error.stack;
}
throw finalError;
}
}
async writeFile(path: string, data: string | Uint8Array, _encoding?: string): Promise<void> {
try {
const fileHandle = await this.getFileHandle(path, { create: true });
const writable = await fileHandle.createWritable();
if (typeof data === 'string') {
await writable.write(data);
} else {
// For binary data, ensure we write it correctly
// Some browsers may have issues with Uint8Array variants
if (data instanceof Uint8Array) {
await writable.write(data);
} else {
// Convert ArrayBuffer or other array-like objects to Uint8Array
const uint8Array = new Uint8Array(data);
await writable.write(uint8Array);
}
}
await writable.close();
} catch (error) {
// Enhanced error handling for write operations
let finalError: Error & NodeJS.ErrnoException;
if (error instanceof Error && (error.message.includes('NotFound') || error.name === 'NotFoundError')) {
finalError = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
finalError.code = 'ENOENT';
finalError.errno = -2;
finalError.syscall = 'open';
finalError.path = path;
} else if (error instanceof Error) {
finalError = error as NodeJS.ErrnoException;
if (!finalError.code) finalError.code = 'EIO';
if (!finalError.errno) finalError.errno = -5;
if (!finalError.syscall) finalError.syscall = 'write';
if (!finalError.path) finalError.path = path;
} else {
finalError = new Error(String(error)) as NodeJS.ErrnoException;
finalError.code = 'EIO';
finalError.errno = -5;
finalError.syscall = 'write';
finalError.path = path;
}
if (error instanceof Error && error !== finalError) {
finalError.stack = error.stack;
}
throw finalError;
}
}
async readdir(path: string): Promise<string[]>;
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
try {
const dirHandle = await this.getDirectoryHandle(path);
const entries: string[] = [];
const directoryEntries: DirectoryEntry[] = [];
// Use asyncIterator to iterate through directory entries
const dirIterator = (dirHandle as unknown as { values: () => AsyncIterableIterator<FileSystemHandle> }).values();
let result = await dirIterator.next();
while (!result.done) {
const entry = result.value;
if (options?.withFileTypes) {
directoryEntries.push({
name: entry.name,
isDirectory: () => entry.kind === 'directory',
isFile: () => entry.kind === 'file',
});
} else {
entries.push(entry.name);
}
result = await dirIterator.next();
}
return options?.withFileTypes ? directoryEntries : entries;
} catch (error) {
// Convert DOMException to Node.js style error for isomorphic-git compatibility
if (error instanceof Error && (error.message.includes('NotFound') || error.name === 'NotFoundError')) {
const nodeError = new Error(`ENOENT: no such file or directory, scandir '${path}'`) as NodeJS.ErrnoException;
nodeError.code = 'ENOENT';
nodeError.errno = -2;
nodeError.syscall = 'scandir';
nodeError.path = path;
throw nodeError;
}
throw error;
}
}
async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {
try {
if (options?.recursive) {
await this.createDirectoriesRecursive(path);
} else {
const parentPath = this.getParentPath(path);
const dirName = this.getBaseName(path);
const parentHandle = await this.getDirectoryHandle(parentPath);
await parentHandle.getDirectoryHandle(dirName, { create: true });
}
} catch (error) {
if (error instanceof Error && (error.message.includes('NotFound') || error.name === 'NotFoundError')) {
throw new Error('ENOENT: no such file or directory');
}
throw error;
}
}
async stat(path: string): Promise<{
isDirectory(): boolean;
size?: number;
mtimeMs?: number;
isFile(): boolean;
}> {
// Basic path validation
if (!path || typeof path !== 'string') {
throw new Error('ENOENT: no such file or directory');
}
try {
const fileHandle = await this.getFileHandle(path);
const file = await fileHandle.getFile();
// Check if this is a Git symlink file
// Git symlinks are small files that contain target paths
// We'll consider files < 1024 bytes that don't contain null bytes as potential symlinks
// const isSymlink = file.size < 1024 && file.size > 0;
return {
isDirectory: () => false,
isFile: () => true,
// isSymbolicLink: () => isSymlink,
size: file.size,
mtimeMs: file.lastModified,
};
} catch {
// If not a file, try as directory
try {
await this.getDirectoryHandle(path);
return {
isDirectory: () => true,
isFile: () => false,
// isSymbolicLink: () => false,
};
} catch (dirError) {
// Enhanced error handling for isomorphic-git compatibility
let finalError: Error & NodeJS.ErrnoException;
if (dirError instanceof Error && (dirError.message.includes('NotFound') || dirError.name === 'NotFoundError')) {
finalError = new Error(`ENOENT: no such file or directory, stat '${path}'`) as NodeJS.ErrnoException;
finalError.code = 'ENOENT';
finalError.errno = -2;
finalError.syscall = 'stat';
finalError.path = path;
} else if (dirError instanceof Error) {
// Wrap any other error to ensure it has required properties
finalError = dirError as NodeJS.ErrnoException;
if (!finalError.code) finalError.code = 'UNKNOWN';
if (!finalError.errno) finalError.errno = -1;
if (!finalError.syscall) finalError.syscall = 'stat';
if (!finalError.path) finalError.path = path;
} else {
// Convert non-Error objects to proper Error
finalError = new Error(String(dirError)) as NodeJS.ErrnoException;
finalError.code = 'UNKNOWN';
finalError.errno = -1;
finalError.syscall = 'stat';
finalError.path = path;
}
// Ensure error has original error information
if (dirError instanceof Error && dirError !== finalError) {
finalError.stack = dirError.stack;
}
throw finalError;
}
}
}
async lstat(path: string): Promise<{
isDirectory(): boolean;
isFile(): boolean;
size?: number;
mtimeMs?: number;
}> {
// OPFS doesn't have real symbolic links, but we emulate them for Git
// lstat should behave the same as stat in our emulation
return this.stat(path);
}
async unlink(path: string): Promise<void> {
const parentPath = this.getParentPath(path);
const fileName = this.getBaseName(path);
const parentHandle = await this.getDirectoryHandle(parentPath);
await parentHandle.removeEntry(fileName);
}
async rmdir(path: string): Promise<void> {
const parentPath = this.getParentPath(path);
const dirName = this.getBaseName(path);
const parentHandle = await this.getDirectoryHandle(parentPath);
await parentHandle.removeEntry(dirName, { recursive: true });
}
async rename(oldPath: string, newPath: string): Promise<void> {
// OPFS doesn't have a native rename operation, so we need to copy and delete
await this.copyRecursive(oldPath, newPath);
await this.unlinkRecursive(oldPath);
}
async readlink(path: string): Promise<string> {
try {
// Basic path validation
if (!path || typeof path !== 'string') {
throw new Error('ENOENT: no such file or directory');
}
// OPFS doesn't support real symlinks, but Git uses them for .git/HEAD and refs
// We emulate symlinks by storing the target as file content
const fileHandle = await this.getFileHandle(path);
const file = await fileHandle.getFile();
const content = await file.text();
// Git symlink files contain the target path
// Remove any trailing newlines and return the target
return content.trim();
} catch (error) {
// Enhanced error handling for isomorphic-git compatibility
let finalError: Error & NodeJS.ErrnoException;
if (error instanceof Error && (error.message.includes('NotFound') || error.name === 'NotFoundError')) {
finalError = new Error(`ENOENT: no such file or directory, readlink '${path}'`) as NodeJS.ErrnoException;
finalError.code = 'ENOENT';
finalError.errno = -2;
finalError.syscall = 'readlink';
finalError.path = path;
} else if (error instanceof Error) {
// Wrap any other error to ensure it has required properties
finalError = error as NodeJS.ErrnoException;
if (!finalError.code) finalError.code = 'UNKNOWN';
if (!finalError.errno) finalError.errno = -1;
if (!finalError.syscall) finalError.syscall = 'readlink';
if (!finalError.path) finalError.path = path;
} else {
// Convert non-Error objects to proper Error
finalError = new Error(String(error)) as NodeJS.ErrnoException;
finalError.code = 'UNKNOWN';
finalError.errno = -1;
finalError.syscall = 'readlink';
finalError.path = path;
}
// Ensure error has original error information
if (error instanceof Error && error !== finalError) {
finalError.stack = error.stack;
}
throw finalError;
}
}
async symlink(target: string, path: string): Promise<void> {
try {
// Basic path validation
if (!path || typeof path !== 'string') {
throw new Error('ENOENT: no such file or directory');
}
// OPFS doesn't support real symlinks, but we can emulate them
// by writing the target as file content (this is how Git stores symlinks)
const fileHandle = await this.getFileHandle(path, { create: true });
const writable = await fileHandle.createWritable();
await writable.write(target);
await writable.close();
} catch (error) {
// Enhanced error handling for isomorphic-git compatibility
let finalError: Error & NodeJS.ErrnoException;
if (error instanceof Error && (error.message.includes('NotFound') || error.name === 'NotFoundError')) {
finalError = new Error(`ENOENT: no such file or directory, symlink '${path}'`) as NodeJS.ErrnoException;
finalError.code = 'ENOENT';
finalError.errno = -2;
finalError.syscall = 'symlink';
finalError.path = path;
} else if (error instanceof Error) {
// Wrap any other error to ensure it has required properties
finalError = error as NodeJS.ErrnoException;
if (!finalError.code) finalError.code = 'UNKNOWN';
if (!finalError.errno) finalError.errno = -1;
if (!finalError.syscall) finalError.syscall = 'symlink';
if (!finalError.path) finalError.path = path;
} else {
// Convert non-Error objects to proper Error
finalError = new Error(String(error)) as NodeJS.ErrnoException;
finalError.code = 'UNKNOWN';
finalError.errno = -1;
finalError.syscall = 'symlink';
finalError.path = path;
}
// Ensure error has original error information
if (error instanceof Error && error !== finalError) {
finalError.stack = error.stack;
}
throw finalError;
}
}
// Helper methods
private async getDirectoryHandle(path: string, options?: { create?: boolean }): Promise<FileSystemDirectoryHandle> {
if (path === '/' || path === '') {
return this.root;
}
// Basic path validation
if (!path || typeof path !== 'string') {
throw new Error('ENOENT: no such file or directory');
}
const parts = path.split('/').filter(Boolean);
let currentHandle = await this.root;
for (const part of parts) {
try {
currentHandle = await currentHandle.getDirectoryHandle(part, options);
} catch (error) {
// Enhanced error handling for isomorphic-git compatibility
let finalError: Error & NodeJS.ErrnoException;
if (error instanceof Error && (error.message.includes('NotFound') || error.name === 'NotFoundError')) {
if (options?.create) {
// If we're supposed to create, this shouldn't happen, but re-throw with better error
finalError = new Error(`Failed to create directory part '${part}' in path '${path}': ${error.message}`) as NodeJS.ErrnoException;
finalError.code = 'EIO';
finalError.errno = -5;
finalError.syscall = 'mkdir';
finalError.path = path;
} else {
// Directory doesn't exist and we're not creating it
finalError = new Error(`ENOENT: no such file or directory, stat '${path}'`) as NodeJS.ErrnoException;
finalError.code = 'ENOENT';
finalError.errno = -2;
finalError.syscall = 'stat';
finalError.path = path;
}
} else if (error instanceof Error) {
// Wrap any other error to ensure it has required properties
finalError = error as NodeJS.ErrnoException;
if (!finalError.code) finalError.code = 'UNKNOWN';
if (!finalError.errno) finalError.errno = -1;
if (!finalError.syscall) finalError.syscall = 'stat';
if (!finalError.path) finalError.path = path;
} else {
// Convert non-Error objects to proper Error
finalError = new Error(String(error)) as NodeJS.ErrnoException;
finalError.code = 'UNKNOWN';
finalError.errno = -1;
finalError.syscall = 'stat';
finalError.path = path;
}
// Ensure error has original error information
if (error instanceof Error && error !== finalError) {
finalError.stack = error.stack;
}
throw finalError;
}
}
return currentHandle;
}
private async getFileHandle(path: string, options?: { create?: boolean }): Promise<FileSystemFileHandle> {
// Basic path validation
if (!path || typeof path !== 'string') {
const error = new Error('ENOENT: no such file or directory, open \'undefined\'') as NodeJS.ErrnoException;
error.code = 'ENOENT';
error.errno = -2;
error.syscall = 'open';
error.path = 'undefined';
throw error;
}
try {
const parentPath = this.getParentPath(path);
const fileName = this.getBaseName(path);
const parentHandle = await this.getDirectoryHandle(parentPath);
return parentHandle.getFileHandle(fileName, options);
} catch (error) {
// Enhanced error handling for isomorphic-git compatibility
let finalError: Error & NodeJS.ErrnoException;
if (error instanceof Error && (error.message.includes('NotFound') || error.name === 'NotFoundError')) {
if (options?.create) {
// If we're supposed to create, this shouldn't happen
finalError = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
finalError.code = 'ENOENT';
finalError.errno = -2;
finalError.syscall = 'open';
finalError.path = path;
} else {
// File doesn't exist and we're not creating it
finalError = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
finalError.code = 'ENOENT';
finalError.errno = -2;
finalError.syscall = 'open';
finalError.path = path;
}
} else if (error instanceof Error) {
// Wrap any other error to ensure it has required properties
finalError = error as NodeJS.ErrnoException;
if (!finalError.code) finalError.code = 'UNKNOWN';
if (!finalError.errno) finalError.errno = -1;
if (!finalError.syscall) finalError.syscall = 'open';
if (!finalError.path) finalError.path = path;
} else {
// Convert non-Error objects to proper Error
finalError = new Error(String(error)) as NodeJS.ErrnoException;
finalError.code = 'UNKNOWN';
finalError.errno = -1;
finalError.syscall = 'open';
finalError.path = path;
}
// Ensure error has original error information
if (error instanceof Error && error !== finalError) {
finalError.stack = error.stack;
}
throw finalError;
}
}
private getParentPath(path: string): string {
const parts = path.split('/').filter(Boolean);
parts.pop(); // Remove the last part
return parts.length > 0 ? `/${parts.join('/')}` : '/';
}
private getBaseName(path: string): string {
const parts = path.split('/').filter(Boolean);
return parts[parts.length - 1] || '';
}
private async createDirectoriesRecursive(path: string): Promise<void> {
const parts = path.split('/').filter(Boolean);
let currentHandle = await this.root;
for (const part of parts) {
currentHandle = await currentHandle.getDirectoryHandle(part, { create: true });
}
}
private async copyRecursive(source: string, destination: string): Promise<void> {
const sourceStat = await this.stat(source);
if (sourceStat.isFile()) {
// Copy file
const sourceHandle = await this.getFileHandle(source);
const file = await sourceHandle.getFile();
const destHandle = await this.getFileHandle(destination, { create: true });
const writable = await destHandle.createWritable();
await writable.write(file);
await writable.close();
} else if (sourceStat.isDirectory()) {
// Copy directory
await this.mkdir(destination, { recursive: true });
const entries = await this.readdir(source);
for (const entry of entries) {
const sourceEntry = source === '/' ? `/${entry}` : `${source}/${entry}`;
const destEntry = destination === '/' ? `/${entry}` : `${destination}/${entry}`;
await this.copyRecursive(sourceEntry, destEntry);
}
}
}
private async unlinkRecursive(path: string): Promise<void> {
const stat = await this.stat(path);
if (stat.isFile()) {
await this.unlink(path);
} else if (stat.isDirectory()) {
const entries = await this.readdir(path);
for (const entry of entries) {
const entryPath = path === '/' ? `/${entry}` : `${path}/${entry}`;
await this.unlinkRecursive(entryPath);
}
// Remove the directory itself
const parentPath = this.getParentPath(path);
const dirName = this.getBaseName(path);
const parentHandle = await this.getDirectoryHandle(parentPath);
await parentHandle.removeEntry(dirName);
}
}
}
+11 -55
View File
@@ -1,27 +1,11 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { describe, it, expect, beforeEach } from 'vitest';
import { ProjectsManager } from './ProjectsManager';
import { JSRuntimeFS } from './JSRuntime';
import { Git } from './git';
import type { NPool } from '@nostrify/nostrify';
const createMockNostr = (): NPool => ({
req: vi.fn(),
query: vi.fn(),
event: vi.fn(),
group: vi.fn(),
relay: vi.fn(),
relays: new Map(),
close: vi.fn(),
}) as unknown as NPool;
// Mock filesystem for testing
class MockFS implements JSRuntimeFS {
class MockFS {
private files: Map<string, string | Uint8Array> = new Map();
private dirs: Set<string> = new Set();
async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, encoding: "utf8"): Promise<string>;
async readFile(path: string, encoding: string): Promise<string | Uint8Array>;
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
const content = this.files.get(path);
if (content === undefined) {
@@ -29,18 +13,10 @@ class MockFS implements JSRuntimeFS {
error.code = 'ENOENT';
throw error;
}
if (encoding === 'utf8') {
if (typeof content === 'string') {
return content;
}
// Convert Uint8Array to string
return new TextDecoder('utf-8').decode(content as Uint8Array);
if (encoding === 'utf8' && typeof content === 'string') {
return content;
}
if (typeof content === 'string') {
// Convert string to Uint8Array
return new TextEncoder().encode(content);
}
return content as Uint8Array;
return content;
}
async writeFile(path: string, data: string | Uint8Array): Promise<void> {
@@ -52,14 +28,13 @@ class MockFS implements JSRuntimeFS {
}
}
// @ts-expect-error I don't know how to type this properly
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
async readdir(path: string): Promise<string[]> {
if (!this.dirs.has(path)) {
const error = new Error(`ENOENT: no such file or directory, scandir '${path}'`) as NodeJS.ErrnoException;
error.code = 'ENOENT';
throw error;
}
const entries: string[] = [];
// Find subdirectories
@@ -76,22 +51,7 @@ class MockFS implements JSRuntimeFS {
}
}
const uniqueEntries = [...new Set(entries)];
if (options && options.withFileTypes) {
// Provide a minimal DirectoryEntry mock
return uniqueEntries.map(name => {
const fullPath = path.endsWith('/') ? path + name : path + '/' + name;
const isDir = this.dirs.has(fullPath);
return {
name,
isDirectory: () => isDir,
isFile: () => !isDir,
} as unknown as DirectoryEntry;
});
}
return uniqueEntries;
return [...new Set(entries)];
}
async mkdir(path: string): Promise<void> {
@@ -128,16 +88,12 @@ class MockFS implements JSRuntimeFS {
}
describe('ProjectsManager', () => {
let fs: JSRuntimeFS;
let git: Git;
let nostr: NPool;
let fs: MockFS;
let projectsManager: ProjectsManager;
beforeEach(() => {
fs = new MockFS() as unknown as JSRuntimeFS;
nostr = createMockNostr();
git = new Git({ fs, nostr });
projectsManager = new ProjectsManager({ fs, git });
fs = new MockFS();
projectsManager = new ProjectsManager(fs as unknown as import('./JSRuntime').JSRuntimeFS);
});
describe('getProjects', () => {
+46 -160
View File
@@ -1,7 +1,8 @@
import { Buffer } from 'buffer';
import type { Git } from '@/lib/git';
import { Git } from '@/lib/git';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
// Polyfill Buffer for browser
if (typeof window !== 'undefined') {
(window as { Buffer?: typeof Buffer }).Buffer = Buffer;
@@ -17,19 +18,14 @@ export interface Project {
lastModified: Date;
}
export interface ProjectsManagerOptions {
fs: JSRuntimeFS;
git: Git;
}
export class ProjectsManager {
fs: JSRuntimeFS;
git: Git;
dir: string;
constructor(options: ProjectsManagerOptions) {
this.fs = options.fs;
this.git = options.git;
constructor(fs: JSRuntimeFS) {
this.fs = fs;
this.git = new Git(fs, 'https://cors.isomorphic-git.org');
this.dir = '/projects';
}
@@ -42,94 +38,60 @@ export class ProjectsManager {
}
async createProject(name: string, customId?: string): Promise<Project> {
console.log(`Creating project: ${name}, customId: ${customId}`);
const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId, { depth: 1 });
console.log(`Project cloned at path: ${project.path}`);
try {
await this.fs.mkdir(this.dir + `/${project.id}/.ai/history`, { recursive: true });
console.log(`Created .ai/history directory for project ${project.id}`);
} catch (error) {
console.log(`Directory .ai/history might already exist for project ${project.id}:`, error);
} catch {
// Directory might already exist
}
// Delete README.md if it exists
try {
await this.fs.unlink(`${project.path}/README.md`);
console.log(`Deleted README.md for project ${project.id}`);
} catch (error) {
console.log(`README.md might not exist for project ${project.id}:`, error);
} catch {
// README.md might not exist, ignore error
}
// Delete .git directory and reinitialize
try {
await this.deleteDirectory(`${project.path}/.git`);
console.log(`Deleted .git directory for project ${project.id}`);
} catch (error) {
console.log(`.git directory might not exist for project ${project.id}:`, error);
} catch {
// .git directory might not exist, ignore error
}
// Initialize new git repository
try {
await this.git.init({
dir: project.path,
defaultBranch: 'main',
});
console.log(`Initialized git repository for project ${project.id}`);
} catch (error) {
console.error(`Failed to initialize git repository for project ${project.id}:`, error);
throw new Error(`Failed to initialize git repository: ${error}`);
}
await this.git.init({
dir: project.path,
defaultBranch: 'main',
});
// Add all files to git
try {
const files = await this.getAllFiles(project.path);
console.log(`Found ${files.length} files to add to git for project ${project.id}`);
for (const file of files) {
// Skip .git directory and other hidden files we don't want to track
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
try {
await this.git.add({
dir: project.path,
filepath: file,
});
} catch (error) {
console.warn(`Failed to add file ${file} to git:`, error);
}
}
const files = await this.getAllFiles(project.path);
for (const file of files) {
// Skip .git directory and other hidden files we don't want to track
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
await this.git.add({
dir: project.path,
filepath: file,
});
}
} catch (error) {
console.error(`Failed to get files for project ${project.id}:`, error);
// Continue with commit even if we can't get all files
}
// Make initial commit
try {
await this.git.commit({
dir: project.path,
message: 'New project created with Shakespeare',
author: {
name: 'shakespeare.diy',
email: '[email protected]',
},
});
console.log(`Made initial commit for project ${project.id}`);
} catch (error) {
console.error(`Failed to make initial commit for project ${project.id}:`, error);
throw new Error(`Failed to make initial commit: ${error}`);
}
await this.git.commit({
dir: project.path,
message: 'New project created with Shakespeare',
author: {
name: 'shakespeare.diy',
email: 'assistant@shakespeare.diy',
},
});
return project;
}
async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise<Project> {
console.log(`Cloning project: ${name}, repo: ${repoUrl}, customId: ${customId}`);
const id = customId || await this.generateUniqueProjectId(name);
// Check if project with this ID already exists when using custom ID
@@ -138,103 +100,28 @@ export class ProjectsManager {
}
const projectPath = `${this.dir}/${id}`;
console.log(`Project will be created at: ${projectPath}`);
try {
await this.fs.mkdir(projectPath);
console.log(`Created project directory: ${projectPath}`);
} catch (error) {
console.error(`Failed to create project directory ${projectPath}:`, error);
throw new Error(`Failed to create project directory: ${error}`);
}
await this.fs.mkdir(projectPath);
// Clone the repository (Git class now handles Nostr URIs automatically)
try {
console.log(`Starting clone operation: ${repoUrl} -> ${projectPath}`);
console.log(`Clone options:`, { singleBranch: true, depth: options?.depth });
// Add a timeout to prevent hanging
const cloneTimeout = 60000; // 60 seconds
const clonePromise = this.git.clone({
dir: projectPath,
url: repoUrl,
singleBranch: true,
depth: options?.depth, // Use depth if provided, otherwise clone full history
});
const timeoutPromise = new Promise<never>((_, reject) => {
setTimeout(() => {
reject(new Error(`Clone operation timed out after ${cloneTimeout}ms`));
}, cloneTimeout);
});
await Promise.race([clonePromise, timeoutPromise]);
console.log(`Successfully cloned repository to: ${projectPath}`);
} catch (error) {
console.error(`Failed to clone repository ${repoUrl} to ${projectPath}:`, error);
// Log additional debugging information
if (error instanceof Error) {
console.error(`Error name: ${error.name}`);
console.error(`Error message: ${error.message}`);
console.error(`Error stack:`, error.stack);
// Check if it's a filesystem-related error that suggests OPFS incompatibility
const isOPFSCompatibilityIssue =
error.message.includes('Cannot read properties of undefined') ||
error.message.includes('readObjectPacked') ||
error.message.includes('reading \'error\'') ||
error.message.includes('TypeError') && error.stack?.includes('isomorphic-git');
if (isOPFSCompatibilityIssue) {
console.error('🚨 DETECTED: Filesystem compatibility issue with isomorphic-git and OPFS');
console.error('📋 ISSUE: isomorphic-git expects Node.js-style filesystem behavior, but OPFS has subtle differences');
console.error('💡 SOLUTION: This project works best with LightningFS for Git operations');
console.error('⚙️ RECOMMENDATION: Change filesystem setting to "lightningfs" in preferences');
// Provide a more user-friendly error message
throw new Error(
'Git clone failed due to filesystem compatibility issues. ' +
'OPFS (Origin Private File System) has some compatibility limitations with Git operations. ' +
'Please switch to LightningFS in your preferences for better Git support.'
);
}
}
// Clean up the failed project directory
try {
await this.deleteDirectory(projectPath);
console.log(`Cleaned up failed project directory: ${projectPath}`);
} catch (cleanupError) {
console.warn(`Failed to clean up project directory after clone failure:`, cleanupError);
}
throw new Error(`Failed to clone repository: ${error}`);
}
// Clone the repository
await this.git.clone({
dir: projectPath,
url: repoUrl,
singleBranch: true,
depth: options?.depth, // Use depth if provided, otherwise clone full history
});
// Get filesystem stats for timestamps
try {
const stats = await this.fs.stat(projectPath);
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
console.log(`Project stats retrieved, timestamp: ${timestamp}`);
const stats = await this.fs.stat(projectPath);
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
// Return the full project object with dynamically generated properties
return {
id,
name: this.formatProjectName(id), // Use formatted directory name
path: projectPath,
lastModified: timestamp,
};
} catch (error) {
console.error(`Failed to get stats for project path ${projectPath}:`, error);
// Return project with current timestamp if stats fail
return {
id,
name: this.formatProjectName(id),
path: projectPath,
lastModified: new Date(),
};
}
// Return the full project object with dynamically generated properties
return {
id,
name: this.formatProjectName(id), // Use formatted directory name
path: projectPath,
lastModified: timestamp,
};
}
async getProjects(): Promise<Project[]> {
@@ -414,8 +301,7 @@ export class ProjectsManager {
const projectPath = `${this.dir}/${id}`;
await this.fs.stat(projectPath);
return true;
} catch (error) {
console.log(`Project ${id} does not exist or stat failed:`, error);
} catch {
return false;
}
}
-98
View File
@@ -1,98 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { SessionManager, type AIMessage } from './SessionManager';
import type { JSRuntimeFS } from './JSRuntime';
// Mock the filesystem
const mockFS: JSRuntimeFS = {
readFile: vi.fn(),
writeFile: vi.fn(),
readdir: vi.fn(),
mkdir: vi.fn(),
rmdir: vi.fn(),
unlink: vi.fn(),
stat: vi.fn(),
exists: vi.fn(),
copyFile: vi.fn(),
rename: vi.fn(),
symlink: vi.fn(),
readlink: vi.fn(),
chmod: vi.fn(),
chown: vi.fn(),
utimes: vi.fn(),
realpath: vi.fn(),
} as unknown as JSRuntimeFS;
describe('SessionManager', () => {
let sessionManager: SessionManager;
const mockAISettings = {
providers: [
{
id: 'test-provider',
baseURL: 'https://api.test.com',
apiKey: 'test-key'
}
]
};
beforeEach(() => {
sessionManager = new SessionManager(mockFS, mockAISettings);
});
it('should initialize streaming message with reasoning content', async () => {
const projectId = 'test-project';
const tools = {};
const customTools = {};
const session = await sessionManager.loadSession(projectId, tools, customTools);
expect(session.projectId).toBe(projectId);
expect(session.streamingMessage).toBeUndefined();
});
it('should emit streamingUpdate events with reasoning content', () => {
const projectId = 'test-project';
const mockListener = vi.fn();
sessionManager.on('streamingUpdate', mockListener);
// Simulate a streaming update with reasoning content
sessionManager.emit('streamingUpdate', projectId, 'content', 'reasoning', undefined);
expect(mockListener).toHaveBeenCalledWith(projectId, 'content', 'reasoning', undefined);
});
it('should handle streaming message with reasoning content', async () => {
const projectId = 'test-project';
const tools = {};
const customTools = {};
const session = await sessionManager.loadSession(projectId, tools, customTools);
// Manually set a streaming message to test the structure
session.streamingMessage = {
role: 'assistant',
content: 'test content',
reasoning_content: 'test reasoning',
tool_calls: undefined
};
expect(session.streamingMessage.reasoning_content).toBe('test reasoning');
expect(session.streamingMessage.content).toBe('test content');
});
it('should support assistant messages with reasoning content', () => {
// Test that AIMessage type supports reasoning content
const messageWithReasoning: AIMessage = {
role: 'assistant',
content: 'Here is my response',
reasoning_content: 'Let me think about this step by step...'
};
expect(messageWithReasoning.role).toBe('assistant');
expect(messageWithReasoning.content).toBe('Here is my response');
expect('reasoning_content' in messageWithReasoning).toBe(true);
if ('reasoning_content' in messageWithReasoning) {
expect(messageWithReasoning.reasoning_content).toBe('Let me think about this step by step...');
}
});
});
+6 -26
View File
@@ -5,14 +5,8 @@ import { parseProviderModel } from './parseProviderModel';
import { createAIClient } from './ai-client';
import type { Tool } from './tools/Tool';
import type { NUser } from '@nostrify/react/login';
import type { AIProvider } from '@/contexts/AISettingsContext';
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
role: 'assistant';
content: string;
reasoning_content?: string;
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
};
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;
export interface SessionState {
projectId: string;
@@ -24,7 +18,6 @@ export interface SessionState {
streamingMessage?: {
role: 'assistant';
content: string;
reasoning_content?: string;
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
};
isLoading: boolean;
@@ -39,7 +32,7 @@ export interface SessionManagerEvents {
sessionCreated: (projectId: string) => void;
sessionDeleted: (projectId: string) => void;
messageAdded: (projectId: string, message: AIMessage) => void;
streamingUpdate: (projectId: string, content: string, reasoningContent?: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
streamingUpdate: (projectId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
loadingChanged: (projectId: string, isLoading: boolean) => void;
costUpdated: (projectId: string, totalCost: number) => void;
contextUsageUpdated: (projectId: string, inputTokens: number) => void;
@@ -53,13 +46,13 @@ export class SessionManager {
private sessions = new Map<string, SessionState>();
private listeners: Partial<Record<keyof SessionManagerEvents, Set<(...args: unknown[]) => void>>> = {};
private fs: JSRuntimeFS;
private aiSettings: { providers: AIProvider[] };
private aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string; nostr?: boolean }> };
private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>;
private getCurrentUser?: () => NUser | undefined;
constructor(
fs: JSRuntimeFS,
aiSettings: { providers: AIProvider[] },
aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string; nostr?: boolean }> },
getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>,
getCurrentUser?: () => NUser | undefined
) {
@@ -226,7 +219,6 @@ export class SessionManager {
session.streamingMessage = {
role: 'assistant',
content: '',
reasoning_content: '',
tool_calls: undefined
};
@@ -253,7 +245,6 @@ export class SessionManager {
});
let accumulatedContent = '';
let accumulatedReasoningContent = '';
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
let finishReason: string | null = null;
@@ -269,17 +260,7 @@ export class SessionManager {
accumulatedContent += delta.content;
if (session.streamingMessage) {
session.streamingMessage.content += delta.content;
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.reasoning_content, session.streamingMessage.tool_calls);
}
}
// Handle reasoning content if present (some providers may include this)
const deltaWithReasoning = delta as { reasoning_content?: string };
if (deltaWithReasoning?.reasoning_content) {
accumulatedReasoningContent += deltaWithReasoning.reasoning_content;
if (session.streamingMessage) {
session.streamingMessage.reasoning_content += deltaWithReasoning.reasoning_content;
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.reasoning_content, session.streamingMessage.tool_calls);
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.tool_calls);
}
}
@@ -302,7 +283,7 @@ export class SessionManager {
if (session.streamingMessage) {
session.streamingMessage.tool_calls = accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined;
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.reasoning_content, session.streamingMessage.tool_calls);
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.tool_calls);
}
}
@@ -323,7 +304,6 @@ export class SessionManager {
const assistantMessage: AIMessage = {
role: 'assistant',
content: accumulatedContent,
...(accumulatedReasoningContent && { reasoning_content: accumulatedReasoningContent }),
...(accumulatedToolCalls.length > 0 && { tool_calls: accumulatedToolCalls })
};
+2 -5
View File
@@ -1,5 +1,6 @@
import OpenAI from 'openai';
import { NIP98Client } from '@nostrify/nostrify';
import type { AIConnection } from '@/contexts/AISettingsContext';
import type { NUser } from '@nostrify/react/login';
/**
@@ -7,11 +8,7 @@ import type { NUser } from '@nostrify/react/login';
* If the connection requires Nostr authentication (NIP-98), it will use
* the NIP98Client for authenticated requests.
*/
export function createAIClient(connection: {
baseURL: string;
apiKey?: string;
nostr?: boolean;
}, user?: NUser): OpenAI {
export function createAIClient(connection: AIConnection, user?: NUser): OpenAI {
const baseConfig: ConstructorParameters<typeof OpenAI>[0] = {
baseURL: connection.baseURL,
apiKey: connection.apiKey ?? '',
-21
View File
@@ -44,23 +44,6 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
};
});
// node built-in modules
build.onResolve({ filter: /^node:/ }, (args) => {
const moduleName = args.path.slice(5);
switch (moduleName) {
case "buffer":
return {
path: `https://esm.sh/${moduleName}?target=${target ?? "esnext"}`,
namespace: "esm",
};
default:
return {
errors: [{ text: `Module not found: ${args.path}` }],
};
}
});
// Handle bare imports like "react"
build.onResolve({ filter: /^[^./].*/ }, (args) => {
const packageName = args.path.startsWith("@")
@@ -78,10 +61,6 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
// fallthrough
}
if (packageName.startsWith("@jsr/")) {
keys.push(`node_modules/@${packageName.slice(5).replace("__", "/")}`);
}
keys.push(`node_modules/${packageName}`);
const packageInfo = keys
+1
View File
@@ -73,6 +73,7 @@ async function tryFileVariants(
return indexFile;
}
}
throw new Error("Directory without index file");
}
// Try direct file with extensions
+2 -3
View File
@@ -78,16 +78,15 @@ Change the current working directory.
**Examples:**
```bash
cd # Stay in current directory
cd # Go to project root
cd src/ # Change to src directory
cd .. # Go to parent directory
cd . # Stay in current directory
cd /projects/my-project # Change to absolute path
```
**Features:**
- Changes working directory for subsequent commands
- Supports both relative and absolute paths
- Supports relative paths (., .., subdirectories)
- Validates target exists and is a directory
- Updates shell working directory state
+1 -1
View File
@@ -1,4 +1,4 @@
import { join } from "path-browserify";
import { join } from "@std/path";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
+2 -16
View File
@@ -98,25 +98,11 @@ describe('CdCommand', () => {
expect(result.stderr).toContain('Not a directory');
});
it('should handle absolute paths to non-existent directories', async () => {
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory'));
it('should reject absolute paths', async () => {
const result = await cdCommand.execute(['/absolute/path'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('No such file or directory');
});
it('should handle absolute paths to existing directories', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
const result = await cdCommand.execute(['/projects/my-project'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.newCwd).toBe('/projects/my-project');
expect(result.stderr).toContain('absolute paths are not supported');
});
it('should reject too many arguments', async () => {
+9 -9
View File
@@ -1,8 +1,7 @@
import { join, resolve, dirname } from "path-browserify";
import { join, resolve, dirname } from "@std/path";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { isAbsolutePath } from "../security";
/**
* Implementation of the 'cd' command
@@ -32,19 +31,20 @@ export class CdCommand implements ShellCommand {
return createErrorResult(`${this.name}: too many arguments`);
}
// Handle both absolute and relative paths
let newCwd: string;
// Handle absolute paths
if (targetPath.startsWith('/') || targetPath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(targetPath)) {
return createErrorResult(`${this.name}: absolute paths are not supported: ${targetPath}`);
}
if (isAbsolutePath(targetPath)) {
// Absolute path - use it directly
newCwd = targetPath;
} else if (targetPath === '.') {
// Resolve the new path
let newCwd: string;
if (targetPath === '.') {
// Current directory
newCwd = cwd;
} else if (targetPath === '..') {
// Parent directory
const parentPath = dirname(cwd);
// Don't allow going above the filesystem root
// Don't allow going above the project root
if (parentPath === cwd) {
return createErrorResult(`${this.name}: cannot access parent directory: Permission denied`);
}
+1 -1
View File
@@ -1,4 +1,4 @@
import { join, dirname, basename } from "path-browserify";
import { join, dirname, basename } from "@std/path";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
+1 -1
View File
@@ -1,4 +1,4 @@
import { join } from "path-browserify";
import { join } from "@std/path";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
+1 -1
View File
@@ -1,4 +1,4 @@
import { join } from "path-browserify";
import { join } from "@std/path";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
+1 -1
View File
@@ -1,4 +1,4 @@
import { join } from "path-browserify";
import { join } from "@std/path";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
+1 -1
View File
@@ -1,4 +1,4 @@
import { join, basename } from "path-browserify";
import { join, basename } from "@std/path";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff. Show more