mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f09f1436ae |
No files matched your search
+3
-3
@@ -2,14 +2,14 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Shakespeare - AI-Powered Nostr Development</title>
|
||||
<meta name="description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment">
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:title" content="Shakespeare - AI-Powered Nostr Development">
|
||||
<meta property="og:description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment">
|
||||
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
||||
<link rel="icon" type="image/png" href="/shakespeare.png">
|
||||
<!-- <meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:"> -->
|
||||
<link rel="icon" type="image/png" href="/favicon.png">
|
||||
<link rel="manifest" href="/manifest.webmanifest">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -1,45 +1,35 @@
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
|
||||
<!-- saved from url=(0053)https://www.gnu.org/licenses/agpl-3.0-standalone.html -->
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
|
||||
<title>GNU Affero General Public License - GNU Project - Free Software Foundation (FSF)</title>
|
||||
<link rel="alternate" type="application/rdf+xml" href="http://www.gnu.org/licenses/agpl-3.0.rdf">
|
||||
</head>
|
||||
<body>
|
||||
<h3 style="text-align: center;">GNU AFFERO GENERAL PUBLIC LICENSE</h3>
|
||||
<p style="text-align: center;">Version 3, 19 November 2007</p>
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
<p>Copyright © 2007 Free Software Foundation,
|
||||
Inc. <<a href="https://fsf.org/">https://fsf.org/</a>>
|
||||
<br>
|
||||
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.</p>
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
<h4 id="preamble">Preamble</h4>
|
||||
Preamble
|
||||
|
||||
<p>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.</p>
|
||||
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.
|
||||
|
||||
<p>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.</p>
|
||||
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.
|
||||
|
||||
<p>When we speak of free software, we are referring to freedom, not
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
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.</p>
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
<p>Developers that use our General Public Licenses protect your rights
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.</p>
|
||||
and/or modify the software.
|
||||
|
||||
<p>A secondary benefit of defending all users' freedom is that
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
@@ -47,79 +37,78 @@ 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.</p>
|
||||
source code to the public.
|
||||
|
||||
<p>The GNU Affero General Public License is designed specifically to
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.</p>
|
||||
code of the modified version.
|
||||
|
||||
<p>An older license, called the Affero General Public License and
|
||||
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.</p>
|
||||
this license.
|
||||
|
||||
<p>The precise terms and conditions for copying, distribution and
|
||||
modification follow.</p>
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
<h4 id="terms">TERMS AND CONDITIONS</h4>
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
<h4 id="section0">0. Definitions.</h4>
|
||||
0. Definitions.
|
||||
|
||||
<p>"This License" refers to version 3 of the GNU Affero General Public
|
||||
License.</p>
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
<p>"Copyright" also means copyright-like laws that apply to other kinds
|
||||
of works, such as semiconductor masks.</p>
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
<p>"The Program" refers to any copyrightable work licensed under this
|
||||
"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.</p>
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
<p>To "modify" a work means to copy from or adapt all or part of the work
|
||||
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.</p>
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
<p>A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.</p>
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
<p>To "propagate" a work means to do anything with it that, without
|
||||
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.</p>
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
<p>To "convey" a work means any kind of propagation that enables other
|
||||
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.</p>
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
<p>An interactive user interface displays "Appropriate Legal Notices"
|
||||
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.</p>
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
<h4 id="section1">1. Source Code.</h4>
|
||||
1. Source Code.
|
||||
|
||||
<p>The "source code" for a work means the preferred form of the work
|
||||
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.</p>
|
||||
form of a work.
|
||||
|
||||
<p>A "Standard Interface" means an interface that either is an official
|
||||
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.</p>
|
||||
is widely used among developers working in that language.
|
||||
|
||||
<p>The "System Libraries" of an executable work include anything, other
|
||||
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
|
||||
@@ -128,9 +117,9 @@ 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.</p>
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
<p>The "Corresponding Source" for a work in object code form means all
|
||||
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
|
||||
@@ -141,26 +130,26 @@ 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.</p>
|
||||
subprograms and other parts of the work.
|
||||
|
||||
<p>The Corresponding Source need not include anything that users
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.</p>
|
||||
Source.
|
||||
|
||||
<p>The Corresponding Source for a work in source code form is that
|
||||
same work.</p>
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
<h4 id="section2">2. Basic Permissions.</h4>
|
||||
2. Basic Permissions.
|
||||
|
||||
<p>All rights granted under this License are granted for the term of
|
||||
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.</p>
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
<p>You may make, run and propagate covered works that you do not
|
||||
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
|
||||
@@ -169,73 +158,69 @@ 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.</p>
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
<p>Conveying under any other circumstances is permitted solely under
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.</p>
|
||||
makes it unnecessary.
|
||||
|
||||
<h4 id="section3">3. Protecting Users' Legal Rights From Anti-Circumvention Law.</h4>
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
<p>No covered work shall be deemed part of an effective technological
|
||||
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.</p>
|
||||
measures.
|
||||
|
||||
<p>When you convey a covered work, you waive any legal power to forbid
|
||||
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.</p>
|
||||
technological measures.
|
||||
|
||||
<h4 id="section4">4. Conveying Verbatim Copies.</h4>
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
<p>You may convey verbatim copies of the Program's source code as you
|
||||
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.</p>
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
<p>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.</p>
|
||||
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.
|
||||
|
||||
<h4 id="section5">5. Conveying Modified Source Versions.</h4>
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
<p>You may convey a work based on the Program, or the modifications to
|
||||
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:</p>
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
<ul>
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
<li>a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.</li>
|
||||
|
||||
<li>b) The work must carry prominent notices stating that it is
|
||||
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".</li>
|
||||
"keep intact all notices".
|
||||
|
||||
<li>c) You must license the entire work, as a whole, under this
|
||||
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.</li>
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
<li>d) If the work has interactive user interfaces, each must display
|
||||
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.</li>
|
||||
work need not make them do so.
|
||||
|
||||
</ul>
|
||||
|
||||
<p>A compilation of a covered work with other separate and independent
|
||||
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
|
||||
@@ -243,23 +228,21 @@ in or on a volume of a storage or distribution medium, is called an
|
||||
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.</p>
|
||||
parts of the aggregate.
|
||||
|
||||
<h4 id="section6">6. Conveying Non-Source Forms.</h4>
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
<p>You may convey a covered work in object code form under the terms
|
||||
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:</p>
|
||||
in one of these ways:
|
||||
|
||||
<ul>
|
||||
|
||||
<li>a) Convey the object code in, or embodied in, a physical product
|
||||
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.</li>
|
||||
customarily used for software interchange.
|
||||
|
||||
<li>b) Convey the object code in, or embodied in, a physical product
|
||||
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
|
||||
@@ -269,15 +252,15 @@ in one of these ways:</p>
|
||||
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.</li>
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
<li>c) Convey individual copies of the object code with a copy of the
|
||||
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.</li>
|
||||
with subsection 6b.
|
||||
|
||||
<li>d) Convey the object code by offering access from a designated
|
||||
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
|
||||
@@ -288,20 +271,18 @@ in one of these ways:</p>
|
||||
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.</li>
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
<li>e) Convey the object code using peer-to-peer transmission, provided
|
||||
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.</li>
|
||||
charge under subsection 6d.
|
||||
|
||||
</ul>
|
||||
|
||||
<p>A separable portion of the object code, whose source code is excluded
|
||||
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.</p>
|
||||
included in conveying the object code work.
|
||||
|
||||
<p>A "User Product" is either (1) a "consumer product", which means any
|
||||
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,
|
||||
@@ -312,17 +293,17 @@ 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.</p>
|
||||
the only significant mode of use of the product.
|
||||
|
||||
<p>"Installation Information" for a User Product means any methods,
|
||||
"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.</p>
|
||||
modification has been made.
|
||||
|
||||
<p>If you convey an object code work under this section in, or with, or
|
||||
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
|
||||
@@ -331,137 +312,133 @@ 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).</p>
|
||||
been installed in ROM).
|
||||
|
||||
<p>The requirement to provide Installation Information does not include a
|
||||
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.</p>
|
||||
protocols for communication across the network.
|
||||
|
||||
<p>Corresponding Source conveyed, and Installation Information provided,
|
||||
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.</p>
|
||||
unpacking, reading or copying.
|
||||
|
||||
<h4 id="section7">7. Additional Terms.</h4>
|
||||
7. Additional Terms.
|
||||
|
||||
<p>"Additional permissions" are terms that supplement the terms of this
|
||||
"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.</p>
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
<p>When you convey a copy of a covered work, you may at your option
|
||||
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.</p>
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
<p>Notwithstanding any other provision of this License, for material you
|
||||
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:</p>
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
<ul>
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
<li>a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or</li>
|
||||
|
||||
<li>b) Requiring preservation of specified reasonable legal notices 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</li>
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
<li>c) Prohibiting misrepresentation of the origin of that material, 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</li>
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
<li>d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or</li>
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
<li>e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or</li>
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
<li>f) Requiring indemnification of licensors and authors of that
|
||||
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.</li>
|
||||
those licensors and authors.
|
||||
|
||||
</ul>
|
||||
|
||||
<p>All other non-permissive additional terms are considered "further
|
||||
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.</p>
|
||||
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.
|
||||
|
||||
<p>If you add terms to a covered work in accord with this section, you
|
||||
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.</p>
|
||||
where to find the applicable terms.
|
||||
|
||||
<p>Additional terms, permissive or non-permissive, may be stated in the
|
||||
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.</p>
|
||||
the above requirements apply either way.
|
||||
|
||||
<h4 id="section8">8. Termination.</h4>
|
||||
8. Termination.
|
||||
|
||||
<p>You may not propagate or modify a covered work except as expressly
|
||||
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).</p>
|
||||
paragraph of section 11).
|
||||
|
||||
<p>However, if you cease all violation of this License, then your
|
||||
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.</p>
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
<p>Moreover, your license from a particular copyright holder is
|
||||
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.</p>
|
||||
your receipt of the notice.
|
||||
|
||||
<p>Termination of your rights under this section does not terminate the
|
||||
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.</p>
|
||||
material under section 10.
|
||||
|
||||
<h4 id="section9">9. Acceptance Not Required for Having Copies.</h4>
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
<p>You are not required to accept this License in order to receive or
|
||||
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.</p>
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
<h4 id="section10">10. Automatic Licensing of Downstream Recipients.</h4>
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
<p>Each time you convey a covered work, the recipient automatically
|
||||
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.</p>
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
<p>An "entity transaction" is a transaction transferring control of an
|
||||
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
|
||||
@@ -469,23 +446,23 @@ 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.</p>
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
<p>You may not impose any further restrictions on the exercise of the
|
||||
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.</p>
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
<h4 id="section11">11. Patents.</h4>
|
||||
11. Patents.
|
||||
|
||||
<p>A "contributor" is a copyright holder who authorizes use under this
|
||||
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".</p>
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
<p>A contributor's "essential patent claims" are all patent claims
|
||||
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,
|
||||
@@ -493,21 +470,21 @@ 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.</p>
|
||||
this License.
|
||||
|
||||
<p>Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
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.</p>
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
<p>In the following three paragraphs, a "patent license" is any express
|
||||
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.</p>
|
||||
patent against the party.
|
||||
|
||||
<p>If you convey a covered work, knowingly relying on a patent license,
|
||||
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,
|
||||
@@ -519,17 +496,17 @@ 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.</p>
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
<p>If, pursuant to or in connection with a single transaction or
|
||||
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.</p>
|
||||
work and works based on it.
|
||||
|
||||
<p>A patent license is "discriminatory" if it does not include within
|
||||
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
|
||||
@@ -542,15 +519,15 @@ 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.</p>
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
<p>Nothing in this License shall be construed as excluding or limiting
|
||||
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.</p>
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
<h4 id="section12">12. No Surrender of Others' Freedom.</h4>
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
<p>If conditions are imposed on you (whether by court order, agreement or
|
||||
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
|
||||
@@ -558,11 +535,11 @@ 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.</p>
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
<h4 id="section13">13. Remote Network Interaction; Use with the GNU General Public License.</h4>
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
<p>Notwithstanding any other provision of this License, if you modify the
|
||||
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
|
||||
@@ -571,56 +548,56 @@ 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.</p>
|
||||
following paragraph.
|
||||
|
||||
<p>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.</p>
|
||||
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.
|
||||
|
||||
<h4 id="section14">14. Revised Versions of this License.</h4>
|
||||
14. Revised Versions of this License.
|
||||
|
||||
<p>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.</p>
|
||||
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.
|
||||
|
||||
<p>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.</p>
|
||||
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.
|
||||
|
||||
<p>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.</p>
|
||||
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.
|
||||
|
||||
<p>Later license versions may give you additional or different
|
||||
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.</p>
|
||||
later version.
|
||||
|
||||
<h4 id="section15">15. Disclaimer of Warranty.</h4>
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
<p>THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
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.</p>
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
<h4 id="section16">16. Limitation of Liability.</h4>
|
||||
16. Limitation of Liability.
|
||||
|
||||
<p>IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
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
|
||||
@@ -628,37 +605,37 @@ 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.</p>
|
||||
SUCH DAMAGES.
|
||||
|
||||
<h4 id="section17">17. Interpretation of Sections 15 and 16.</h4>
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
<p>If the disclaimer of warranty and limitation of liability provided
|
||||
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.</p>
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
<p>END OF TERMS AND CONDITIONS</p>
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
<h4 id="howto">How to Apply These Terms to Your New Programs</h4>
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
<p>If you develop a new program, and you want it to be of the greatest
|
||||
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.</p>
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
<p>To do so, attach the following notices to the program. It is safest
|
||||
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.</p>
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<pre> <one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
<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.
|
||||
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
|
||||
@@ -666,23 +643,19 @@ the "copyright" line and a pointer to where the full notice is found.</p>
|
||||
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/>.
|
||||
</pre>
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
<p>Also add information on how to contact you by electronic and paper mail.</p>
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
<p>If your software can interact with users remotely through a computer
|
||||
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.</p>
|
||||
specific requirements.
|
||||
|
||||
<p>You should also get your employer (if you work as a programmer) or school,
|
||||
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
|
||||
<<a href="https://www.gnu.org/licenses/">https://www.gnu.org/licenses/</a>>.</p>
|
||||
|
||||
|
||||
</body></html>
|
||||
<https://www.gnu.org/licenses/>.
|
||||
File renamed without changes.
|
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 18 KiB |
@@ -8,12 +8,12 @@
|
||||
"theme_color": "#000000",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/shakespeare.png",
|
||||
"src": "/favicon.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "/shakespeare.png",
|
||||
"src": "/favicon.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png"
|
||||
}
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generator: Adobe Illustrator 25.2.3, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||
<svg version="1.1" id="レイヤー_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px"
|
||||
y="0px" viewBox="0 0 128 128" style="enable-background:new 0 0 128 128;" xml:space="preserve">
|
||||
<g>
|
||||
<g>
|
||||
<path style="fill:#F45125;" d="M110.28,61.32l2.63,8.84c0,0,7.24-1.6,7.62,3.2c0.38,4.8-6.77,8-6.77,8l2.26,10.63
|
||||
c0,0,7.9-6.4,8-15.61c0,0,0.66-11.29-6.11-13.92C113.67,60.85,110.28,61.32,110.28,61.32z"/>
|
||||
<path style="fill:#F45125;" d="M68.71,94.99c0,0-11.1-4.7-16.46,1.98c-0.75,0.94-1.41,1.88-2.16,2.82
|
||||
c-0.56,0.75-1.13,1.5-1.69,2.16c-0.47,0.56-1.03,1.13-1.69,1.5c-0.66,0.38-1.32,0.66-2.07,0.85c-0.94,0.19-1.88,0.19-2.82,0.09
|
||||
c-1.32-0.09-2.63-0.38-3.95-0.66c-0.47-0.09-0.85-0.19-1.22-0.28c-0.09,0-0.19-0.09-0.28-0.09s-0.19-0.09-0.28-0.09
|
||||
c-0.38,0.09,0.19,0.75,0.38,0.94c0.28,0.28,0.56,0.66,0.85,0.94c0.85,0.75,1.69,1.5,2.73,1.98c1.32,0.66,2.73,1.03,4.14,1.13
|
||||
c0.09,0,0.38,0,0.47,0.09c0.19,0.19-0.28,0.47-0.47,0.56c-0.28,0.19-0.47,0.28-0.75,0.38c-0.85,0.38-1.79,0.56-2.63,0.75
|
||||
c-0.85,0.19-1.69,0.28-2.45,0.28c-0.47,0-0.85,0.09-1.22,0.09c-0.28,0-0.56-0.09-0.85,0s0.09,0.47,0.28,0.56
|
||||
c0.38,0.19,0.75,0.47,1.13,0.66c1.13,0.56,2.26,1.03,3.39,1.32c1.5,0.38,3.1,0.56,4.61,0.38c1.32-0.19,2.63-0.56,3.86-1.03
|
||||
c6.77-3.1,6.21-9.59,12.42-10.16c4.61-0.38,11.1,2.07,11.1,2.07L68.71,94.99z"/>
|
||||
<path style="fill:#F45125;" d="M19.79,38.28c0,0-12.13,1.98-15.24,12.79C0.61,64.9,20.26,69.5,20.26,69.5l1.22-9.41
|
||||
c0,0-13.07-1.32-12.32-6.3c0.94-6.21,11.85-5.64,11.85-5.64L19.79,38.28z"/>
|
||||
<path style="fill:#F45125;" d="M20.73,70.92c0,0-1.88,0.56-4.61,2.54c-1.88,1.32-4.42,3.01-6.87,5.93
|
||||
c-1.22,1.41-2.16,3.1-2.82,4.89c-0.47,1.22-0.66,2.45-0.66,3.76c0,0.28,0,0.56,0,0.85c0,0.09,0,0.85,0.28,0.66
|
||||
c0.09-0.09,0.19-0.38,0.28-0.47c0.19-0.47,0.47-0.85,0.75-1.22c0.85-1.13,1.88-2.16,3.01-3.01c0.38-0.28,0.75-0.47,1.13-0.66
|
||||
c0.28-0.28,0.75-0.66,0.94-0.28c0.09,0.19-0.09,0.47-0.19,0.66c-0.09,0.28-0.19,0.66-0.19,0.94c-0.38,1.5-0.56,3.01-0.75,4.51
|
||||
c-0.09,0.85-0.09,1.69,0,2.45c0,0.38,0.09,0.85,0.09,1.22c0,0.19,0.09,0.38,0.09,0.56c0,0.19,0.19,0.47,0.38,0.19
|
||||
c0.09-0.09,0.09-0.19,0.19-0.38c0.19-0.28,0.28-0.66,0.47-0.94c0.47-0.85,0.94-1.69,1.5-2.63c0.66-1.13,1.41-2.16,2.16-3.1
|
||||
c0.85-1.13,1.88-2.26,2.92-3.2c1.13-1.03,2.35-2.07,3.67-2.92c0.75-0.47,1.6-0.94,2.45-1.32L20.73,70.92z"/>
|
||||
<g>
|
||||
<path style="fill:#FCC21B;" d="M116.4,79.29c-1.13-5.55-2.73-11.01-4.51-16.46c-1.5-4.61-3.1-9.31-5.83-13.36
|
||||
c-1.22-1.79-3.01-3.01-5.27-3.86c-4.33-1.69-9.97-1.98-13.73-1.98c-5.64,0-11.48,1.22-16.74,3.67
|
||||
c-1.88,5.64-7.05,19.94-14.86,26.34c0.47,2.63,1.03,5.36,1.79,8c1.32,4.61,3.01,9.22,4.61,13.83c1.5,4.42,3.29,8.84,6.58,12.23
|
||||
c0.85,0.94,1.88,1.69,2.82,2.45c2.26,1.88,4.99,3.01,7.71,3.95c2.54,0.85,5.17,1.5,7.81,2.07c4.7,1.03,11.48,2.82,16.08,0.66
|
||||
c2.54-1.13,4.61-2.92,6.3-5.08c1.79-2.26,3.2-4.8,4.42-7.43c1.88-3.95,3.86-8.37,4.14-12.89
|
||||
C117.99,87.38,117.24,83.24,116.4,79.29z"/>
|
||||
<path style="fill:#429ADF;" d="M77.64,33.57c-0.28-1.03-1.03-2.07-1.6-3.01c-6.3-11.01-20.04-16.27-32.26-15.52
|
||||
c-3.76,0.28-9.31,0.85-13.54,2.73c-2.07,0.94-3.86,2.35-4.99,4.14c-2.54,4.23-3.76,8.94-5.08,13.64
|
||||
C18.67,41,17.35,46.55,16.5,52.2c-0.75,4.89-1.41,10.25-0.09,15.14c1.03,3.86,3.29,9.22,5.74,12.32
|
||||
c2.73,3.39,6.58,7.34,10.72,8.84c0.75,0.28,1.6,0.47,2.45,0.66c1.6,0.28,3.29,0.47,4.89,0.19c0.94-0.19,1.98-0.28,2.92-0.56
|
||||
c1.88-0.47,3.67-1.13,5.46-1.79c7.52-3.01,13.64-7.43,17.68-14.58c1.69-3.1,3.1-6.4,4.42-9.69c0.09-0.19,0.19-0.38,0.19-0.56
|
||||
c1.98-5.46,3.29-11.19,4.61-16.84c0.66-2.73,1.41-5.55,1.79-8.37C77.55,35.92,77.92,34.7,77.64,33.57z"/>
|
||||
</g>
|
||||
</g>
|
||||
<path style="fill:#193D51;" d="M23.09,40.53c1.69-3.1,5.74-5.55,9.31-5.08c0.56,0.09,1.22,0.19,1.79,0.47
|
||||
c3.57,1.5,5.74,4.99,4.89,8.56c-0.19,0.75-0.66,0.85-1.22,0.38c-1.98-1.69-3.57-3.01-6.21-3.67c-2.16-0.56-4.61-0.28-6.68,0.28
|
||||
c-0.47,0.09-1.22,0.56-1.69,0.38C22.61,41.57,22.9,40.91,23.09,40.53z"/>
|
||||
<path style="fill:#193D51;" d="M62.21,64.9c-1.03,1.6-2.45,3.01-3.86,4.33c-0.38,0.28-0.66,0.66-1.03,0.94
|
||||
c-5.64,4.7-13.26,7.05-20.51,5.27c-1.98-0.47-4.14-1.5-5.74-2.73c-1.22-0.94-2.45-2.16-3.48-3.39c-1.88-2.26-3.29-4.89-4.23-7.62
|
||||
c-0.47-1.41-0.75-2.73-0.94-4.23c0-0.47-0.66-5.46,0.85-4.8c0.38,0.19,0.66,0.47,0.94,0.75c0.28,0.38,0.47,0.75,0.75,1.03
|
||||
c0.66,0.85,1.32,1.69,2.07,2.45c2.35,2.73,5.27,4.89,8.56,6.4c2.26,1.03,4.7,1.6,7.15,1.79c1.41,0.09,2.73,0.19,4.14,0.09
|
||||
c5.08-0.28,10.25-1.79,14.86-3.76c0.38-0.19,0.85-0.47,1.32-0.47C64.66,61.04,62.5,64.52,62.21,64.9z"/>
|
||||
<path style="fill:#193D51;" d="M67.58,51.16c0,0.47-0.19,1.13-0.75,1.03c-0.47-0.09-0.85-0.94-1.13-1.22
|
||||
c-1.32-1.69-3.86-3.57-6.4-4.14c-3.01-0.75-5.27,0.56-8.28,0.85c-0.85,0.09-1.32-0.28-0.94-1.03c1.6-3.48,5.83-6.21,10.25-5.46
|
||||
c0.75,0.09,1.41,0.28,2.07,0.56C66.26,43.36,67.86,47.59,67.58,51.16z"/>
|
||||
<path style="fill:#9B7515;" d="M91.84,63.86c4.23,2.73,9.69,3.48,14.58,3.2c1.41-0.09,2.26,0.09,1.88,1.69
|
||||
c-0.75,3.29-3.86,5.17-6.87,5.83c-0.75,0.19-1.5,0.19-2.26,0.19c-1.41-0.09-2.82-0.66-4.04-1.5c-2.63-1.79-4.61-4.89-5.17-8
|
||||
C89.68,63.67,90.25,62.83,91.84,63.86z"/>
|
||||
<path style="fill:#9B7515;" d="M65.22,80.79C64,79.57,64.66,79,65.98,78.25c4.51-2.35,9.03-5.93,11.38-10.63
|
||||
c0.85-1.79,1.79-1.41,2.45,0.28c1.13,3.1,1.03,6.87-0.38,9.88c-0.66,1.41-1.6,2.63-2.82,3.57c-0.66,0.47-1.32,0.75-2.07,1.03
|
||||
C71.43,83.33,67.58,83.24,65.22,80.79z"/>
|
||||
<path style="fill:#9B7515;" d="M110,96.41c-0.38,0-0.94-0.38-1.41-0.66c-0.47-0.28-0.94-0.66-1.22-0.85
|
||||
c-1.13-0.56-2.45-1.13-3.67-1.5c-3.76-1.22-7.9-1.22-11.57,0c-2.63,0.85-5.17,2.45-7.24,4.33c-2.26,2.16-3.95,4.8-6.11,7.05
|
||||
c-0.28,0.28-0.56,0.56-0.85,0.75c-0.56,0.28-1.13-0.09-1.32-0.66c-0.94-3.95,1.69-9.5,3.67-12.89c2.26-3.76,5.55-6.77,9.78-8
|
||||
c2.07-0.66,4.33-0.66,6.49-0.38c6.3,0.94,12.79,5.93,14.02,11.66C110.56,95.75,110.47,96.5,110,96.41z"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 5.8 KiB |
+20
-17
@@ -16,6 +16,7 @@ import { AISettingsProvider } from '@/components/AISettingsProvider';
|
||||
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
|
||||
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
|
||||
import { FSProvider } from '@/components/FSProvider';
|
||||
import { ConsoleProvider } from '@/contexts/ConsoleContext';
|
||||
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
|
||||
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
|
||||
|
||||
@@ -38,7 +39,7 @@ const queryClient = new QueryClient({
|
||||
});
|
||||
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "system",
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.primal.net",
|
||||
deployServer: "shakespeare.wtf",
|
||||
};
|
||||
@@ -73,22 +74,24 @@ export function App() {
|
||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
|
||||
<FSProvider fs={fs}>
|
||||
<FSCleanupHandler />
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
<ConsoleProvider>
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</ConsoleProvider>
|
||||
</FSProvider>
|
||||
</AppProvider>
|
||||
</QueryClientProvider>
|
||||
|
||||
+2
-1
@@ -11,7 +11,7 @@ import AISettings from "./pages/AISettings";
|
||||
import GitSettings from "./pages/GitSettings";
|
||||
import DataSettings from "./pages/DataSettings";
|
||||
import AboutSettings from "./pages/AboutSettings";
|
||||
|
||||
import EmailSettings from "./pages/EmailSettings";
|
||||
import GitHubOAuth from "./pages/GitHubOAuth";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
@@ -34,6 +34,7 @@ export function AppRouter() {
|
||||
<Route path="ai" element={<AISettings />} />
|
||||
<Route path="git" element={<GitSettings />} />
|
||||
<Route path="data" element={<DataSettings />} />
|
||||
<Route path="email" element={<EmailSettings />} />
|
||||
<Route path="about" element={<AboutSettings />} />
|
||||
</Route>
|
||||
<Route path="/project/:projectId" element={<ProjectView />} />
|
||||
|
||||
@@ -57,7 +57,6 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
// If providers are being updated, invalidate the provider-models query
|
||||
if ('providers' in newSettings) {
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -81,7 +80,6 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
}
|
||||
});
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
|
||||
};
|
||||
|
||||
const removeProvider = (id: string) => {
|
||||
@@ -90,7 +88,6 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
providers: prev.providers.filter(provider => provider.id !== id),
|
||||
}));
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
|
||||
};
|
||||
|
||||
const setProviders = (providers: AIProvider[]) => {
|
||||
@@ -99,7 +96,6 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
providers,
|
||||
}));
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
|
||||
};
|
||||
|
||||
const addRecentlyUsedModel = (modelId: string) => {
|
||||
|
||||
@@ -1,380 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { ArrowRight, ArrowLeft, Download, Upload, ExternalLink, Sparkles } 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 { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
|
||||
interface Act1DialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
type DialogStep = 'welcome' | 'migration' | 'credits' | 'conclusion';
|
||||
|
||||
const SHAKESPEARE_PROVIDER = {
|
||||
id: "shakespeare",
|
||||
baseURL: "https://ai.shakespeare.diy/v1",
|
||||
nostr: true,
|
||||
};
|
||||
|
||||
const MKSTACK_NSP_ADDR = '31999:4bcaa7b5606e3c14df05cd497e588f5d3fe559b4e9a425e8b418a43af1ffb015:mkstack';
|
||||
|
||||
export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
|
||||
const [step, setStep] = useState<DialogStep>('welcome');
|
||||
const [isSettingUp, setIsSettingUp] = useState(false);
|
||||
const { setProvider, updateSettings } = useAISettings();
|
||||
|
||||
// Get the selectedNSPAddr from localStorage
|
||||
const [selectedNSPAddr] = useLocalStorage<string | null>('selectedNSPAddr', null);
|
||||
|
||||
// Get user's credits
|
||||
const { data: creditsData } = useAICredits(SHAKESPEARE_PROVIDER);
|
||||
|
||||
const handleGetStarted = async () => {
|
||||
setIsSettingUp(true);
|
||||
|
||||
try {
|
||||
// Add Shakespeare provider to their config
|
||||
setProvider(SHAKESPEARE_PROVIDER);
|
||||
|
||||
// Configure recently used models based on credits or NSP
|
||||
const hasCredits = creditsData?.amount && creditsData.amount > 0;
|
||||
const hasMKStackNSP = selectedNSPAddr === MKSTACK_NSP_ADDR;
|
||||
|
||||
if (hasCredits || hasMKStackNSP) {
|
||||
// User has credits or MKStack NSP - set to shakespeare model
|
||||
updateSettings({ recentlyUsedModels: ['shakespeare/shakespeare'] });
|
||||
} else {
|
||||
// No credits - set to tybalt model (free)
|
||||
updateSettings({ recentlyUsedModels: ['shakespeare/tybalt'] });
|
||||
}
|
||||
|
||||
// Move to migration step
|
||||
setStep('migration');
|
||||
} catch (error) {
|
||||
console.error('Failed to configure Shakespeare provider:', error);
|
||||
} finally {
|
||||
setIsSettingUp(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleContinue = () => {
|
||||
setStep('credits');
|
||||
};
|
||||
|
||||
const handleCreditsNext = () => {
|
||||
setStep('conclusion');
|
||||
};
|
||||
|
||||
const handleFinish = () => {
|
||||
// Mark that the user is a previous Act 1 user
|
||||
localStorage.setItem('act1', 'true');
|
||||
// Remove the selectedNSPAddr from localStorage
|
||||
localStorage.removeItem('selectedNSPAddr');
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const handleVisitAct1 = () => {
|
||||
window.open('https://act1.shakespeare.diy', '_blank');
|
||||
};
|
||||
|
||||
// Reset state when dialog opens/closes
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setStep('welcome');
|
||||
setIsSettingUp(false);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-hidden">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
{step === 'migration' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setStep('welcome')}
|
||||
className="mr-2 p-1 h-auto"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{step === 'credits' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setStep('migration')}
|
||||
className="mr-2 p-1 h-auto"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{step === 'conclusion' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setStep('credits')}
|
||||
className="mr-2 p-1 h-auto"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<span className="text-xl">
|
||||
{step === 'welcome' && 'Welcome to Shakespeare: Act 2! 🎭'}
|
||||
{step === 'migration' && 'Migrating Your Projects'}
|
||||
{step === 'credits' && 'Your Credits'}
|
||||
{step === 'conclusion' && "You're All Set!"}
|
||||
</span>
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="overflow-y-auto max-h-[calc(90vh-120px)] pr-2">
|
||||
<div className="space-y-6 py-4">
|
||||
{step === 'welcome' && (
|
||||
<div className="text-center space-y-6">
|
||||
<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 Act 2!
|
||||
</h2>
|
||||
<p className="text-lg text-muted-foreground max-w-lg mx-auto">
|
||||
We're excited to see you again! Shakespeare has been completely rebuilt
|
||||
with new features, improved performance, and a better development experience.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="max-w-lg mx-auto text-left">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<span className="text-2xl">🔄</span>
|
||||
What's Changed
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<Badge variant="secondary" className="mt-0.5">New</Badge>
|
||||
<div>
|
||||
<p className="font-medium">Use any AI Provider</p>
|
||||
<p className="text-sm text-muted-foreground">Your browser connects to AI providers directly</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<Badge variant="secondary" className="mt-0.5">New</Badge>
|
||||
<div>
|
||||
<p className="font-medium">Git Integration</p>
|
||||
<p className="text-sm text-muted-foreground">Push to GitHub, Nostr relays, and more</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<Badge variant="secondary" className="mt-0.5">New</Badge>
|
||||
<div>
|
||||
<p className="font-medium">Your Files</p>
|
||||
<p className="text-sm text-muted-foreground">Files are stored on your device directly in your browser</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="bg-amber-50 dark:bg-amber-950/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4 max-w-lg mx-auto">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="text-amber-600 dark:text-amber-400 text-lg">⚠️</span>
|
||||
<div className="text-left">
|
||||
<p className="font-medium text-amber-800 dark:text-amber-200">Act 2 is in Development</p>
|
||||
<p className="text-sm text-amber-700 dark:text-amber-300">
|
||||
While we're working hard to make Act 2 stable, you may encounter bugs.
|
||||
Your Act 1 projects remain safe and accessible.
|
||||
</p>
|
||||
</div>
|
||||
</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" />
|
||||
Configure Act 2
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'migration' && (
|
||||
<div className="space-y-6">
|
||||
<div className="text-center space-y-3">
|
||||
<h2 className="text-xl font-bold">Your Act 1 Projects & Credits</h2>
|
||||
<p className="text-muted-foreground max-w-lg mx-auto">
|
||||
All your Act 1 projects and credits are safe and still accessible.
|
||||
Here's how to work with them in Act 2.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="text-center">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleVisitAct1}
|
||||
className="gap-2"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
Visit Act 1
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Download className="h-5 w-5 text-green-500" />
|
||||
Export from Act 1
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
In Act 1, you can export your projects as ZIP files using the project menu.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Upload className="h-5 w-5 text-purple-500" />
|
||||
Import to Act 2
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
In Act 2, use the "Import Project" option in the sidebar to upload your exported ZIP files.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end pt-4">
|
||||
<Button
|
||||
onClick={handleContinue}
|
||||
className="gap-2"
|
||||
>
|
||||
Continue
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'credits' && (
|
||||
<div className="text-center space-y-6">
|
||||
<div className="text-6xl mb-4">💳</div>
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-2xl font-bold">Your Credits</h2>
|
||||
<p className="text-lg text-muted-foreground max-w-md mx-auto">
|
||||
Your Act 1 credits are still available through the Shakespeare AI provider.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="max-w-md mx-auto">
|
||||
<CardContent className="pt-6">
|
||||
{creditsData?.amount && creditsData.amount > 0 ? (
|
||||
<div className="text-center space-y-4">
|
||||
<div className="space-y-2">
|
||||
<div className="text-3xl font-bold text-green-600 dark:text-green-400">
|
||||
${creditsData.amount.toFixed(2)}
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Available credits
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-green-50 dark:bg-green-950/20 border border-green-200 dark:border-green-800 rounded-lg p-3">
|
||||
<p className="text-sm text-green-800 dark:text-green-200">
|
||||
✅ You're all set! We've configured the premium Shakespeare model for you.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center space-y-4">
|
||||
<div className="space-y-2">
|
||||
<div className="text-2xl">🆓</div>
|
||||
<p className="font-medium">Free Access</p>
|
||||
</div>
|
||||
<div className="bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800 rounded-lg p-3">
|
||||
<p className="text-sm text-blue-800 dark:text-blue-200">
|
||||
You can continue using Shakespeare for free with the Tybalt model.
|
||||
It's perfect for learning and building amazing projects!
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex justify-end pt-4">
|
||||
<Button
|
||||
onClick={handleCreditsNext}
|
||||
className="gap-2"
|
||||
>
|
||||
Continue
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'conclusion' && (
|
||||
<div className="text-center space-y-6">
|
||||
<div className="text-5xl mb-4">🎉</div>
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-2xl font-bold">Welcome to the Future!</h2>
|
||||
<p className="text-lg text-muted-foreground max-w-md mx-auto">
|
||||
You're all set up with Act 2! Your AI assistant is configured
|
||||
and ready to help you build 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 decentralized social media app with custom feeds and real-time messaging..."
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button onClick={handleFinish} size="lg" className="gap-2">
|
||||
<Sparkles className="h-4 w-4" />
|
||||
Start Building in Act 2
|
||||
</Button>
|
||||
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Remember: You can always access Act 1 at{' '}
|
||||
<button
|
||||
onClick={handleVisitAct1}
|
||||
className="text-primary hover:underline"
|
||||
>
|
||||
act1.shakespeare.diy
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -18,6 +18,7 @@ interface AppLayoutProps {
|
||||
export function AppLayout({
|
||||
children,
|
||||
selectedProject = null,
|
||||
title = "Shakespeare",
|
||||
showSidebar = true,
|
||||
headerContent
|
||||
}: AppLayoutProps) {
|
||||
@@ -84,6 +85,9 @@ export function AppLayout({
|
||||
<Menu className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<h1 className="text-lg font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
{title}
|
||||
</h1>
|
||||
</div>
|
||||
{headerContent}
|
||||
</header>
|
||||
|
||||
@@ -399,7 +399,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent onOpenAutoFocus={(e) => e.preventDefault()} 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">
|
||||
<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 ? (
|
||||
@@ -509,13 +509,17 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
</div>
|
||||
<div className="flex-1 min-h-0 overflow-y-auto">
|
||||
{isLoadingPayments ? (
|
||||
<div 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 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">
|
||||
|
||||
@@ -1,204 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Mail, CheckCircle } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
export function EmailSubscription() {
|
||||
const { t } = useTranslation();
|
||||
const { user } = useCurrentUser();
|
||||
const { toast } = useToast();
|
||||
|
||||
const [email, setEmail] = useState('');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [isSubmitted, setIsSubmitted] = useState(false);
|
||||
|
||||
const url = new URL('https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&id=f7271442a0&f_id=00ffa3e4f0');
|
||||
const honeypot = `b_${url.searchParams.get('u')}_${url.searchParams.get('id')}`;
|
||||
const tag = '8982396';
|
||||
|
||||
// Check localStorage on component mount
|
||||
useEffect(() => {
|
||||
const hasSubscribed = localStorage.getItem('shakespeare-email-subscribed');
|
||||
if (hasSubscribed === 'true') {
|
||||
setIsSubmitted(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!email.trim()) {
|
||||
toast({
|
||||
title: "Email required",
|
||||
description: "Please enter your email address",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Basic email validation
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
toast({
|
||||
title: "Invalid email",
|
||||
description: "Please enter a valid email address",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
// Submit to Mailchimp
|
||||
const form = document.createElement('form');
|
||||
form.method = 'POST';
|
||||
form.action = url.href;
|
||||
form.target = '_blank'; // Open in new tab
|
||||
form.style.display = 'none';
|
||||
|
||||
// Add email field
|
||||
const emailInput = document.createElement('input');
|
||||
emailInput.type = 'email';
|
||||
emailInput.name = 'EMAIL';
|
||||
emailInput.value = email.trim();
|
||||
form.appendChild(emailInput);
|
||||
|
||||
// Add tag field with the new Shakespeare tag ID
|
||||
const tagInput = document.createElement('input');
|
||||
tagInput.type = 'hidden';
|
||||
tagInput.name = 'tags';
|
||||
tagInput.value = tag;
|
||||
form.appendChild(tagInput);
|
||||
|
||||
// Add npub if available
|
||||
if (user?.pubkey) {
|
||||
const npubInput = document.createElement('input');
|
||||
npubInput.type = 'text';
|
||||
npubInput.name = 'NPUB';
|
||||
npubInput.value = nip19.npubEncode(user.pubkey);
|
||||
npubInput.style.display = 'none';
|
||||
form.appendChild(npubInput);
|
||||
}
|
||||
|
||||
// Add honeypot field
|
||||
const honeypotInput = document.createElement('input');
|
||||
honeypotInput.type = 'text';
|
||||
honeypotInput.name = honeypot;
|
||||
honeypotInput.tabIndex = -1;
|
||||
honeypotInput.style.position = 'absolute';
|
||||
honeypotInput.style.left = '-5000px';
|
||||
form.appendChild(honeypotInput);
|
||||
|
||||
// Add form to document and submit
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
|
||||
// Clean up after a short delay
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(form);
|
||||
}, 1000);
|
||||
|
||||
// Save subscription status to localStorage
|
||||
localStorage.setItem('shakespeare-email-subscribed', 'true');
|
||||
|
||||
setIsSubmitted(true);
|
||||
toast({
|
||||
title: "Successfully subscribed!",
|
||||
description: "You'll receive Shakespeare updates and resources occasionally.",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Email signup error:', error);
|
||||
toast({
|
||||
title: "Subscription failed",
|
||||
description: "There was an error subscribing you to updates. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isSubmitted) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="text-center space-y-4">
|
||||
<CheckCircle className="h-12 w-12 mx-auto text-green-500" />
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-lg font-semibold">
|
||||
Thanks for subscribing!
|
||||
</h3>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
You can opt out at any time using the unsubscribe link in our emails.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => {
|
||||
localStorage.removeItem('shakespeare-email-subscribed');
|
||||
setIsSubmitted(false);
|
||||
setEmail('');
|
||||
}}
|
||||
variant="outline"
|
||||
className="w-full text-xs"
|
||||
>
|
||||
Subscribe with different email
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Mail className="h-5 w-5 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{t('emailUpdatesDescription')}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">
|
||||
Email Address
|
||||
</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="[email protected]"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
disabled={isSubmitting}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{isSubmitting ? 'Subscribing...' : 'Subscribe to Updates'}
|
||||
</Button>
|
||||
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
You can opt out at any time using the unsubscribe link in our emails.
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
@@ -47,7 +47,7 @@ import { cn } from '@/lib/utils';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev"];
|
||||
const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev", "gitnostr.com"];
|
||||
|
||||
interface GitDialogProps {
|
||||
projectId: string;
|
||||
@@ -62,7 +62,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
const [isPushingToNostr, setIsPushingToNostr] = useState(false);
|
||||
const [originUrl, setOriginUrl] = useState('');
|
||||
const [isSavingOrigin, setIsSavingOrigin] = useState(false);
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
|
||||
@@ -335,7 +334,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
title: "Push to Nostr failed",
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
duration: Infinity,
|
||||
});
|
||||
} finally {
|
||||
setIsPushingToNostr(false);
|
||||
@@ -397,7 +395,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
title: "Push failed",
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
duration: Infinity,
|
||||
});
|
||||
} finally {
|
||||
setIsPushing(false);
|
||||
@@ -428,12 +425,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
try {
|
||||
const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin')
|
||||
|
||||
// Get the current HEAD commit before pulling
|
||||
const beforeCommit = await git.resolveRef({
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
|
||||
await git.pull({
|
||||
dir: projectPath,
|
||||
ref: gitStatus.currentBranch,
|
||||
@@ -445,38 +436,20 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
onAuth: (url) => findCredentialsForRepo(url, settings.credentials),
|
||||
});
|
||||
|
||||
// Get the current HEAD commit after pulling
|
||||
const afterCommit = await git.resolveRef({
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
|
||||
// Check if the repository actually changed
|
||||
const repoChanged = beforeCommit !== afterCommit;
|
||||
|
||||
toast({
|
||||
title: "Pull successful",
|
||||
description: repoChanged
|
||||
? `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}`
|
||||
: `Already up to date with ${remote.name}/${gitStatus.currentBranch}`,
|
||||
description: `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}`,
|
||||
});
|
||||
|
||||
// Refresh git status after pull
|
||||
await refetchGitStatus();
|
||||
|
||||
// Only trigger build if the repository actually changed
|
||||
if (repoChanged) {
|
||||
const newSearchParams = new URLSearchParams(searchParams);
|
||||
newSearchParams.set('build', '');
|
||||
setSearchParams(newSearchParams);
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
toast({
|
||||
title: "Pull failed",
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
duration: Infinity,
|
||||
});
|
||||
} finally {
|
||||
setIsPulling(false);
|
||||
|
||||
@@ -168,9 +168,7 @@ export function ModelSelector({
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-96 p-0" align="end">
|
||||
<Command>
|
||||
{(isConfigured && models.length >= 5) && (
|
||||
<CommandInput placeholder={t('searchModels')} className="h-9" />
|
||||
)}
|
||||
{isConfigured && <CommandInput placeholder={t('searchModels')} className="h-9" />}
|
||||
<CommandList className="max-h-[300px]">
|
||||
<CommandEmpty>
|
||||
<div className="py-6 text-center text-sm text-muted-foreground">
|
||||
|
||||
@@ -18,6 +18,7 @@ const GIT_KINDS = [
|
||||
const GIT_RELAYS = [
|
||||
'wss://git.shakespeare.diy/',
|
||||
'wss://relay.ngit.dev/',
|
||||
'wss://gitnostr.com/',
|
||||
];
|
||||
|
||||
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||
|
||||
@@ -42,7 +42,7 @@ describe('OnboardingDialog', () => {
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Welcome to Shakespeare!')).toBeInTheDocument(); // Only in dialog title now
|
||||
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();
|
||||
});
|
||||
|
||||
@@ -8,13 +8,12 @@ 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';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
|
||||
interface OnboardingDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
@@ -120,8 +119,8 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] sm:max-h-[80vh] flex flex-col">
|
||||
<DialogHeader className="flex-shrink-0">
|
||||
<DialogContent className="max-w-2xl max-h-[80vh] overflow-hidden">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
{step === 'model-selection' && (
|
||||
<Button
|
||||
@@ -133,28 +132,18 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{step === 'conclusion' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setStep('model-selection')}
|
||||
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-y-auto min-h-0">
|
||||
<div className="flex-1 overflow-hidden">
|
||||
{step === 'welcome' && (
|
||||
<div className="text-center space-y-6 py-4">
|
||||
<div className="mb-4">
|
||||
<ShakespeareLogo className="w-16 h-16 mx-auto" />
|
||||
</div>
|
||||
<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!
|
||||
@@ -202,8 +191,15 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
)}
|
||||
|
||||
{step === 'model-selection' && (
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="flex-1 overflow-y-auto min-h-0 my-4">
|
||||
<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 ? (
|
||||
<>
|
||||
@@ -236,7 +232,6 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
shakespeareModels.map((model) => {
|
||||
const isSelected = selectedModel === model.fullId;
|
||||
const isFree = model.pricing?.prompt.equals(0) && model.pricing?.completion.equals(0);
|
||||
const isPremium = !isFree;
|
||||
|
||||
return (
|
||||
<Card
|
||||
@@ -249,12 +244,12 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex-1">
|
||||
<CardTitle className={`text-xl font-semibold ${isPremium ? 'bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent' : ''}`}>
|
||||
{ model.name || model.description || model.id}
|
||||
<CardTitle className="text-base font-semibold">
|
||||
{model.description || model.name || model.id}
|
||||
</CardTitle>
|
||||
{model.description && (
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{model.description || model.id}
|
||||
{model.name || model.id}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -264,11 +259,6 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
Free
|
||||
</Badge>
|
||||
)}
|
||||
{isPremium && (
|
||||
<Badge className="text-xs bg-primary text-white border-0">
|
||||
Premium
|
||||
</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" />
|
||||
@@ -278,12 +268,12 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
<div className="flex items-end justify-end gap-4 text-xs text-muted-foreground">
|
||||
<div className="flex items-center gap-4 text-xs text-muted-foreground">
|
||||
{model.pricing && (
|
||||
<div className="text-right">
|
||||
<div>Input: {formatPrice(model.pricing.prompt)}</div>
|
||||
<div>Output: {formatPrice(model.pricing.completion)}</div>
|
||||
</div>
|
||||
<>
|
||||
<span>Input: {formatPrice(model.pricing.prompt)}</span>
|
||||
<span>Output: {formatPrice(model.pricing.completion)}</span>
|
||||
</>
|
||||
)}
|
||||
{model.contextLength && (
|
||||
<span>Context: {model.contextLength.toLocaleString()} tokens</span>
|
||||
@@ -295,9 +285,9 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-4 border-t flex-shrink-0">
|
||||
<div className="flex justify-end gap-2 pt-4 border-t">
|
||||
<Button
|
||||
onClick={handleContinue}
|
||||
disabled={!selectedModel}
|
||||
@@ -320,6 +310,11 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
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
|
||||
|
||||
@@ -208,7 +208,7 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md" onOpenAutoFocus={(e) => e.preventDefault()}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Folder className="h-5 w-5" />
|
||||
|
||||
@@ -1,685 +0,0 @@
|
||||
import React, { useState, useRef, useCallback, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Upload, FileArchive, AlertCircle, FileText, Trash2, FolderOpen, CheckSquare, Square, AlertTriangle } from 'lucide-react';
|
||||
import { useProjects } from '@/hooks/useProjects';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import JSZip from 'jszip';
|
||||
|
||||
interface ProjectInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
path: string;
|
||||
files: string[];
|
||||
isConflict: boolean;
|
||||
selected: boolean;
|
||||
}
|
||||
|
||||
interface ProjectImportDialogProps {
|
||||
mode?: 'single' | 'bulk';
|
||||
onImport: (data: { file: File; projectId?: string } | { projects: { id: string; files: { [path: string]: Uint8Array } }[] }, overwrite: boolean) => Promise<void>;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function ProjectImportDialog({
|
||||
mode = 'single',
|
||||
onImport,
|
||||
disabled = false,
|
||||
className,
|
||||
open,
|
||||
onOpenChange
|
||||
}: ProjectImportDialogProps) {
|
||||
// Use controlled state if props are provided, otherwise use internal state
|
||||
const [internalIsOpen, setInternalIsOpen] = useState(false);
|
||||
const isOpen = open !== undefined ? open : internalIsOpen;
|
||||
const setIsOpen = onOpenChange || setInternalIsOpen;
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||
const [generatedId, setGeneratedId] = useState('');
|
||||
const [discoveredProjects, setDiscoveredProjects] = useState<ProjectInfo[]>([]);
|
||||
const [isAnalyzing, setIsAnalyzing] = useState(false);
|
||||
const [isImporting, setIsImporting] = useState(false);
|
||||
const [importProgress, setImportProgress] = useState(0);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
const [showOverwriteDialog, setShowOverwriteDialog] = useState(false);
|
||||
const [zipData, setZipData] = useState<JSZip | null>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const { data: existingProjects = [] } = useProjects();
|
||||
const projectsManager = useProjectsManager();
|
||||
|
||||
// Analyze ZIP for bulk import
|
||||
const analyzeZipForProjects = useCallback(async (zip: JSZip): Promise<ProjectInfo[]> => {
|
||||
const projects: ProjectInfo[] = [];
|
||||
const projectPaths = new Set<string>();
|
||||
|
||||
// Find all potential project directories
|
||||
for (const [path] of Object.entries(zip.files)) {
|
||||
const pathParts = path.split('/').filter(part => part !== '');
|
||||
|
||||
// Skip files in root directory - we're looking for project directories
|
||||
if (pathParts.length < 2) continue;
|
||||
|
||||
// Check if this looks like a project indicator file
|
||||
if (isProjectIndicator(path)) {
|
||||
let projectPath: string;
|
||||
|
||||
// If structure is projects/project-name/file, extract project-name
|
||||
if (pathParts[0] === 'projects' && pathParts.length >= 3) {
|
||||
projectPath = `projects/${pathParts[1]}`;
|
||||
} else {
|
||||
// Otherwise, assume first directory is the project
|
||||
projectPath = pathParts[0];
|
||||
}
|
||||
|
||||
projectPaths.add(projectPath);
|
||||
}
|
||||
}
|
||||
|
||||
// For each discovered project path, gather information
|
||||
for (const projectPath of projectPaths) {
|
||||
const files: string[] = [];
|
||||
|
||||
// Collect all files in this project directory
|
||||
for (const [path, zipEntry] of Object.entries(zip.files)) {
|
||||
if (path.startsWith(projectPath + '/') && !zipEntry.dir) {
|
||||
const relativePath = path.substring(projectPath.length + 1);
|
||||
files.push(relativePath);
|
||||
}
|
||||
}
|
||||
|
||||
// Generate project ID and name from directory path
|
||||
let id: string;
|
||||
let name: string;
|
||||
|
||||
if (projectPath.startsWith('projects/')) {
|
||||
const projectName = projectPath.substring('projects/'.length);
|
||||
id = projectName
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
name = projectName;
|
||||
} else {
|
||||
id = projectPath
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
name = projectPath;
|
||||
}
|
||||
|
||||
// Skip if no files found (empty directory)
|
||||
if (files.length === 0) continue;
|
||||
|
||||
// Check if this project conflicts with existing projects
|
||||
const isConflict = existingProjects.some(existing => existing.id === id);
|
||||
|
||||
projects.push({
|
||||
id,
|
||||
name,
|
||||
path: projectPath,
|
||||
files,
|
||||
isConflict,
|
||||
selected: !isConflict, // Auto-select non-conflicting projects
|
||||
});
|
||||
}
|
||||
|
||||
return projects;
|
||||
}, [existingProjects]);
|
||||
|
||||
// Handle file selection
|
||||
const handleFileSelect = useCallback(async (file: File) => {
|
||||
// Only accept zip files
|
||||
if (!file.name.toLowerCase().endsWith('.zip')) {
|
||||
setError('Please select a ZIP file');
|
||||
return;
|
||||
}
|
||||
|
||||
setSelectedFile(file);
|
||||
setError(null);
|
||||
setGeneratedId('');
|
||||
|
||||
// Auto-generate ID from file name for single mode
|
||||
if (mode === 'single') {
|
||||
const baseName = file.name.replace(/\.zip$/i, '');
|
||||
const id = baseName
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
setGeneratedId(id);
|
||||
}
|
||||
|
||||
// For bulk mode, analyze the ZIP to discover projects
|
||||
if (mode === 'bulk') {
|
||||
setIsAnalyzing(true);
|
||||
setDiscoveredProjects([]);
|
||||
|
||||
try {
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
const zip = await JSZip.loadAsync(arrayBuffer);
|
||||
setZipData(zip);
|
||||
|
||||
const projects = await analyzeZipForProjects(zip);
|
||||
setDiscoveredProjects(projects);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to analyze ZIP file');
|
||||
} finally {
|
||||
setIsAnalyzing(false);
|
||||
}
|
||||
}
|
||||
}, [mode, analyzeZipForProjects]);
|
||||
|
||||
|
||||
const isProjectIndicator = (path: string): boolean => {
|
||||
const indicators = [
|
||||
'package.json',
|
||||
'index.html',
|
||||
'src/',
|
||||
'public/',
|
||||
'tsconfig.json',
|
||||
'vite.config.',
|
||||
'webpack.config.',
|
||||
'README.md',
|
||||
'.git/',
|
||||
];
|
||||
|
||||
return indicators.some(indicator => path.includes('/' + indicator));
|
||||
};
|
||||
|
||||
// Check for existing project when generated ID changes (single mode)
|
||||
useEffect(() => {
|
||||
if (mode === 'single' && generatedId && existingProjects.length > 0) {
|
||||
const existing = existingProjects.find(project => project.id === generatedId);
|
||||
if (existing) {
|
||||
setError(`A project with ID "${generatedId}" already exists. You can choose to overwrite it.`);
|
||||
} else {
|
||||
setError(null);
|
||||
}
|
||||
}
|
||||
}, [generatedId, existingProjects, mode]);
|
||||
|
||||
// Drag and drop handlers
|
||||
const handleDragOver = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(true);
|
||||
}, []);
|
||||
|
||||
const handleDragLeave = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(false);
|
||||
}, []);
|
||||
|
||||
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(false);
|
||||
|
||||
const files = Array.from(e.dataTransfer.files);
|
||||
if (files.length > 0) {
|
||||
handleFileSelect(files[0]);
|
||||
}
|
||||
}, [handleFileSelect]);
|
||||
|
||||
const handleClickUpload = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
const handleFileRemove = () => {
|
||||
setSelectedFile(null);
|
||||
setGeneratedId('');
|
||||
setDiscoveredProjects([]);
|
||||
setZipData(null);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
// Bulk import project selection handlers
|
||||
const handleProjectToggle = (projectId: string, checked: boolean) => {
|
||||
setDiscoveredProjects(prev =>
|
||||
prev.map(project =>
|
||||
project.id === projectId ? { ...project, selected: checked } : project
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
const handleSelectAll = () => {
|
||||
setDiscoveredProjects(prev =>
|
||||
prev.map(project => ({ ...project, selected: true }))
|
||||
);
|
||||
};
|
||||
|
||||
const handleDeselectAll = () => {
|
||||
setDiscoveredProjects(prev =>
|
||||
prev.map(project => ({ ...project, selected: false }))
|
||||
);
|
||||
};
|
||||
|
||||
const selectedProjects = discoveredProjects.filter(project => project.selected);
|
||||
const conflictingProjects = selectedProjects.filter(project => project.isConflict);
|
||||
|
||||
const handleImport = async (overwrite = false) => {
|
||||
if (!selectedFile) return;
|
||||
|
||||
setIsImporting(true);
|
||||
setImportProgress(0);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
if (mode === 'single') {
|
||||
// Single project import
|
||||
const progressInterval = setInterval(() => {
|
||||
setImportProgress(prev => Math.min(prev + 10, 90));
|
||||
}, 200);
|
||||
|
||||
await onImport({ file: selectedFile, projectId: generatedId }, overwrite);
|
||||
|
||||
clearInterval(progressInterval);
|
||||
setImportProgress(100);
|
||||
} else {
|
||||
// Bulk project import
|
||||
const projectsToImport = await Promise.all(
|
||||
selectedProjects.map(async (project) => {
|
||||
const files = await projectsManager.extractFilesFromZip(zipData!, project.path);
|
||||
return {
|
||||
id: project.id,
|
||||
files,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
const progressInterval = setInterval(() => {
|
||||
setImportProgress(prev => Math.min(prev + 5, 90));
|
||||
}, 100);
|
||||
|
||||
await onImport({ projects: projectsToImport }, overwrite);
|
||||
|
||||
clearInterval(progressInterval);
|
||||
setImportProgress(100);
|
||||
}
|
||||
|
||||
// Close dialog and reset state immediately
|
||||
setIsOpen(false);
|
||||
handleFileRemove();
|
||||
setImportProgress(0);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to import projects');
|
||||
setImportProgress(0);
|
||||
} finally {
|
||||
setIsImporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImportWithOverwriteCheck = async () => {
|
||||
if (mode === 'single') {
|
||||
// For single mode, check if project exists
|
||||
const existingProject = existingProjects.find(project => project.id === generatedId);
|
||||
if (existingProject) {
|
||||
setShowOverwriteDialog(true);
|
||||
} else {
|
||||
await handleImport(false);
|
||||
}
|
||||
} else {
|
||||
// For bulk mode, check for conflicts
|
||||
if (conflictingProjects.length > 0) {
|
||||
setShowOverwriteDialog(true);
|
||||
} else {
|
||||
await handleImport(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const confirmOverwrite = async () => {
|
||||
setShowOverwriteDialog(false);
|
||||
await handleImport(true);
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
if (!isImporting && !isAnalyzing) {
|
||||
setIsOpen(false);
|
||||
handleFileRemove();
|
||||
setImportProgress(0);
|
||||
}
|
||||
};
|
||||
|
||||
// Only render DialogTrigger if this component is being used in uncontrolled mode
|
||||
const isControlled = open !== undefined && onOpenChange !== undefined;
|
||||
|
||||
const canImport = mode === 'single'
|
||||
? selectedFile && generatedId
|
||||
: selectedProjects.length > 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
||||
{!isControlled && (
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
className={cn("gap-2", className)}
|
||||
>
|
||||
<FileArchive className="h-4 w-4" />
|
||||
{mode === 'single' ? 'Import ZIP' : 'Import Projects'}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
)}
|
||||
|
||||
<DialogContent className={cn(
|
||||
"h-auto max-h-[90vh] flex flex-col",
|
||||
mode === 'single' ? "sm:max-w-md" : "sm:max-w-xl"
|
||||
)}>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Upload className="h-5 w-5" />
|
||||
{mode === 'single' ? 'Import Project from ZIP' : 'Import Multiple Projects'}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{mode === 'single'
|
||||
? 'Upload a ZIP file containing your project source code to import it into Shakespeare.'
|
||||
: 'Upload a ZIP file containing multiple projects to import them into Shakespeare.'
|
||||
}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 flex flex-col overflow-hidden min-h-0 space-y-4">
|
||||
{!isImporting && !isAnalyzing && (
|
||||
<>
|
||||
{/* Drag and Drop Area */}
|
||||
<div
|
||||
className={cn(
|
||||
"relative border-2 border-dashed rounded-lg p-4 text-center transition-colors cursor-pointer",
|
||||
isDragOver ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50 hover:bg-primary/5",
|
||||
selectedFile && "border-green-500/50 bg-green-500/5"
|
||||
)}
|
||||
onClick={handleClickUpload}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
onChange={(e) => {
|
||||
const files = e.target.files;
|
||||
if (files && files.length > 0) {
|
||||
handleFileSelect(files[0]);
|
||||
}
|
||||
}}
|
||||
accept=".zip"
|
||||
className="hidden"
|
||||
disabled={isImporting || isAnalyzing}
|
||||
/>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-center">
|
||||
{selectedFile ? (
|
||||
<FileText className="h-6 w-6 text-green-600" />
|
||||
) : (
|
||||
<Upload className="h-6 w-6 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{selectedFile ? (
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium text-green-600">
|
||||
{selectedFile.name}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{(selectedFile.size / 1024 / 1024).toFixed(2)} MB
|
||||
</p>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleFileRemove();
|
||||
}}
|
||||
className="text-xs text-destructive hover:underline"
|
||||
>
|
||||
Remove file
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium">
|
||||
Drop your ZIP file here or click to browse
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{mode === 'single'
|
||||
? 'Supports ZIP files up to 50MB'
|
||||
: 'Supports ZIP files containing exported Shakespeare projects'
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error Display */}
|
||||
{error && (
|
||||
<div className="flex items-center gap-2 text-sm text-amber-600 mb-4">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Project List (Bulk Mode Only) */}
|
||||
{mode === 'bulk' && discoveredProjects.length > 0 && (
|
||||
<div className="space-y-3 flex-1 flex flex-col min-h-0">
|
||||
<div className="flex items-center justify-between flex-shrink-0">
|
||||
<h3 className="text-sm font-medium">
|
||||
Found {discoveredProjects.length} project{discoveredProjects.length !== 1 ? 's' : ''}
|
||||
</h3>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleSelectAll}
|
||||
className="h-8 text-xs"
|
||||
>
|
||||
<CheckSquare className="h-3 w-3 mr-1" />
|
||||
Select All
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleDeselectAll}
|
||||
className="h-8 text-xs"
|
||||
>
|
||||
<Square className="h-3 w-3 mr-1" />
|
||||
Deselect All
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border rounded-lg overflow-hidden">
|
||||
<ScrollArea className="h-64">
|
||||
<div className="p-2 space-y-1">
|
||||
{discoveredProjects.map((project) => (
|
||||
<div
|
||||
key={project.id}
|
||||
className={cn(
|
||||
"flex items-start space-x-3 p-2 rounded-lg border transition-colors",
|
||||
project.selected ? "bg-primary/5 border-primary/20" : "bg-background",
|
||||
project.isConflict && "border-amber-200 bg-amber-50/50 dark:border-amber-800 dark:bg-amber-950/20"
|
||||
)}
|
||||
>
|
||||
<Checkbox
|
||||
id={`project-${project.id}`}
|
||||
checked={project.selected}
|
||||
onCheckedChange={(checked) => handleProjectToggle(project.id, checked as boolean)}
|
||||
className="mt-1"
|
||||
/>
|
||||
<div className="flex-1 min-w-0 space-y-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<FolderOpen className="h-4 w-4 text-primary flex-shrink-0" />
|
||||
<span className="font-medium text-sm truncate">{project.name}</span>
|
||||
{project.isConflict && (
|
||||
<div className="hidden sm:flex items-center gap-1 text-amber-600 flex-shrink-0">
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
<span className="text-xs">Conflict</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{project.isConflict && (
|
||||
<div className="sm:hidden flex items-center gap-1 text-amber-600">
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
<span className="text-xs font-medium">Conflict - Will overwrite existing project</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{project.files.length} file{project.files.length !== 1 ? 's' : ''}
|
||||
{project.isConflict && <span className="hidden sm:inline"> • Will overwrite existing project</span>}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Import Button */}
|
||||
{selectedFile && (mode === 'single' || discoveredProjects.length > 0) && (
|
||||
<div className="flex justify-end gap-2 pt-3 border-t flex-shrink-0">
|
||||
<Button variant="outline" onClick={handleClose} disabled={isImporting}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleImportWithOverwriteCheck}
|
||||
disabled={!canImport || isImporting}
|
||||
className={mode === 'single' && error ? "bg-amber-600 hover:bg-amber-700" : conflictingProjects.length > 0 ? "bg-amber-600 hover:bg-amber-700" : ""}
|
||||
>
|
||||
{mode === 'single' ? (
|
||||
error ? (
|
||||
<>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Overwrite Project
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Upload className="mr-2 h-4 w-4" />
|
||||
Import Project
|
||||
</>
|
||||
)
|
||||
) : (
|
||||
<>
|
||||
{conflictingProjects.length > 0 ? <Trash2 className="mr-2 h-4 w-4" /> : <Upload className="mr-2 h-4 w-4" />}
|
||||
{conflictingProjects.length > 0 ? 'Import & Overwrite' : 'Import Projects'} ({selectedProjects.length})
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Analysis Progress (Bulk Mode Only) */}
|
||||
{mode === 'bulk' && isAnalyzing && (
|
||||
<div className="space-y-2 py-6">
|
||||
<div className="flex items-center gap-2 text-sm justify-center">
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div>
|
||||
Analyzing ZIP file...
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
Discovering projects and checking for conflicts...
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Import Progress */}
|
||||
{isImporting && (
|
||||
<div className="space-y-3 py-6">
|
||||
<div className="flex items-center gap-2 text-sm justify-center">
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div >
|
||||
{mode === 'single' ? 'Importing project...' : `Importing ${selectedProjects.length} project${selectedProjects.length !== 1 ? 's' : ''}...`}
|
||||
</div>
|
||||
<Progress value={importProgress} className="w-full" />
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
Extracting files and setting up projects...
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Success State */}
|
||||
{!isImporting && !isAnalyzing && importProgress === 100 && (
|
||||
<div className="flex items-center gap-2 text-sm text-green-600 justify-center py-3">
|
||||
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path>
|
||||
</svg>
|
||||
{mode === 'single' ? 'Project imported successfully!' : 'Projects imported successfully!'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Overwrite Confirmation Dialog */}
|
||||
<AlertDialog open={showOverwriteDialog} onOpenChange={setShowOverwriteDialog}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="flex items-center gap-2">
|
||||
<AlertCircle className="h-5 w-5 text-amber-600" />
|
||||
{mode === 'single' ? 'Overwrite Existing Project' : 'Overwrite Existing Projects'}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription className="space-y-3">
|
||||
{mode === 'single' ? (
|
||||
<>
|
||||
<p>
|
||||
A project with ID "<strong>{generatedId}</strong>" already exists.
|
||||
Overwriting it will:
|
||||
</p>
|
||||
<ul className="list-disc list-inside text-sm space-y-1 ml-2">
|
||||
<li><strong>Delete all existing files</strong> in project</li>
|
||||
<li><strong>Replace them with files</strong> from the ZIP archive</li>
|
||||
<li><strong>Preserve Git history</strong> if it exists</li>
|
||||
<li><strong>Keep AI chat history</strong> and session data</li>
|
||||
</ul>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
You have selected <strong>{conflictingProjects.length}</strong> project{conflictingProjects.length !== 1 ? 's' : ''} that already exist:
|
||||
</p>
|
||||
<ul className="list-disc list-inside text-sm space-y-1 ml-2 max-h-32 overflow-y-auto">
|
||||
{conflictingProjects.map((project) => (
|
||||
<li key={project.id}>
|
||||
<strong>{project.name}</strong> (ID: {project.id})
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>Overwriting will:</p>
|
||||
<ul className="list-disc list-inside text-sm space-y-1 ml-2">
|
||||
<li><strong>Delete all existing files</strong> in these projects</li>
|
||||
<li><strong>Replace them with files</strong> from the ZIP archive</li>
|
||||
<li><strong>Preserve Git history</strong> if it exists</li>
|
||||
<li><strong>Keep AI chat history</strong> and session data</li>
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
<p className="text-amber-600 font-medium">
|
||||
This action cannot be undone. Are you sure you want to continue?
|
||||
</p>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={confirmOverwrite}
|
||||
className="bg-amber-600 hover:bg-amber-700"
|
||||
>
|
||||
Yes, {mode === 'single' ? 'Overwrite Project' : 'Overwrite Projects'}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -60,7 +60,7 @@ describe('ProjectSidebar', () => {
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByAltText('Shakespeare')).toBeInTheDocument();
|
||||
expect(screen.getByText('🎭')).toBeInTheDocument();
|
||||
expect(screen.getByText('Shakespeare')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import React, { useEffect, useState } 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, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, FileArchive } 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';
|
||||
@@ -9,10 +9,12 @@ import { useProjects } from '@/hooks/useProjects';
|
||||
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { ZipImportDialog } from '@/components/ZipImportDialog';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import type { Project } from '@/lib/ProjectsManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
|
||||
interface ProjectItemProps {
|
||||
project: Project;
|
||||
@@ -93,6 +95,9 @@ export function ProjectSidebar({
|
||||
const queryClient = useQueryClient();
|
||||
const { data: projects = [], isLoading, error } = useProjects();
|
||||
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
|
||||
const projectsManager = useProjectsManager();
|
||||
const { toast } = useToast();
|
||||
const [isZipDialogOpen, setIsZipDialogOpen] = useState(false);
|
||||
|
||||
const isMobile = useIsMobile();
|
||||
const navigate = useNavigate();
|
||||
@@ -118,6 +123,25 @@ export function ProjectSidebar({
|
||||
}
|
||||
};
|
||||
|
||||
const handleImportZip = async (file: File, overwrite = false, projectId?: string) => {
|
||||
try {
|
||||
// Import project from zip file
|
||||
const project = await projectsManager.importProjectFromZip(file, projectId, overwrite);
|
||||
|
||||
// Show success toast
|
||||
toast({
|
||||
title: overwrite ? "Project Overwritten Successfully" : "Project Imported Successfully",
|
||||
description: `"${project.name}" has been ${overwrite ? 'overwritten' : 'imported'} and is ready to use.`,
|
||||
});
|
||||
|
||||
// Navigate to the imported project
|
||||
navigate(`/project/${project.id}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to import project:', error);
|
||||
throw error; // Re-throw to let the dialog handle the error display
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||
}, [favorites, queryClient]);
|
||||
@@ -135,7 +159,7 @@ export function ProjectSidebar({
|
||||
onClick={() => navigateAndClose('/')}
|
||||
className="flex items-center gap-3 hover:opacity-80 transition-opacity text-left"
|
||||
>
|
||||
<ShakespeareLogo className="w-6 h-6" />
|
||||
<span className="text-2xl">🎭</span>
|
||||
<h1 className="text-xl font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
Shakespeare
|
||||
</h1>
|
||||
@@ -187,6 +211,13 @@ export function ProjectSidebar({
|
||||
<GitBranch className="h-4 w-4" />
|
||||
{t('importRepository')}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setIsZipDialogOpen(true)}
|
||||
className="flex items-center gap-2 w-full"
|
||||
>
|
||||
<FileArchive className="h-4 w-4" />
|
||||
Import ZIP File
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
@@ -249,6 +280,13 @@ export function ProjectSidebar({
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ZIP Import Dialog */}
|
||||
<ZipImportDialog
|
||||
onImport={handleImportZip}
|
||||
open={isZipDialogOpen}
|
||||
onOpenChange={setIsZipDialogOpen}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
import { CreditsDialog } from './CreditsDialog';
|
||||
import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { ProjectPreviewConsoleError } from '@/contexts/ConsoleContext';
|
||||
import { useState } from 'react';
|
||||
|
||||
export interface QuillyProps {
|
||||
@@ -30,17 +30,8 @@ interface ErrorBody {
|
||||
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
|
||||
const navigate = useNavigate();
|
||||
const { settings } = useAISettings();
|
||||
|
||||
// Handle empty provider model gracefully
|
||||
let provider;
|
||||
try {
|
||||
provider = parseProviderModel(providerModel, settings.providers).provider;
|
||||
} catch {
|
||||
// If no valid provider model, use a default or undefined
|
||||
provider = undefined;
|
||||
}
|
||||
|
||||
const credits = useAICredits(provider || { id: '', name: '', apiKey: '', nostr: false });
|
||||
const { provider } = parseProviderModel(providerModel, settings.providers);
|
||||
const credits = useAICredits(provider);
|
||||
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
|
||||
|
||||
const renderBody = (error: Error): ErrorBody => {
|
||||
|
||||
@@ -3,7 +3,7 @@ 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, Bot, GitBranch, Database, Wifi, Settings2, Info, Mail } from 'lucide-react';
|
||||
import { ProjectSidebar } from '@/components/ProjectSidebar';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
@@ -56,6 +56,13 @@ const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [
|
||||
icon: Database,
|
||||
href: '/settings/data',
|
||||
},
|
||||
{
|
||||
id: 'email',
|
||||
title: t('emailUpdates'),
|
||||
description: t('emailUpdatesDescription'),
|
||||
icon: Mail,
|
||||
href: '/settings/email',
|
||||
},
|
||||
{
|
||||
id: 'about',
|
||||
title: t('aboutShakespeare'),
|
||||
|
||||
@@ -34,14 +34,14 @@ 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 { ReadConsoleMessagesTool, ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { useConsole, ProjectPreviewConsoleError } from '@/contexts/ConsoleContext';
|
||||
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
||||
import { Tool } from '@/lib/tools/Tool';
|
||||
import OpenAI from 'openai';
|
||||
import { saveFileToTmp } from '@/lib/fileUtils';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { Quilly } from '@/components/Quilly';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
|
||||
// Clean interfaces now handled by proper hooks
|
||||
|
||||
@@ -52,8 +52,6 @@ interface ChatPaneProps {
|
||||
onLoadingChange?: (isLoading: boolean) => void;
|
||||
isLoading?: boolean;
|
||||
isBuildLoading?: boolean;
|
||||
consoleError?: ProjectPreviewConsoleError | null;
|
||||
onDismissConsoleError?: () => void;
|
||||
}
|
||||
|
||||
export interface ChatPaneRef {
|
||||
@@ -67,15 +65,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
onLoadingChange,
|
||||
isLoading: externalIsLoading,
|
||||
isBuildLoading: externalIsBuildLoading,
|
||||
consoleError,
|
||||
onDismissConsoleError,
|
||||
}, ref) => {
|
||||
const { t } = useTranslation();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const { fs } = useFS();
|
||||
const { git } = useGit();
|
||||
const { user } = useCurrentUser();
|
||||
const { models } = useProviderModels();
|
||||
const [input, setInput] = useState('');
|
||||
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
|
||||
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
|
||||
@@ -85,8 +76,21 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
const [isStuck, setIsStuck] = useState(false);
|
||||
const [aiError, setAIError] = useState<Error | null>(null);
|
||||
|
||||
// Determine which error to show - console error takes priority over AI errors
|
||||
const displayError = consoleError || aiError;
|
||||
// Get console functionality early so it can be used in useEffect
|
||||
const { messagesRef: consoleMessagesRef, addErrorListener, removeErrorListener } = useConsole();
|
||||
|
||||
// Console error handling
|
||||
useEffect(() => {
|
||||
const handleConsoleError = (error: ProjectPreviewConsoleError) => {
|
||||
// Only show console errors if there's no existing AI error
|
||||
if (!aiError) {
|
||||
setAIError(error);
|
||||
}
|
||||
};
|
||||
|
||||
addErrorListener(handleConsoleError);
|
||||
return () => removeErrorListener(handleConsoleError);
|
||||
}, [aiError, addErrorListener, removeErrorListener]);
|
||||
|
||||
// Use external state if provided, otherwise default to false
|
||||
const isBuildLoading = externalIsBuildLoading || false;
|
||||
@@ -98,7 +102,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
});
|
||||
// State to control model selector dropdown
|
||||
const [isModelSelectorOpen, setIsModelSelectorOpen] = useState(false);
|
||||
const [shouldAutostart, setShouldAutostart] = useState(false);
|
||||
const autostartedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -107,29 +110,17 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
}, [providerModel, settings.recentlyUsedModels]);
|
||||
|
||||
useEffect(() => {
|
||||
const urlModel = searchParams.get('model');
|
||||
const autostart = searchParams.get('autostart');
|
||||
|
||||
if (urlModel && !providerModel) {
|
||||
setProviderModel(urlModel);
|
||||
}
|
||||
if (autostart === 'true') {
|
||||
setShouldAutostart(true);
|
||||
}
|
||||
|
||||
// Clear the autostart and model parameters
|
||||
const newSearchParams = new URLSearchParams(searchParams);
|
||||
newSearchParams.delete('autostart');
|
||||
newSearchParams.delete('model');
|
||||
setSearchParams(newSearchParams, { replace: true });
|
||||
}, [providerModel, searchParams, setSearchParams])
|
||||
|
||||
// Reset error state when navigating between projects and switching models
|
||||
useEffect(() => {
|
||||
setAIError(null);
|
||||
}, [projectId, providerModel]);
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const { fs } = useFS();
|
||||
const { git } = useGit();
|
||||
const { user } = useCurrentUser();
|
||||
const { models } = useProviderModels();
|
||||
|
||||
// Initialize AI chat with tools
|
||||
const cwd = `/projects/${projectId}`;
|
||||
const customTools = useMemo(() => {
|
||||
@@ -150,7 +141,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
nostr_read_nips_index: new NostrReadNipsIndexTool(),
|
||||
nostr_generate_kind: new NostrGenerateKindTool(),
|
||||
shell: new ShellTool(fs, cwd, git),
|
||||
read_console_messages: new ReadConsoleMessagesTool(),
|
||||
read_console_messages: new ReadConsoleMessagesTool(() => consoleMessagesRef.current),
|
||||
};
|
||||
|
||||
// Add deploy tool only if user is logged in
|
||||
@@ -162,7 +153,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
|
||||
return baseTools;
|
||||
}, [fs, git, cwd, user, projectId]);
|
||||
}, [fs, git, cwd, user, projectId, consoleMessagesRef]);
|
||||
|
||||
// Convert tools to OpenAI format
|
||||
const tools = useMemo(() => {
|
||||
@@ -180,7 +171,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
artist: `Working on ${projectId}...`,
|
||||
artwork: [
|
||||
{
|
||||
src: '/shakespeare.png',
|
||||
src: '/favicon.png',
|
||||
sizes: '512x512',
|
||||
type: 'image/png'
|
||||
}
|
||||
@@ -220,15 +211,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
sendMessage('Read the console messages and fix any errors present.', providerModel);
|
||||
}, [sendMessage, providerModel]);
|
||||
|
||||
// Handle error dismissal
|
||||
const handleErrorDismiss = useCallback(() => {
|
||||
if (consoleError && onDismissConsoleError) {
|
||||
onDismissConsoleError();
|
||||
} else {
|
||||
setAIError(null);
|
||||
}
|
||||
}, [consoleError, onDismissConsoleError]);
|
||||
|
||||
// Use external loading state if provided, otherwise use internal state
|
||||
const isLoading = externalIsLoading !== undefined ? externalIsLoading : internalIsLoading;
|
||||
|
||||
@@ -284,13 +266,32 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
useEffect(() => {
|
||||
if (autostartedRef.current) return;
|
||||
|
||||
if (shouldAutostart && providerModel && isConfigured) {
|
||||
// Start AI generation
|
||||
addRecentlyUsedModel(providerModel);
|
||||
startGeneration(providerModel);
|
||||
autostartedRef.current = true;
|
||||
const autostart = searchParams.get('autostart');
|
||||
const urlModel = searchParams.get('model');
|
||||
|
||||
if (autostart === 'true' && isConfigured) {
|
||||
// Use model from URL if available, otherwise use current selection
|
||||
const modelToUse = urlModel?.trim() || providerModel.trim();
|
||||
|
||||
if (modelToUse) {
|
||||
// Update provider model if it came from URL
|
||||
if (urlModel?.trim() && urlModel.trim() !== providerModel) {
|
||||
setProviderModel(urlModel.trim());
|
||||
}
|
||||
|
||||
// Clear the autostart and model parameters so they don't trigger again
|
||||
const newSearchParams = new URLSearchParams(searchParams);
|
||||
newSearchParams.delete('autostart');
|
||||
newSearchParams.delete('model');
|
||||
setSearchParams(newSearchParams, { replace: true });
|
||||
|
||||
// Start AI generation
|
||||
addRecentlyUsedModel(modelToUse);
|
||||
startGeneration(modelToUse);
|
||||
autostartedRef.current = true;
|
||||
}
|
||||
}
|
||||
}, [addRecentlyUsedModel, isConfigured, providerModel, shouldAutostart, startGeneration]);
|
||||
}, [addRecentlyUsedModel, isConfigured, providerModel, searchParams, setSearchParams, startGeneration]);
|
||||
|
||||
// Simple scroll event listener
|
||||
useEffect(() => {
|
||||
@@ -529,9 +530,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
{messages.length === 0 && !streamingMessage && !isLoading && (
|
||||
<div className="flex-1 flex items-center justify-center min-h-[400px]">
|
||||
<div className="text-center space-y-4 max-w-md mx-auto">
|
||||
<div className="mb-6">
|
||||
<ShakespeareLogo className="w-16 h-16 mx-auto" />
|
||||
</div>
|
||||
<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')}
|
||||
@@ -614,11 +613,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error Alert (Console or AI) */}
|
||||
{displayError && (
|
||||
{/* AI Error Alert */}
|
||||
{aiError && (
|
||||
<Quilly
|
||||
error={displayError}
|
||||
onDismiss={handleErrorDismiss}
|
||||
error={aiError}
|
||||
onDismiss={() => setAIError(null)}
|
||||
onNewChat={onNewChat}
|
||||
onOpenModelSelector={openModelSelector}
|
||||
onRequestConsoleErrorHelp={handleConsoleErrorHelp}
|
||||
|
||||
@@ -3,12 +3,12 @@ import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { useConsole, type ConsoleMessage } from '@/contexts/ConsoleContext';
|
||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
import { Tabs, TabsContent } from '@/components/ui/tabs';
|
||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload, X, Terminal } from 'lucide-react';
|
||||
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload, X } from 'lucide-react';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
|
||||
@@ -27,7 +27,6 @@ import { cn } from '@/lib/utils';
|
||||
import { FileTree } from './FileTree';
|
||||
import { FileEditor } from './FileEditor';
|
||||
import { DeployDialog } from '@/components/DeployDialog';
|
||||
import { Terminal as TerminalComponent } from '@/components/Terminal';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
|
||||
// Get iframe domain from environment variable
|
||||
@@ -77,8 +76,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
const [selectedFile, setSelectedFile] = useState<string | null>(null);
|
||||
const [fileContent, setFileContent] = useState<string>('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [mobileCodeView, setMobileCodeView] = useState<'explorer' | 'editor' | 'terminal'>('explorer');
|
||||
const [desktopCodeView, setDesktopCodeView] = useState<'files' | 'terminal'>('files');
|
||||
const [mobileCodeView, setMobileCodeView] = useState<'explorer' | 'editor'>('explorer');
|
||||
const isMobile = useIsMobile();
|
||||
const [hasBuiltProject, setHasBuiltProject] = useState(false);
|
||||
const [currentPath, setCurrentPath] = useState('/');
|
||||
@@ -89,6 +87,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||
const { fs } = useFS();
|
||||
const projectsManager = useProjectsManager();
|
||||
const { addMessage: addConsoleMessage, messages: consoleMessages } = useConsole();
|
||||
|
||||
const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId);
|
||||
|
||||
@@ -222,7 +221,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
|
||||
// Log to parent console for debugging with appropriate level
|
||||
console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`);
|
||||
}, []);
|
||||
}, [addConsoleMessage]);
|
||||
|
||||
const handleUpdateNavigationState = useCallback((message: {
|
||||
jsonrpc: '2.0';
|
||||
@@ -457,7 +456,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
setSelectedFile(null);
|
||||
setFileContent('');
|
||||
setMobileCodeView('explorer');
|
||||
setDesktopCodeView('files');
|
||||
|
||||
// Reset navigation history and state
|
||||
setCurrentPath('/');
|
||||
@@ -516,7 +514,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
}
|
||||
};
|
||||
|
||||
const consoleMessages = getConsoleMessages();
|
||||
// consoleMessages is now available from the hook
|
||||
const messageCount = consoleMessages.length;
|
||||
const hasErrors = consoleMessages.some(msg => msg.level === 'error');
|
||||
|
||||
@@ -732,48 +730,18 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
|
||||
<TabsContent value="code" className="h-full mt-0">
|
||||
{isMobile ? (
|
||||
<div className="h-full flex flex-col min-h-0">
|
||||
<div className="h-full flex flex-col">
|
||||
{mobileCodeView === 'explorer' ? (
|
||||
<div className="flex-1 relative min-h-0">
|
||||
<ScrollArea className="h-full">
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
{/* Floating Terminal Button */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setMobileCodeView('terminal')}
|
||||
className="fixed right-4 bottom-safe-nav z-20 h-12 w-12 p-0 rounded-full shadow-lg bg-background border-2"
|
||||
>
|
||||
<Terminal className="h-6 w-6" />
|
||||
</Button>
|
||||
</div>
|
||||
) : mobileCodeView === 'terminal' ? (
|
||||
<>
|
||||
<div className="h-12 px-3 flex items-center gap-2 bg-black text-purple-400 flex-shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setMobileCodeView('explorer')}
|
||||
className="p-1 hover:bg-transparent hover:text-white"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<h3 className="font-semibold">
|
||||
Terminal
|
||||
</h3>
|
||||
<ScrollArea className="flex-1">
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 min-h-0">
|
||||
<TerminalComponent projectId={projectId} />
|
||||
</div>
|
||||
</>
|
||||
</ScrollArea>
|
||||
) : (
|
||||
<>
|
||||
<div className="p-3 border-b bg-gradient-to-r from-primary/5 to-accent/5 flex items-center gap-2">
|
||||
@@ -836,73 +804,50 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
{t('backToPreview')}
|
||||
</Button>
|
||||
<div className="flex-1" />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setDesktopCodeView(desktopCodeView === 'terminal' ? 'files' : 'terminal')}
|
||||
className="gap-2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Terminal className="h-4 w-4" />
|
||||
</Button>
|
||||
<GitStatusIndicator projectId={projectId} />
|
||||
</div>
|
||||
)}
|
||||
{/* Code view header without back button for non-previewable projects */}
|
||||
{!isMobile && !isPreviewable && (
|
||||
<div className="h-12 px-4 border-b flex items-center bg-gradient-to-r from-muted/20 to-background">
|
||||
<div className="flex-1" />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setDesktopCodeView(desktopCodeView === 'terminal' ? 'files' : 'terminal')}
|
||||
className="gap-2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Terminal className="h-4 w-4" />
|
||||
</Button>
|
||||
<GitStatusIndicator projectId={projectId} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex-1 flex min-h-0">
|
||||
{desktopCodeView === 'terminal' ? (
|
||||
<div className="flex-1">
|
||||
<TerminalComponent projectId={projectId} />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="w-1/3 border-r flex flex-col">
|
||||
<ScrollArea className="flex-1">
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
<div className="w-1/3 border-r flex flex-col">
|
||||
<ScrollArea className="flex-1">
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
<div className="flex-1">
|
||||
{selectedFile ? (
|
||||
<FileEditor
|
||||
filePath={selectedFile}
|
||||
content={fileContent}
|
||||
onSave={handleFileSave}
|
||||
isLoading={isLoading}
|
||||
projectId={projectId}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<p className="text-muted-foreground">
|
||||
{t('selectFileFromExplorer')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1">
|
||||
{selectedFile ? (
|
||||
<FileEditor
|
||||
filePath={selectedFile}
|
||||
content={fileContent}
|
||||
onSave={handleFileSave}
|
||||
isLoading={isLoading}
|
||||
projectId={projectId}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<p className="text-muted-foreground">
|
||||
{t('selectFileFromExplorer')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
export interface ShakespeareLogoProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function ShakespeareLogo({ className }: ShakespeareLogoProps) {
|
||||
return (
|
||||
<img
|
||||
src="/shakespeare.svg"
|
||||
alt="Shakespeare"
|
||||
className={className}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,235 +0,0 @@
|
||||
import { useState, useRef, useEffect, useCallback } from 'react';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Copy } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
|
||||
interface TerminalProps {
|
||||
projectId: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
interface TerminalLine {
|
||||
id: string;
|
||||
type: 'input' | 'output' | 'error';
|
||||
content: string;
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
export function Terminal({ projectId, className }: TerminalProps) {
|
||||
const [lines, setLines] = useState<TerminalLine[]>([]);
|
||||
const [currentInput, setCurrentInput] = useState('');
|
||||
const [isExecuting, setIsExecuting] = useState(false);
|
||||
const [commandHistory, setCommandHistory] = useState<string[]>([]);
|
||||
const [historyIndex, setHistoryIndex] = useState(-1);
|
||||
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const shellToolRef = useRef<ShellTool | null>(null);
|
||||
|
||||
const { fs } = useFS();
|
||||
const { git } = useGit();
|
||||
|
||||
// Initialize ShellTool
|
||||
useEffect(() => {
|
||||
shellToolRef.current = new ShellTool(fs, `/projects/${projectId}`, git);
|
||||
|
||||
// Add welcome message
|
||||
setLines([{
|
||||
id: Date.now().toString(),
|
||||
type: 'output',
|
||||
content: `Welcome to Shakespeare Terminal\nType 'help' to see available commands.`,
|
||||
timestamp: new Date()
|
||||
}]);
|
||||
}, [projectId, fs, git]);
|
||||
|
||||
// Auto-scroll to bottom when new lines are added or execution state changes
|
||||
useEffect(() => {
|
||||
if (scrollRef.current) {
|
||||
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
|
||||
}
|
||||
}, [lines, isExecuting]);
|
||||
|
||||
// Focus input when component mounts
|
||||
useEffect(() => {
|
||||
if (inputRef.current) {
|
||||
inputRef.current.focus();
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Refocus input after command execution
|
||||
useEffect(() => {
|
||||
if (!isExecuting && inputRef.current) {
|
||||
inputRef.current.focus();
|
||||
}
|
||||
}, [isExecuting]);
|
||||
|
||||
const addLine = useCallback((type: TerminalLine['type'], content: string) => {
|
||||
const newLine: TerminalLine = {
|
||||
id: Date.now().toString() + Math.random(),
|
||||
type,
|
||||
content,
|
||||
timestamp: new Date()
|
||||
};
|
||||
setLines(prev => [...prev, newLine]);
|
||||
}, []);
|
||||
|
||||
const executeCommand = useCallback(async (command: string) => {
|
||||
if (!shellToolRef.current || !command.trim()) return;
|
||||
|
||||
// Add command to history
|
||||
if (command.trim() && !commandHistory.includes(command.trim())) {
|
||||
setCommandHistory(prev => [...prev, command.trim()]);
|
||||
}
|
||||
setHistoryIndex(-1);
|
||||
|
||||
// Add input line
|
||||
addLine('input', command);
|
||||
|
||||
setIsExecuting(true);
|
||||
|
||||
try {
|
||||
// Handle special help command
|
||||
if (command.trim() === 'help') {
|
||||
const availableCommands = shellToolRef.current.getAvailableCommands();
|
||||
const helpText = `Available commands:\n\n${availableCommands.map(cmd =>
|
||||
`${cmd.name.padEnd(12)} - ${cmd.description}`
|
||||
).join('\n')}\n\nUse 'which <command>' for more details about a specific command.`;
|
||||
addLine('output', helpText);
|
||||
} else if (command.trim() === 'clear') {
|
||||
setLines([]);
|
||||
} else {
|
||||
const result = await shellToolRef.current.execute({ command });
|
||||
|
||||
// Add output
|
||||
if (result && result.trim()) {
|
||||
addLine('output', result);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
addLine('error', `Error: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
} finally {
|
||||
setIsExecuting(false);
|
||||
}
|
||||
}, [addLine, commandHistory]);
|
||||
|
||||
const handleSubmit = useCallback((e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (currentInput.trim() && !isExecuting) {
|
||||
executeCommand(currentInput);
|
||||
setCurrentInput('');
|
||||
}
|
||||
}, [currentInput, isExecuting, executeCommand]);
|
||||
|
||||
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
|
||||
if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
if (commandHistory.length > 0) {
|
||||
const newIndex = historyIndex === -1 ? commandHistory.length - 1 : Math.max(0, historyIndex - 1);
|
||||
setHistoryIndex(newIndex);
|
||||
setCurrentInput(commandHistory[newIndex]);
|
||||
}
|
||||
} else if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
if (historyIndex >= 0) {
|
||||
const newIndex = historyIndex + 1;
|
||||
if (newIndex >= commandHistory.length) {
|
||||
setHistoryIndex(-1);
|
||||
setCurrentInput('');
|
||||
} else {
|
||||
setHistoryIndex(newIndex);
|
||||
setCurrentInput(commandHistory[newIndex]);
|
||||
}
|
||||
}
|
||||
} else if (e.key === 'Tab') {
|
||||
e.preventDefault();
|
||||
// Basic tab completion could be added here
|
||||
}
|
||||
}, [commandHistory, historyIndex]);
|
||||
|
||||
const copyToClipboard = useCallback(async (content: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(content);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy to clipboard:', error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Focus input when clicking anywhere in the terminal
|
||||
const handleTerminalClick = useCallback(() => {
|
||||
if (inputRef.current) {
|
||||
inputRef.current.focus();
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className={cn("h-full flex flex-col bg-black text-slate-300 font-mono text-sm", className)}>
|
||||
{/* Terminal Content */}
|
||||
<div className="flex-1 flex flex-col min-h-0" onClick={handleTerminalClick}>
|
||||
<ScrollArea className="flex-1" ref={scrollRef}>
|
||||
<div className="p-2 space-y-1">
|
||||
{lines.map((line) => (
|
||||
<div
|
||||
key={line.id}
|
||||
className={cn(
|
||||
"group relative",
|
||||
line.type === 'input' && "text-white",
|
||||
line.type === 'error' && "text-red-400",
|
||||
line.type === 'output' && "text-slate-300"
|
||||
)}
|
||||
>
|
||||
<pre className="whitespace-pre-wrap break-words font-mono leading-relaxed">
|
||||
{line.type === 'input' ? (
|
||||
<span className="text-purple-400 font-mono whitespace-nowrap">
|
||||
${' '}
|
||||
</span>
|
||||
) : null}
|
||||
{line.content}
|
||||
</pre>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
copyToClipboard(line.content);
|
||||
}}
|
||||
className="absolute right-0 top-0 h-4 w-4 p-0 opacity-0 group-hover:opacity-100 transition-opacity text-gray-500 hover:text-white hover:bg-gray-700"
|
||||
>
|
||||
<Copy className="h-2 w-2" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Current Command Input - inline with content */}
|
||||
{!isExecuting && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-purple-400 font-mono whitespace-nowrap">
|
||||
$
|
||||
</span>
|
||||
<form onSubmit={handleSubmit} className="flex-1 relative">
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
value={currentInput}
|
||||
onChange={(e) => setCurrentInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={isExecuting}
|
||||
className="w-full bg-transparent border-none outline-none text-white font-mono placeholder-gray-500 caret-white leading-relaxed"
|
||||
placeholder=""
|
||||
autoComplete="off"
|
||||
spellCheck="false"
|
||||
autoCapitalize="off"
|
||||
autoCorrect="off"
|
||||
/>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { ZipImportDialog } from './ZipImportDialog';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
|
||||
// Mock the useProjects hook
|
||||
const mockProjects = [
|
||||
{ id: 'test-project', name: 'Test Project', path: '/projects/test-project', lastModified: new Date() }
|
||||
];
|
||||
|
||||
vi.mock('@/hooks/useProjects', () => ({
|
||||
useProjects: () => ({
|
||||
data: mockProjects,
|
||||
isLoading: false,
|
||||
error: null
|
||||
})
|
||||
}));
|
||||
|
||||
describe('ZipImportDialog', () => {
|
||||
const mockOnImport = vi.fn();
|
||||
const defaultProps = {
|
||||
onImport: mockOnImport,
|
||||
disabled: false
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mockOnImport.mockClear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders dialog trigger button', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Import ZIP')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens dialog when trigger is clicked', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const triggerButton = screen.getByText('Import ZIP');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Import Project from ZIP')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('processes file selection without displaying project ID', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Open dialog
|
||||
const triggerButton = screen.getByText('Import ZIP');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
// Create a mock file
|
||||
const file = new File(['test content'], 'my-project.zip', { type: 'application/zip' });
|
||||
|
||||
// Find the hidden file input by ref
|
||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||
|
||||
if (fileInput) {
|
||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||
}
|
||||
|
||||
await waitFor(() => {
|
||||
// Verify that the file name is displayed (from the file selection area)
|
||||
expect(screen.getByText('my-project.zip')).toBeInTheDocument();
|
||||
// Verify that Project ID label is not displayed
|
||||
expect(screen.queryByText('Project ID')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows overwrite warning when project ID already exists', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Open dialog
|
||||
const triggerButton = screen.getByText('Import ZIP');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
// Create a mock file that will generate an existing project ID
|
||||
const file = new File(['test content'], 'test-project.zip', { type: 'application/zip' });
|
||||
|
||||
// Find the hidden file input by ref
|
||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||
|
||||
if (fileInput) {
|
||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||
}
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/A project with this ID already exists/)).toBeInTheDocument();
|
||||
expect(screen.getByText('Overwrite Project')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('calls onImport with correct parameters when import button is clicked', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Open dialog
|
||||
const triggerButton = screen.getByText('Import ZIP');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
// Create a mock file
|
||||
const file = new File(['test content'], 'new-project.zip', { type: 'application/zip' });
|
||||
|
||||
// Find the hidden file input by ref
|
||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||
|
||||
if (fileInput) {
|
||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||
}
|
||||
|
||||
// Wait for file to be processed
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('new-project.zip')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Click import button
|
||||
const importButton = screen.getByText('Import Project');
|
||||
fireEvent.click(importButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockOnImport).toHaveBeenCalledWith(file, false, "new-project");
|
||||
});
|
||||
});
|
||||
|
||||
it('shows overwrite confirmation dialog when overwrite button is clicked', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Open dialog
|
||||
const triggerButton = screen.getByText('Import ZIP');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
// Create a mock file that will generate an existing project ID
|
||||
const file = new File(['test content'], 'test-project.zip', { type: 'application/zip' });
|
||||
|
||||
// Find the hidden file input by ref
|
||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||
|
||||
if (fileInput) {
|
||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||
}
|
||||
|
||||
// Wait for overwrite button to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Overwrite Project')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Click overwrite button
|
||||
const overwriteButton = screen.getByText('Overwrite Project');
|
||||
fireEvent.click(overwriteButton);
|
||||
|
||||
// Check for overwrite confirmation dialog
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Overwrite Existing Project')).toBeInTheDocument();
|
||||
// Use a more flexible matcher for the text that might be split across elements
|
||||
const dialogContent = screen.getByText('Overwrite Existing Project').closest('.AlertDialogContent');
|
||||
if (dialogContent) {
|
||||
expect(dialogContent.textContent).toContain('A project with the ID "test-project" already exists');
|
||||
}
|
||||
}, { timeout: 2000 });
|
||||
});
|
||||
|
||||
it('does not show project ID input field (simplified interface)', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Open dialog
|
||||
const triggerButton = screen.getByText('Import ZIP');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
// Check that there's no input field for project ID
|
||||
expect(screen.queryByLabelText('Project ID')).not.toBeInTheDocument();
|
||||
expect(screen.queryByPlaceholderText('project-name')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,397 @@
|
||||
import React, { useState, useRef, useCallback, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
|
||||
import { Upload, FileArchive, AlertCircle, FileText, Trash2 } from 'lucide-react';
|
||||
import { useProjects } from '@/hooks/useProjects';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ZipImportDialogProps {
|
||||
onImport: (file: File, overwrite?: boolean, projectId?: string) => Promise<void>;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function ZipImportDialog({ onImport, disabled = false, className, open, onOpenChange }: ZipImportDialogProps) {
|
||||
// Use controlled state if props are provided, otherwise use internal state
|
||||
const [internalIsOpen, setInternalIsOpen] = useState(false);
|
||||
const isOpen = open !== undefined ? open : internalIsOpen;
|
||||
const setIsOpen = onOpenChange || setInternalIsOpen;
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||
const [generatedId, setGeneratedId] = useState('');
|
||||
const [isImporting, setIsImporting] = useState(false);
|
||||
const [importProgress, setImportProgress] = useState(0);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
const [existingProject, setExistingProject] = useState<{ id: string; name: string } | null>(null);
|
||||
const [showOverwriteDialog, setShowOverwriteDialog] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const { data: projects = [] } = useProjects();
|
||||
|
||||
const handleFileSelect = (file: File) => {
|
||||
// Only accept zip files
|
||||
if (!file.name.toLowerCase().endsWith('.zip')) {
|
||||
setError('Please select a ZIP file');
|
||||
return;
|
||||
}
|
||||
|
||||
setSelectedFile(file);
|
||||
setError(null);
|
||||
|
||||
// Auto-generate ID from file name
|
||||
const baseName = file.name.replace(/\.zip$/i, '');
|
||||
const id = baseName
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
setGeneratedId(id);
|
||||
};
|
||||
|
||||
// Check for existing project when generated ID changes
|
||||
useEffect(() => {
|
||||
if (generatedId && projects.length > 0) {
|
||||
const existing = projects.find(project => project.id === generatedId);
|
||||
setExistingProject(existing || null);
|
||||
} else {
|
||||
setExistingProject(null);
|
||||
}
|
||||
}, [generatedId, projects]);
|
||||
|
||||
// Drag and drop handlers
|
||||
const handleDragOver = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(true);
|
||||
}, []);
|
||||
|
||||
const handleDragLeave = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(false);
|
||||
}, []);
|
||||
|
||||
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(false);
|
||||
|
||||
const files = Array.from(e.dataTransfer.files);
|
||||
if (files.length > 0) {
|
||||
handleFileSelect(files[0]);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleDragOverDialog = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setIsDragOver(true);
|
||||
}, []);
|
||||
|
||||
const handleDragLeaveDialog = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setIsDragOver(false);
|
||||
}, []);
|
||||
|
||||
const handleDropDialog = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setIsDragOver(false);
|
||||
|
||||
const files = Array.from(e.dataTransfer.files);
|
||||
if (files.length > 0) {
|
||||
handleFileSelect(files[0]);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleClickUpload = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
const handleFileRemove = () => {
|
||||
setSelectedFile(null);
|
||||
setGeneratedId('');
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const handleImport = async (overwrite = false) => {
|
||||
if (!selectedFile) return;
|
||||
|
||||
setIsImporting(true);
|
||||
setImportProgress(0);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Simulate progress for better UX
|
||||
const progressInterval = setInterval(() => {
|
||||
setImportProgress(prev => Math.min(prev + 10, 90));
|
||||
}, 200);
|
||||
|
||||
await onImport(selectedFile, overwrite, generatedId);
|
||||
|
||||
clearInterval(progressInterval);
|
||||
setImportProgress(100);
|
||||
|
||||
// Close dialog after a short delay
|
||||
setTimeout(() => {
|
||||
setIsOpen(false);
|
||||
setSelectedFile(null);
|
||||
setGeneratedId('');
|
||||
setImportProgress(0);
|
||||
setExistingProject(null);
|
||||
}, 1000);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to import project');
|
||||
setImportProgress(0);
|
||||
} finally {
|
||||
setIsImporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImportWithOverwriteCheck = async () => {
|
||||
if (!selectedFile || !generatedId) return;
|
||||
|
||||
// Check if project with this ID already exists
|
||||
try {
|
||||
// This would ideally be passed as a prop or through context
|
||||
// For now, we'll assume the parent will handle the check and pass existing project info
|
||||
if (existingProject) {
|
||||
setShowOverwriteDialog(true);
|
||||
} else {
|
||||
await handleImport(false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error checking existing project:', error);
|
||||
await handleImport(false);
|
||||
}
|
||||
};
|
||||
|
||||
const confirmOverwrite = async () => {
|
||||
setShowOverwriteDialog(false);
|
||||
await handleImport(true);
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
if (!isImporting) {
|
||||
setIsOpen(false);
|
||||
setSelectedFile(null);
|
||||
setGeneratedId('');
|
||||
setError(null);
|
||||
setImportProgress(0);
|
||||
}
|
||||
};
|
||||
|
||||
// Only render DialogTrigger if this component is being used in uncontrolled mode
|
||||
// (no open/onOpenChange props provided)
|
||||
const isControlled = open !== undefined && onOpenChange !== undefined;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
||||
{!isControlled && (
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
className={cn("gap-2", className)}
|
||||
>
|
||||
<FileArchive className="h-4 w-4" />
|
||||
Import ZIP
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
)}
|
||||
|
||||
<DialogContent
|
||||
className="sm:max-w-md"
|
||||
onDragOver={handleDragOverDialog}
|
||||
onDragLeave={handleDragLeaveDialog}
|
||||
onDrop={handleDropDialog}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Upload className="h-5 w-5" />
|
||||
Import Project from ZIP
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Upload a ZIP file containing your project source code to import it into Shakespeare.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
{!isImporting && (
|
||||
<>
|
||||
{/* Drag and Drop Area */}
|
||||
<div
|
||||
className={cn(
|
||||
"relative border-2 border-dashed rounded-lg p-8 text-center transition-colors cursor-pointer",
|
||||
isDragOver ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50 hover:bg-primary/5",
|
||||
selectedFile && "border-green-500/50 bg-green-500/5"
|
||||
)}
|
||||
onClick={handleClickUpload}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
onChange={(e) => {
|
||||
const files = e.target.files;
|
||||
if (files && files.length > 0) {
|
||||
handleFileSelect(files[0]);
|
||||
}
|
||||
}}
|
||||
accept=".zip"
|
||||
className="hidden"
|
||||
disabled={isImporting}
|
||||
/>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex justify-center">
|
||||
{selectedFile ? (
|
||||
<FileText className="h-8 w-8 text-green-600" />
|
||||
) : (
|
||||
<Upload className="h-8 w-8 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{selectedFile ? (
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium text-green-600">
|
||||
{selectedFile.name}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{(selectedFile.size / 1024 / 1024).toFixed(2)} MB
|
||||
</p>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleFileRemove();
|
||||
}}
|
||||
className="text-xs text-destructive hover:underline"
|
||||
>
|
||||
Remove file
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium">
|
||||
Drop your ZIP file here or click to browse
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Supports ZIP files up to 50MB
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error Display */}
|
||||
{error && (
|
||||
<div className="flex items-center gap-2 text-sm text-destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Overwrite Warning */}
|
||||
{existingProject && (
|
||||
<div className="flex items-center gap-2 text-xs text-amber-600 bg-amber-50 dark:bg-amber-950/20 p-2 rounded">
|
||||
<AlertCircle className="h-3 w-3" />
|
||||
A project with this ID already exists. You can choose to overwrite it.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Import Button */}
|
||||
<div className="flex justify-end gap-2 pt-4">
|
||||
<Button variant="outline" onClick={handleClose} disabled={isImporting}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleImportWithOverwriteCheck}
|
||||
disabled={!selectedFile || !generatedId || isImporting}
|
||||
className={existingProject ? "bg-amber-600 hover:bg-amber-700" : ""}
|
||||
>
|
||||
{existingProject ? (
|
||||
<>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Overwrite Project
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Upload className="mr-2 h-4 w-4" />
|
||||
Import Project
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Import Progress */}
|
||||
{isImporting && (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div>
|
||||
Importing project...
|
||||
</div>
|
||||
<Progress value={importProgress} className="w-full" />
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
Extracting files and setting up project...
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Success State */}
|
||||
{!isImporting && importProgress === 100 && (
|
||||
<div className="flex items-center gap-2 text-sm text-green-600">
|
||||
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path>
|
||||
</svg>
|
||||
Project imported successfully!
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Overwrite Confirmation Dialog */}
|
||||
<AlertDialog open={showOverwriteDialog} onOpenChange={setShowOverwriteDialog}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="flex items-center gap-2">
|
||||
<AlertCircle className="h-5 w-5 text-amber-600" />
|
||||
Overwrite Existing Project
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription className="space-y-2">
|
||||
<p>
|
||||
A project with the ID "<strong>{generatedId}</strong>" already exists.
|
||||
Overwriting it will:
|
||||
</p>
|
||||
<ul className="list-disc list-inside text-sm space-y-1 ml-2">
|
||||
<li><strong>Delete all existing files</strong> in the project</li>
|
||||
<li><strong>Replace them with files</strong> from the ZIP archive</li>
|
||||
<li><strong>Preserve Git history</strong> if it exists</li>
|
||||
<li><strong>Keep AI chat history</strong> and session data</li>
|
||||
</ul>
|
||||
<p className="text-amber-600 font-medium">
|
||||
This action cannot be undone. Are you sure you want to continue?
|
||||
</p>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={confirmOverwrite}
|
||||
className="bg-amber-600 hover:bg-amber-700"
|
||||
>
|
||||
Yes, Overwrite Project
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Cloud, Upload } from 'lucide-react';
|
||||
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";
|
||||
@@ -32,7 +32,6 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
}) => {
|
||||
// Removed step state - we only have one step now
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isFileLoading, setIsFileLoading] = useState(false);
|
||||
const [nsec, setNsec] = useState('');
|
||||
const [bunkerUri, setBunkerUri] = useState('');
|
||||
const [activeTab, setActiveTab] = useState<'nsec' | 'bunker'>('nsec');
|
||||
@@ -40,9 +39,7 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
nsec?: string;
|
||||
bunker?: string;
|
||||
extension?: string;
|
||||
file?: string;
|
||||
}>({});
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const login = useLoginActions();
|
||||
|
||||
@@ -50,15 +47,10 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setIsLoading(false);
|
||||
setIsFileLoading(false);
|
||||
setNsec('');
|
||||
setBunkerUri('');
|
||||
setActiveTab('nsec');
|
||||
setErrors({});
|
||||
// Reset file input
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = '';
|
||||
}
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
@@ -94,7 +86,20 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
|
||||
return;
|
||||
}
|
||||
executeLogin(nsec);
|
||||
|
||||
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 () => {
|
||||
@@ -126,52 +131,6 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
}
|
||||
};
|
||||
|
||||
const executeLogin = (key: string) => {
|
||||
setIsLoading(true);
|
||||
setErrors({});
|
||||
|
||||
// Use a timeout to allow the UI to update before the synchronous login call
|
||||
setTimeout(() => {
|
||||
try {
|
||||
login.nsec(key);
|
||||
onLogin();
|
||||
onClose();
|
||||
} catch {
|
||||
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, 50);
|
||||
};
|
||||
|
||||
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
setIsFileLoading(true);
|
||||
setErrors({});
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
setIsFileLoading(false);
|
||||
const content = event.target?.result as string;
|
||||
if (content) {
|
||||
const trimmedContent = content.trim();
|
||||
if (validateNsec(trimmedContent)) {
|
||||
executeLogin(trimmedContent);
|
||||
} else {
|
||||
setErrors({ file: 'File does not contain a valid secret key.' });
|
||||
}
|
||||
} else {
|
||||
setErrors({ file: 'Could not read file content.' });
|
||||
}
|
||||
};
|
||||
reader.onerror = () => {
|
||||
setIsFileLoading(false);
|
||||
setErrors({ file: 'Failed to read file.' });
|
||||
};
|
||||
reader.readAsText(file);
|
||||
};
|
||||
|
||||
const handleSignupClick = () => {
|
||||
onClose();
|
||||
if (onSignup) {
|
||||
@@ -243,37 +202,14 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex space-x-2">
|
||||
<Button
|
||||
size="lg"
|
||||
onClick={handleKeyLogin}
|
||||
disabled={isLoading || !nsec.trim()}
|
||||
className="flex-1"
|
||||
>
|
||||
{isLoading ? 'Verifying...' : 'Add Key'}
|
||||
</Button>
|
||||
|
||||
<input
|
||||
type="file"
|
||||
accept=".txt"
|
||||
className="hidden"
|
||||
ref={fileInputRef}
|
||||
onChange={handleFileUpload}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="lg"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={isLoading || isFileLoading}
|
||||
className="px-3"
|
||||
>
|
||||
<Upload className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{errors.file && (
|
||||
<p className="text-sm text-red-500 text-center">{errors.file}</p>
|
||||
)}
|
||||
<Button
|
||||
size="lg"
|
||||
onClick={handleKeyLogin}
|
||||
disabled={isLoading || !nsec.trim()}
|
||||
className="w-full"
|
||||
>
|
||||
{isLoading ? 'Verifying...' : 'Add Key'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { ConsoleProvider, useConsole } from './ConsoleContext';
|
||||
import { ProjectPreviewConsoleError } from '@/lib/errors/ProjectPreviewConsoleError';
|
||||
|
||||
// Test wrapper component
|
||||
function TestWrapper({ children }: { children: React.ReactNode }) {
|
||||
return <ConsoleProvider>{children}</ConsoleProvider>;
|
||||
}
|
||||
|
||||
describe('ConsoleContext', () => {
|
||||
it('should provide console functionality', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
|
||||
expect(result.current.messages).toEqual([]);
|
||||
expect(result.current.messagesRef.current).toEqual([]);
|
||||
expect(typeof result.current.addMessage).toBe('function');
|
||||
expect(typeof result.current.clearMessages).toBe('function');
|
||||
expect(typeof result.current.addErrorListener).toBe('function');
|
||||
expect(typeof result.current.removeErrorListener).toBe('function');
|
||||
});
|
||||
|
||||
it('should add and retrieve messages', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
|
||||
act(() => {
|
||||
result.current.addMessage('log', 'Test log message');
|
||||
result.current.addMessage('error', 'Test error message');
|
||||
});
|
||||
|
||||
expect(result.current.messages).toHaveLength(2);
|
||||
expect(result.current.messagesRef.current).toHaveLength(2);
|
||||
expect(result.current.messages[0]).toEqual({
|
||||
level: 'log',
|
||||
message: 'Test log message',
|
||||
});
|
||||
expect(result.current.messagesRef.current[0]).toEqual({
|
||||
level: 'log',
|
||||
message: 'Test log message',
|
||||
});
|
||||
expect(result.current.messages[1]).toEqual({
|
||||
level: 'error',
|
||||
message: 'Test error message',
|
||||
});
|
||||
expect(result.current.messagesRef.current[1]).toEqual({
|
||||
level: 'error',
|
||||
message: 'Test error message',
|
||||
});
|
||||
});
|
||||
|
||||
it('should clear messages', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
|
||||
act(() => {
|
||||
result.current.addMessage('log', 'Test message');
|
||||
});
|
||||
|
||||
expect(result.current.messages).toHaveLength(1);
|
||||
expect(result.current.messagesRef.current).toHaveLength(1);
|
||||
|
||||
act(() => {
|
||||
result.current.clearMessages();
|
||||
});
|
||||
|
||||
expect(result.current.messages).toHaveLength(0);
|
||||
expect(result.current.messagesRef.current).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should trigger error listener when error message is added', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
const errorListener = vi.fn();
|
||||
|
||||
act(() => {
|
||||
result.current.addErrorListener(errorListener);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.addMessage('error', 'Test error message');
|
||||
});
|
||||
|
||||
expect(errorListener).toHaveBeenCalledTimes(1);
|
||||
expect(errorListener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
message: 'Console error detected: Test error message',
|
||||
logs: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
level: 'error',
|
||||
message: 'Test error message',
|
||||
}),
|
||||
]),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('should not trigger error listener for non-error messages', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
const errorListener = vi.fn();
|
||||
|
||||
act(() => {
|
||||
result.current.addErrorListener(errorListener);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.addMessage('log', 'Test log message');
|
||||
result.current.addMessage('warn', 'Test warning message');
|
||||
result.current.addMessage('info', 'Test info message');
|
||||
});
|
||||
|
||||
expect(errorListener).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should remove error listener correctly', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
const errorListener = vi.fn();
|
||||
|
||||
act(() => {
|
||||
result.current.addErrorListener(errorListener);
|
||||
result.current.removeErrorListener(errorListener);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.addMessage('error', 'Test error message');
|
||||
});
|
||||
|
||||
expect(errorListener).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle listener errors gracefully', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
const faultyListener = vi.fn(() => {
|
||||
throw new Error('Listener error');
|
||||
});
|
||||
const workingListener = vi.fn();
|
||||
|
||||
act(() => {
|
||||
result.current.addErrorListener(faultyListener);
|
||||
result.current.addErrorListener(workingListener);
|
||||
});
|
||||
|
||||
// Should not throw despite faulty listener
|
||||
expect(() => {
|
||||
act(() => {
|
||||
result.current.addMessage('error', 'Test error message');
|
||||
});
|
||||
}).not.toThrow();
|
||||
|
||||
expect(faultyListener).toHaveBeenCalled();
|
||||
expect(workingListener).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should throw error when used outside provider', () => {
|
||||
expect(() => {
|
||||
renderHook(() => useConsole());
|
||||
}).toThrow('useConsole must be used within a ConsoleProvider');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ProjectPreviewConsoleError', () => {
|
||||
it('should create error with console logs', () => {
|
||||
const logs = [{ level: 'error' as const, message: 'Test error' }];
|
||||
const error = new ProjectPreviewConsoleError('Test message', logs);
|
||||
|
||||
expect(error.message).toBe('Test message');
|
||||
expect(error.name).toBe('ProjectPreviewConsoleError');
|
||||
expect(error.logs).toEqual(logs);
|
||||
expect(error instanceof Error).toBe(true);
|
||||
expect(error instanceof ProjectPreviewConsoleError).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import React, { createContext, useContext, useState, useCallback, useRef, ReactNode } from 'react';
|
||||
|
||||
import { ProjectPreviewConsoleError } from '@/lib/errors/ProjectPreviewConsoleError';
|
||||
|
||||
export interface ConsoleMessage {
|
||||
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
|
||||
message: string;
|
||||
}
|
||||
|
||||
export { ProjectPreviewConsoleError };
|
||||
|
||||
interface ConsoleContextType {
|
||||
messages: ConsoleMessage[];
|
||||
messagesRef: React.MutableRefObject<ConsoleMessage[]>;
|
||||
addMessage: (level: ConsoleMessage['level'], message: string) => void;
|
||||
clearMessages: () => void;
|
||||
addErrorListener: (listener: (error: ProjectPreviewConsoleError) => void) => void;
|
||||
removeErrorListener: (listener: (error: ProjectPreviewConsoleError) => void) => void;
|
||||
}
|
||||
|
||||
const ConsoleContext = createContext<ConsoleContextType | undefined>(undefined);
|
||||
|
||||
export function useConsole(): ConsoleContextType {
|
||||
const context = useContext(ConsoleContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useConsole must be used within a ConsoleProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
interface ConsoleProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function ConsoleProvider({ children }: ConsoleProviderProps) {
|
||||
const [messages, setMessages] = useState<ConsoleMessage[]>([]);
|
||||
const messagesRef = useRef<ConsoleMessage[]>([]);
|
||||
const [errorListeners, setErrorListeners] = useState<Array<(error: ProjectPreviewConsoleError) => void>>([]);
|
||||
|
||||
const addMessage = useCallback((level: ConsoleMessage['level'], message: string) => {
|
||||
const consoleMessage: ConsoleMessage = {
|
||||
level,
|
||||
message,
|
||||
};
|
||||
|
||||
// Update both state and ref
|
||||
const newMessages = [...messagesRef.current, consoleMessage];
|
||||
messagesRef.current = newMessages;
|
||||
setMessages(newMessages);
|
||||
|
||||
// If this is an error, notify listeners
|
||||
if (level === 'error') {
|
||||
const error = new ProjectPreviewConsoleError(
|
||||
`Console error detected: ${message}`,
|
||||
newMessages.filter(msg => msg.level === 'error')
|
||||
);
|
||||
|
||||
errorListeners.forEach(listener => {
|
||||
try {
|
||||
listener(error);
|
||||
} catch (err) {
|
||||
console.warn('Error listener failed:', err);
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [errorListeners]);
|
||||
|
||||
const clearMessages = useCallback(() => {
|
||||
setMessages([]);
|
||||
messagesRef.current = [];
|
||||
}, []);
|
||||
|
||||
const addErrorListener = useCallback((listener: (error: ProjectPreviewConsoleError) => void) => {
|
||||
setErrorListeners(prev => [...prev, listener]);
|
||||
}, []);
|
||||
|
||||
const removeErrorListener = useCallback((listener: (error: ProjectPreviewConsoleError) => void) => {
|
||||
setErrorListeners(prev => prev.filter(l => l !== listener));
|
||||
}, []);
|
||||
|
||||
const value: ConsoleContextType = {
|
||||
messages,
|
||||
messagesRef,
|
||||
addMessage,
|
||||
clearMessages,
|
||||
addErrorListener,
|
||||
removeErrorListener,
|
||||
};
|
||||
|
||||
return (
|
||||
<ConsoleContext.Provider value={value}>
|
||||
{children}
|
||||
</ConsoleContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -4,18 +4,34 @@ import { createAIClient } from '@/lib/ai-client';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
const creditsResponseSchema = z.object({
|
||||
// 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 */
|
||||
/**
|
||||
* 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(provider: AIProvider) {
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
@@ -25,7 +41,20 @@ export function useAICredits(provider: AIProvider) {
|
||||
try {
|
||||
const ai = createAIClient(provider, user);
|
||||
const data = await ai.get('/credits');
|
||||
return creditsResponseSchema.parse(data);
|
||||
|
||||
// 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);
|
||||
|
||||
@@ -80,7 +80,7 @@ export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Failed to generate project ID';
|
||||
onError?.(errorMessage);
|
||||
throw error;
|
||||
throw new Error(errorMessage);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
|
||||
+4
-37
@@ -110,13 +110,11 @@
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
border-color: hsl(var(--border));
|
||||
@apply border-border;
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: hsl(var(--background));
|
||||
color: hsl(var(--foreground));
|
||||
font-family: 'Inter Variable', 'Inter', 'system-ui', 'sans-serif';
|
||||
@apply bg-background text-foreground font-sans;
|
||||
font-feature-settings: "rlig" 1, "calt" 1;
|
||||
}
|
||||
|
||||
@@ -140,10 +138,8 @@
|
||||
}
|
||||
|
||||
/* GitHub-style focus rings */
|
||||
.focus-ring:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 2px hsl(var(--ring));
|
||||
outline-offset: 2px;
|
||||
.focus-ring {
|
||||
@apply focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2;
|
||||
}
|
||||
|
||||
/* Smooth transitions for theme switching */
|
||||
@@ -251,35 +247,6 @@
|
||||
max-height: 100dvh;
|
||||
}
|
||||
|
||||
/* iOS Safe Area Support */
|
||||
.safe-area-inset-bottom {
|
||||
padding-bottom: env(safe-area-inset-bottom);
|
||||
}
|
||||
|
||||
.safe-area-inset-top {
|
||||
padding-top: env(safe-area-inset-top);
|
||||
}
|
||||
|
||||
.bottom-safe-nav {
|
||||
bottom: calc(env(safe-area-inset-bottom) + 3.75rem);
|
||||
}
|
||||
|
||||
/* Mobile navigation button styles - text/icon highlighting only */
|
||||
.mobile-nav-button,
|
||||
.mobile-nav-button:hover,
|
||||
.mobile-nav-button:active,
|
||||
.mobile-nav-button-active,
|
||||
.mobile-nav-button-active:hover,
|
||||
.mobile-nav-button-active:active {
|
||||
background-color: transparent !important;
|
||||
}
|
||||
|
||||
.mobile-nav-button-active,
|
||||
.mobile-nav-button-active:hover,
|
||||
.mobile-nav-button-active:active {
|
||||
color: hsl(var(--primary)) !important;
|
||||
}
|
||||
|
||||
pre.shiki {
|
||||
background-color: transparent !important;
|
||||
}
|
||||
|
||||
@@ -98,6 +98,8 @@ invalid json line
|
||||
it('should create history directory if it does not exist', async () => {
|
||||
// Mock historyDirExists to return false initially
|
||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false);
|
||||
// Mock setupAiHistoryDir
|
||||
vi.spyOn(dotAI, 'setupAiHistoryDir').mockResolvedValue();
|
||||
|
||||
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
|
||||
{ role: 'user', content: 'Hello' }
|
||||
@@ -105,8 +107,8 @@ invalid json line
|
||||
|
||||
await dotAI.setHistory('test-session', messages);
|
||||
|
||||
// Verify mkdir was called with recursive option
|
||||
expect(mockFS.mkdir).toHaveBeenCalledWith('/test-project/.git/ai/history', { recursive: true });
|
||||
// Verify setupAiHistoryDir was called
|
||||
expect(dotAI.setupAiHistoryDir).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should write messages as JSONL format', async () => {
|
||||
@@ -122,7 +124,7 @@ invalid json line
|
||||
|
||||
// Verify writeFile was called with correct content
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
'/test-project/.git/ai/history/test-session.jsonl',
|
||||
'/test-project/.ai/history/test-session.jsonl',
|
||||
'{"role":"user","content":"Hello"}\n{"role":"assistant","content":"Hi there!"}\n'
|
||||
);
|
||||
});
|
||||
@@ -135,7 +137,7 @@ invalid json line
|
||||
|
||||
// Verify writeFile was called with empty content
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
'/test-project/.git/ai/history/test-session.jsonl',
|
||||
'/test-project/.ai/history/test-session.jsonl',
|
||||
''
|
||||
);
|
||||
});
|
||||
|
||||
+86
-16
@@ -2,7 +2,7 @@ import { join } from "path-browserify";
|
||||
import type OpenAI from "openai";
|
||||
import type { JSRuntimeFS } from "./JSRuntime";
|
||||
|
||||
/** AI message history manager and .git/ai directory utilities */
|
||||
/** AI message history manager and .ai directory utilities */
|
||||
export class DotAI {
|
||||
readonly fs: JSRuntimeFS;
|
||||
readonly historyDir: string;
|
||||
@@ -11,7 +11,7 @@ export class DotAI {
|
||||
constructor(fs: JSRuntimeFS, workingDir: string = "/") {
|
||||
this.fs = fs;
|
||||
this.workingDir = workingDir;
|
||||
this.historyDir = join(workingDir, ".git", "ai", "history");
|
||||
this.historyDir = join(workingDir, ".ai", "history");
|
||||
}
|
||||
|
||||
/** Generate a unique session name based on the current date and time */
|
||||
@@ -31,6 +31,8 @@ export class DotAI {
|
||||
return filename;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/** Check if the history directory exists */
|
||||
async historyDirExists(): Promise<boolean> {
|
||||
try {
|
||||
@@ -49,9 +51,10 @@ export class DotAI {
|
||||
// Validate messages before saving
|
||||
this.validateMessages(messages);
|
||||
|
||||
// Always create the .ai directory and write session history
|
||||
// Create the history directory if it doesn't exist
|
||||
if (!(await this.historyDirExists())) {
|
||||
await this.fs.mkdir(this.historyDir, { recursive: true });
|
||||
await this.setupAiHistoryDir();
|
||||
}
|
||||
|
||||
const sessionFile = join(this.historyDir, sessionName + ".jsonl");
|
||||
@@ -119,11 +122,29 @@ export class DotAI {
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the model from .git/ai/MODEL file
|
||||
* Creates .ai/history directory and ensures .ai/ is gitignored at the project root.
|
||||
*/
|
||||
async setupAiHistoryDir(): Promise<void> {
|
||||
const aiHistoryDir = join(this.workingDir, ".ai", "history");
|
||||
|
||||
try {
|
||||
// Create .ai/history directory
|
||||
await this.fs.mkdir(aiHistoryDir, { recursive: true });
|
||||
|
||||
// Ensure .ai/ is gitignored at the project root
|
||||
await this.ensureAiGitignored();
|
||||
} catch (error) {
|
||||
// Log error but don't fail the main operation
|
||||
console.warn(`Failed to setup .ai/history directory: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the model from .ai/MODEL file
|
||||
*/
|
||||
async readAiModel(): Promise<string | undefined> {
|
||||
try {
|
||||
const modelPath = join(this.workingDir, ".git", "ai", "MODEL");
|
||||
const modelPath = join(this.workingDir, ".ai", "MODEL");
|
||||
const content = await this.fs.readFile(modelPath, "utf8");
|
||||
return content.trim();
|
||||
} catch {
|
||||
@@ -132,29 +153,32 @@ export class DotAI {
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the model to .git/ai/MODEL file
|
||||
* Write the model to .ai/MODEL file
|
||||
*/
|
||||
async writeAiModel(model: string): Promise<void> {
|
||||
const aiDir = join(this.workingDir, ".git", "ai");
|
||||
const aiDir = join(this.workingDir, ".ai");
|
||||
const modelPath = join(aiDir, "MODEL");
|
||||
|
||||
try {
|
||||
// Ensure .git/ai directory exists
|
||||
// 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) {
|
||||
console.warn(`Failed to write .git/ai/MODEL file: ${error}`);
|
||||
console.warn(`Failed to write .ai/MODEL file: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read parameters from .git/ai/PARAMETERS file
|
||||
* Read parameters from .ai/PARAMETERS file
|
||||
*/
|
||||
async readAiParameters(): Promise<Record<string, string>> {
|
||||
try {
|
||||
const parametersPath = join(this.workingDir, ".git", "ai", "PARAMETERS");
|
||||
const parametersPath = join(this.workingDir, ".ai", "PARAMETERS");
|
||||
const content = await this.fs.readFile(parametersPath, "utf8");
|
||||
|
||||
const parameters: Record<string, string> = {};
|
||||
@@ -179,16 +203,19 @@ export class DotAI {
|
||||
}
|
||||
|
||||
/**
|
||||
* Write parameters to .git/ai/PARAMETERS file
|
||||
* Write parameters to .ai/PARAMETERS file
|
||||
*/
|
||||
async writeAiParameters(parameters: Record<string, string>): Promise<void> {
|
||||
const aiDir = join(this.workingDir, ".git", "ai");
|
||||
const aiDir = join(this.workingDir, ".ai");
|
||||
const parametersPath = join(aiDir, "PARAMETERS");
|
||||
|
||||
try {
|
||||
// Ensure .git/ai directory exists
|
||||
// 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}`
|
||||
@@ -198,12 +225,12 @@ export class DotAI {
|
||||
// Write the parameters
|
||||
await this.fs.writeFile(parametersPath, content);
|
||||
} catch (error) {
|
||||
console.warn(`Failed to write .git/ai/PARAMETERS file: ${error}`);
|
||||
console.warn(`Failed to write .ai/PARAMETERS file: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a single parameter in .git/ai/PARAMETERS file
|
||||
* Update a single parameter in .ai/PARAMETERS file
|
||||
*/
|
||||
async updateAiParameter(key: string, value: string): Promise<void> {
|
||||
const currentParameters = await this.readAiParameters();
|
||||
@@ -274,4 +301,47 @@ export class DotAI {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that .ai/ is gitignored at the project root level.
|
||||
* Creates a .gitignore file if it doesn't exist, or adds the line if not already present.
|
||||
*/
|
||||
async ensureAiGitignored(): Promise<void> {
|
||||
const gitignorePath = join(this.workingDir, ".gitignore");
|
||||
const aiPattern = ".ai/";
|
||||
|
||||
try {
|
||||
// Try to read existing .gitignore
|
||||
let gitignoreContent = "";
|
||||
try {
|
||||
gitignoreContent = await this.fs.readFile(gitignorePath, "utf8");
|
||||
} catch {
|
||||
// .gitignore doesn't exist, will create it
|
||||
}
|
||||
|
||||
// Check if .ai/ is already gitignored
|
||||
const lines = gitignoreContent.split("\n").map((line) => line.trim());
|
||||
const hasAiPattern = lines.some((line) => {
|
||||
if (line.startsWith("#") || line === "") {
|
||||
return false;
|
||||
}
|
||||
// Check for various .ai patterns
|
||||
return line === ".ai" || line === ".ai/" || line === "/.ai" ||
|
||||
line === "/.ai/" ||
|
||||
line === ".ai/*" || line === "/.ai/*";
|
||||
});
|
||||
|
||||
if (!hasAiPattern) {
|
||||
// Add .ai/ to .gitignore
|
||||
const newContent = gitignoreContent.trim() === ""
|
||||
? aiPattern
|
||||
: gitignoreContent.trim() + "\n" + aiPattern;
|
||||
|
||||
await this.fs.writeFile(gitignorePath, newContent + "\n");
|
||||
}
|
||||
} catch (error) {
|
||||
// Log error but don't fail the main operation
|
||||
console.warn(`Failed to ensure .ai/ is gitignored: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ import { ProjectsManager } from './ProjectsManager';
|
||||
import { JSRuntimeFS } from './JSRuntime';
|
||||
import { Git } from './git';
|
||||
import type { NPool } from '@nostrify/nostrify';
|
||||
import type JSZip from 'jszip';
|
||||
|
||||
const createMockNostr = (): NPool => ({
|
||||
req: vi.fn(),
|
||||
@@ -439,50 +438,6 @@ describe('ProjectsManager', () => {
|
||||
vi.restoreAllMocks();
|
||||
}
|
||||
});
|
||||
|
||||
it('should prevent zip slip attacks during bulk file extraction', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
// Create a mock ZIP with malicious paths for bulk import
|
||||
const mockZip = {
|
||||
files: {
|
||||
'projects/project1/../../../etc/passwd': {
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3]))
|
||||
},
|
||||
'projects/project1/../../outside.txt': {
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6]))
|
||||
},
|
||||
'projects/project1/safe-file.txt': {
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9]))
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Spy on console.warn to check for security warnings
|
||||
const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
|
||||
try {
|
||||
// Extract files from the malicious ZIP for bulk import
|
||||
const files = await projectsManager.extractFilesFromZip(mockZip as unknown as JSZip, 'projects/project1');
|
||||
|
||||
// Should only contain safe files
|
||||
expect(Object.keys(files)).toEqual(['safe-file.txt']);
|
||||
expect(files['safe-file.txt']).toEqual(new Uint8Array([7, 8, 9]));
|
||||
|
||||
// Should have logged a security warning about skipped files
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Skipped 2 files due to resolving to paths outside of project directory:'),
|
||||
['projects/project1/../../../etc/passwd', 'projects/project1/../../outside.txt']
|
||||
);
|
||||
|
||||
} finally {
|
||||
// Restore mocks
|
||||
consoleSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('renameProject', () => {
|
||||
|
||||
+118
-401
@@ -46,259 +46,65 @@ export class ProjectsManager {
|
||||
async createProject(name: string, customId?: string): Promise<Project> {
|
||||
const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId, { depth: 1 });
|
||||
|
||||
// Delete README.md if it exists (template-specific cleanup)
|
||||
try {
|
||||
await this.fs.mkdir(this.dir + `/${project.id}/.ai/history`, { recursive: true });
|
||||
} catch {
|
||||
// Directory might already exist
|
||||
}
|
||||
|
||||
// Delete README.md if it exists
|
||||
try {
|
||||
await this.fs.unlink(`${project.path}/README.md`);
|
||||
} catch {
|
||||
// README.md might not exist, ignore error
|
||||
}
|
||||
|
||||
// Setup project infrastructure using unified method
|
||||
await this.setupProjectInfrastructure(project.path, {
|
||||
isOverwrite: false,
|
||||
commitMessage: 'New project created with Shakespeare',
|
||||
skipPersistentStorage: false,
|
||||
// Delete .git directory and reinitialize
|
||||
try {
|
||||
await this.deleteDirectory(`${project.path}/.git`);
|
||||
} catch {
|
||||
// .git directory might not exist, ignore error
|
||||
}
|
||||
|
||||
// Initialize new git repository
|
||||
await this.git.init({
|
||||
dir: project.path,
|
||||
defaultBranch: 'main',
|
||||
});
|
||||
|
||||
// Add all files to git
|
||||
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,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Make initial commit
|
||||
await this.git.commit({
|
||||
dir: project.path,
|
||||
message: 'New project created with Shakespeare',
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
|
||||
// Automatically request persistent storage after project creation
|
||||
try {
|
||||
await ensurePersistentStorage();
|
||||
} catch (error) {
|
||||
// Don't fail project creation if persistent storage request fails
|
||||
console.warn('Failed to request persistent storage after project creation:', error);
|
||||
}
|
||||
|
||||
return project;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unified method for setting up project infrastructure.
|
||||
* Handles git initialization/management, .ai directory creation, and persistent storage.
|
||||
*/
|
||||
private async setupProjectInfrastructure(
|
||||
projectPath: string,
|
||||
options: {
|
||||
isOverwrite?: boolean;
|
||||
commitMessage?: string;
|
||||
skipPersistentStorage?: boolean;
|
||||
} = {}
|
||||
): Promise<void> {
|
||||
const { isOverwrite = false, commitMessage = 'Project setup', skipPersistentStorage = false } = options;
|
||||
|
||||
// Initialize git repository if there's no .git directory
|
||||
try {
|
||||
await this.fs.stat(`${projectPath}/.git`);
|
||||
|
||||
// If git exists and we're overwriting, stage the new files
|
||||
if (isOverwrite) {
|
||||
const projectFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of projectFiles) {
|
||||
// Skip .git directory and .ai directory
|
||||
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
|
||||
try {
|
||||
await this.git.add({
|
||||
dir: projectPath,
|
||||
filepath: file,
|
||||
});
|
||||
} catch {
|
||||
// Ignore git add errors for files that might be gitignored
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Make commit for the overwrite
|
||||
await this.git.commit({
|
||||
dir: projectPath,
|
||||
message: commitMessage,
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// No .git directory found, initialize new repository
|
||||
await this.git.init({
|
||||
dir: projectPath,
|
||||
defaultBranch: 'main',
|
||||
});
|
||||
|
||||
// Add all files to git (excluding .ai directory)
|
||||
const projectFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of projectFiles) {
|
||||
// Skip .git directory and .ai directory
|
||||
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
|
||||
await this.git.add({
|
||||
dir: projectPath,
|
||||
filepath: file,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Make initial commit
|
||||
await this.git.commit({
|
||||
dir: projectPath,
|
||||
message: commitMessage,
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Create .ai/history directory
|
||||
try {
|
||||
await this.fs.mkdir(`${projectPath}/.ai/history`, { recursive: true });
|
||||
} catch {
|
||||
// Directory might already exist
|
||||
}
|
||||
|
||||
// Automatically request persistent storage (unless skipped)
|
||||
if (!skipPersistentStorage) {
|
||||
try {
|
||||
await ensurePersistentStorage();
|
||||
} catch (error) {
|
||||
// Don't fail project setup if persistent storage request fails
|
||||
console.warn('Failed to request persistent storage after project setup:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unified project import method that handles both ZIP files and direct file objects
|
||||
*/
|
||||
async importProject(
|
||||
source: File | { files: { [path: string]: Uint8Array } },
|
||||
options: {
|
||||
projectId?: string;
|
||||
overwrite?: boolean;
|
||||
projectName?: string;
|
||||
} = {}
|
||||
): Promise<Project> {
|
||||
const { projectId, overwrite = false, projectName } = options;
|
||||
|
||||
let finalProjectId: string;
|
||||
let finalProjectName: string;
|
||||
let files: { [path: string]: Uint8Array };
|
||||
|
||||
if (source instanceof File) {
|
||||
// Handle ZIP file import
|
||||
finalProjectId = projectId || await this.generateUniqueProjectId(source.name.replace(/\.zip$/i, ''));
|
||||
finalProjectName = projectName || this.formatProjectName(finalProjectId);
|
||||
|
||||
// Extract files from ZIP
|
||||
const arrayBuffer = await source.arrayBuffer();
|
||||
const zip = await JSZip.loadAsync(arrayBuffer);
|
||||
|
||||
files = {};
|
||||
const skippedFiles: string[] = [];
|
||||
|
||||
for (const [relativePath, zipEntry] of Object.entries(zip.files)) {
|
||||
if (zipEntry.dir) continue;
|
||||
|
||||
// Validate extraction path is within project directory
|
||||
const projectPath = `${this.dir}/${finalProjectId}`;
|
||||
const extractPath = this.join(projectPath, relativePath);
|
||||
|
||||
if (!this.isPathWithinProject(extractPath, projectPath)) {
|
||||
skippedFiles.push(relativePath);
|
||||
continue;
|
||||
}
|
||||
|
||||
const content = await zipEntry.async('uint8array');
|
||||
files[relativePath] = content;
|
||||
}
|
||||
|
||||
if (skippedFiles.length > 0) {
|
||||
console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside of project directory:`, skippedFiles);
|
||||
}
|
||||
} else {
|
||||
// Handle direct files import
|
||||
finalProjectId = projectId || await this.generateUniqueProjectId('imported-project');
|
||||
finalProjectName = projectName || this.formatProjectName(finalProjectId);
|
||||
files = source.files;
|
||||
}
|
||||
|
||||
const projectPath = `${this.dir}/${finalProjectId}`;
|
||||
const projectExists = await this.projectExists(finalProjectId);
|
||||
|
||||
// Check if project with this ID already exists when not overwriting
|
||||
if (projectExists && !overwrite) {
|
||||
throw new Error(`Project with ID "${finalProjectId}" already exists`);
|
||||
}
|
||||
|
||||
try {
|
||||
// Create project directory (or ensure it exists for overwrite)
|
||||
await this.fs.mkdir(projectPath, { recursive: true });
|
||||
|
||||
// If overwriting, delete existing files except .ai directory and .git directory
|
||||
if (projectExists && overwrite) {
|
||||
const existingFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of existingFiles) {
|
||||
// Preserve .ai directory and .git directory
|
||||
if (!file.startsWith('.ai/') && !file.startsWith('.git/')) {
|
||||
try {
|
||||
await this.fs.unlink(`${projectPath}/${file}`);
|
||||
} catch {
|
||||
// Ignore deletion errors
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extract all files with security validation
|
||||
const extractedFiles: string[] = [];
|
||||
const skippedFiles: string[] = [];
|
||||
|
||||
for (const [relativePath, content] of Object.entries(files)) {
|
||||
// Validate extraction path is within project directory
|
||||
const extractPath = this.join(projectPath, relativePath);
|
||||
|
||||
if (!this.isPathWithinProject(extractPath, projectPath)) {
|
||||
skippedFiles.push(relativePath);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Ensure parent directory exists
|
||||
const dirPath = extractPath.split('/').slice(0, -1).join('/');
|
||||
if (dirPath) {
|
||||
await this.fs.mkdir(dirPath, { recursive: true });
|
||||
}
|
||||
|
||||
// Write the file (this will overwrite existing files)
|
||||
await this.fs.writeFile(extractPath, content);
|
||||
extractedFiles.push(relativePath);
|
||||
}
|
||||
|
||||
if (skippedFiles.length > 0) {
|
||||
console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside of project directory:`, skippedFiles);
|
||||
}
|
||||
|
||||
// Get filesystem stats for timestamps
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
// Setup project infrastructure using unified method
|
||||
await this.setupProjectInfrastructure(projectPath, {
|
||||
isOverwrite: overwrite,
|
||||
commitMessage: source instanceof File
|
||||
? `Import project from ${source.name}`
|
||||
: `Import project from files`,
|
||||
skipPersistentStorage: false,
|
||||
});
|
||||
|
||||
return {
|
||||
id: finalProjectId,
|
||||
name: finalProjectName,
|
||||
path: projectPath,
|
||||
lastModified: timestamp,
|
||||
};
|
||||
} catch (error) {
|
||||
// Clean up on error (only if this was a new project creation)
|
||||
if (!projectExists) {
|
||||
try {
|
||||
await this.deleteDirectory(projectPath);
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Legacy method for backward compatibility
|
||||
async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise<Project> {
|
||||
// Generate a project ID based on the zip file name or use custom ID
|
||||
const baseName = zipFile.name.replace(/\.zip$/i, '');
|
||||
@@ -338,12 +144,12 @@ export class ProjectsManager {
|
||||
// Create project directory (or ensure it exists for overwrite)
|
||||
await this.fs.mkdir(projectPath, { recursive: true });
|
||||
|
||||
// If overwriting, delete existing files except .git directory
|
||||
// If overwriting, delete existing files except .ai directory and .git directory
|
||||
if (projectExists && overwrite) {
|
||||
const existingFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of existingFiles) {
|
||||
// Preserve .git directory
|
||||
if (!file.startsWith('.git/')) {
|
||||
// Preserve .ai directory and .git directory
|
||||
if (!file.startsWith('.ai/') && !file.startsWith('.git/')) {
|
||||
try {
|
||||
await this.fs.unlink(`${projectPath}/${file}`);
|
||||
} catch {
|
||||
@@ -398,12 +204,73 @@ export class ProjectsManager {
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
// Setup project infrastructure using unified method
|
||||
await this.setupProjectInfrastructure(projectPath, {
|
||||
isOverwrite: overwrite,
|
||||
commitMessage: `Import project from ${zipFile.name}`,
|
||||
skipPersistentStorage: false,
|
||||
});
|
||||
// Initialize git repository if there's no .git directory
|
||||
try {
|
||||
await this.fs.stat(`${projectPath}/.git`);
|
||||
|
||||
// If git exists and we're overwriting, stage the new files
|
||||
if (overwrite) {
|
||||
const projectFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of projectFiles) {
|
||||
// Skip .git directory and .ai directory
|
||||
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
|
||||
try {
|
||||
await this.git.add({
|
||||
dir: projectPath,
|
||||
filepath: file,
|
||||
});
|
||||
} catch {
|
||||
// Ignore git add errors for files that might be gitignored
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Make commit for the overwrite
|
||||
await this.git.commit({
|
||||
dir: projectPath,
|
||||
message: `Overwrite project from ${zipFile.name}`,
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// No .git directory found, initialize new repository
|
||||
await this.git.init({
|
||||
dir: projectPath,
|
||||
defaultBranch: 'main',
|
||||
});
|
||||
|
||||
// Add all files to git (excluding .ai directory)
|
||||
const projectFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of projectFiles) {
|
||||
// Skip .git directory and .ai directory
|
||||
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
|
||||
await this.git.add({
|
||||
dir: projectPath,
|
||||
filepath: file,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Make initial commit
|
||||
await this.git.commit({
|
||||
dir: projectPath,
|
||||
message: `Import project from ${zipFile.name}`,
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Create .ai/history directory
|
||||
try {
|
||||
await this.fs.mkdir(`${projectPath}/.ai/history`, { recursive: true });
|
||||
} catch {
|
||||
// Directory might already exist
|
||||
}
|
||||
|
||||
return {
|
||||
id,
|
||||
@@ -424,106 +291,6 @@ export class ProjectsManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Import project directly from files object (bypasses ZIP creation)
|
||||
* Used by bulk import to avoid unnecessary ZIP repackaging
|
||||
*/
|
||||
async importProjectFromFiles(
|
||||
projectId: string,
|
||||
files: { [path: string]: Uint8Array },
|
||||
overwrite = false,
|
||||
projectName?: string
|
||||
): Promise<Project> {
|
||||
const projectPath = `${this.dir}/${projectId}`;
|
||||
const projectExists = await this.projectExists(projectId);
|
||||
|
||||
// Check if project with this ID already exists when not overwriting
|
||||
if (projectExists && !overwrite) {
|
||||
throw new Error(`Project with ID "${projectId}" already exists`);
|
||||
}
|
||||
|
||||
// Determine project name
|
||||
const finalProjectName = projectName || this.formatProjectName(projectId);
|
||||
|
||||
try {
|
||||
// Create project directory (or ensure it exists for overwrite)
|
||||
await this.fs.mkdir(projectPath, { recursive: true });
|
||||
|
||||
// If overwriting, delete existing files except .ai directory and .git directory
|
||||
if (projectExists && overwrite) {
|
||||
const existingFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of existingFiles) {
|
||||
// Preserve .ai directory and .git directory
|
||||
if (!file.startsWith('.ai/') && !file.startsWith('.git/')) {
|
||||
try {
|
||||
await this.fs.unlink(`${projectPath}/${file}`);
|
||||
} catch {
|
||||
// Ignore deletion errors
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extract all files with security validation
|
||||
const extractedFiles: string[] = [];
|
||||
const skippedFiles: string[] = [];
|
||||
|
||||
for (const [relativePath, content] of Object.entries(files)) {
|
||||
// Validate the extraction path is within the project directory
|
||||
const extractPath = this.join(projectPath, relativePath);
|
||||
|
||||
if (!this.isPathWithinProject(extractPath, projectPath)) {
|
||||
skippedFiles.push(relativePath);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Ensure parent directory exists
|
||||
const dirPath = extractPath.split('/').slice(0, -1).join('/');
|
||||
if (dirPath) {
|
||||
await this.fs.mkdir(dirPath, { recursive: true });
|
||||
}
|
||||
|
||||
// Write the file (this will overwrite existing files)
|
||||
await this.fs.writeFile(extractPath, content);
|
||||
extractedFiles.push(relativePath);
|
||||
}
|
||||
|
||||
if (skippedFiles.length > 0) {
|
||||
console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside the project directory:`, skippedFiles);
|
||||
}
|
||||
|
||||
// Get filesystem stats for timestamps
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
// Setup project infrastructure using unified method
|
||||
await this.setupProjectInfrastructure(projectPath, {
|
||||
isOverwrite: overwrite,
|
||||
commitMessage: `Import project from files`,
|
||||
skipPersistentStorage: false,
|
||||
});
|
||||
|
||||
return {
|
||||
id: projectId,
|
||||
name: finalProjectName,
|
||||
path: projectPath,
|
||||
lastModified: timestamp,
|
||||
};
|
||||
} catch (error) {
|
||||
// Clean up on error (only if this was a new project creation)
|
||||
if (!projectExists) {
|
||||
try {
|
||||
await this.deleteDirectory(projectPath);
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise<Project> {
|
||||
const id = customId || await this.generateUniqueProjectId(name);
|
||||
|
||||
@@ -892,54 +659,4 @@ export class ProjectsManager {
|
||||
|
||||
return '/' + normalized.join('/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract files from a ZIP archive for a specific project path
|
||||
* Used by bulk import to extract files from a specific directory within a ZIP
|
||||
*/
|
||||
async extractFilesFromZip(zip: JSZip, projectPath: string): Promise<{ [path: string]: Uint8Array }> {
|
||||
const files: { [path: string]: Uint8Array } = {};
|
||||
const skippedFiles: string[] = [];
|
||||
const securitySkippedFiles: string[] = [];
|
||||
|
||||
for (const [relativePath, zipEntry] of Object.entries(zip.files)) {
|
||||
if (zipEntry.dir) continue;
|
||||
|
||||
// Check if this file is within the specified project path
|
||||
if (!relativePath.startsWith(projectPath + '/')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get the relative path within the project
|
||||
const fileRelativePath = relativePath.substring(projectPath.length + 1);
|
||||
|
||||
// Skip empty paths (shouldn't happen due to the dir check above, but just in case)
|
||||
if (!fileRelativePath) continue;
|
||||
|
||||
// Validate extraction path is safe (zip slip protection)
|
||||
// Check for directory traversal attempts in the original path
|
||||
if (fileRelativePath.includes('../') || fileRelativePath.includes('..\\') || fileRelativePath.startsWith('/') || fileRelativePath.startsWith('\\')) {
|
||||
securitySkippedFiles.push(relativePath);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const content = await zipEntry.async('uint8array');
|
||||
files[fileRelativePath] = content;
|
||||
} catch (error) {
|
||||
console.warn(`Failed to extract file ${relativePath}:`, error);
|
||||
skippedFiles.push(relativePath);
|
||||
}
|
||||
}
|
||||
|
||||
if (securitySkippedFiles.length > 0) {
|
||||
console.warn(`Skipped ${securitySkippedFiles.length} files due to resolving to paths outside of project directory:`, securitySkippedFiles);
|
||||
}
|
||||
|
||||
if (skippedFiles.length > 0) {
|
||||
console.warn(`Skipped ${skippedFiles.length} files due to extraction errors:`, skippedFiles);
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
}
|
||||
@@ -250,6 +250,7 @@ export class SessionManager {
|
||||
model,
|
||||
messages,
|
||||
tools: session.tools && Object.keys(session.tools).length > 0 ? Object.values(session.tools) : undefined,
|
||||
tool_choice: session.tools && Object.keys(session.tools).length > 0 ? 'auto' : undefined,
|
||||
stream: true,
|
||||
stream_options: {
|
||||
include_usage: true,
|
||||
@@ -300,9 +301,9 @@ export class SessionManager {
|
||||
}
|
||||
|
||||
if (delta?.tool_calls) {
|
||||
for (let i = 0; i < delta.tool_calls.length; i++) {
|
||||
const toolCallDelta = delta.tool_calls[i];
|
||||
const index = toolCallDelta.index ?? i; // Fix for Gemini models
|
||||
for (const toolCallDelta of delta.tool_calls) {
|
||||
const index = toolCallDelta.index;
|
||||
if (index === undefined) continue;
|
||||
|
||||
accumulatedToolCalls[index] ??= {
|
||||
id: '',
|
||||
|
||||
@@ -13,11 +13,11 @@ export function createAIClient(provider: AIProvider, user?: NUser): OpenAI {
|
||||
baseURL: provider.baseURL,
|
||||
apiKey: provider.apiKey ?? '',
|
||||
dangerouslyAllowBrowser: true,
|
||||
defaultHeaders: provider.id === 'openrouter' ? {
|
||||
defaultHeaders: {
|
||||
// https://openrouter.ai/docs/app-attribution
|
||||
'HTTP-Referer': 'https://shakespeare.diy',
|
||||
'X-Title': 'Shakespeare',
|
||||
} : {},
|
||||
},
|
||||
};
|
||||
|
||||
let openai: OpenAI;
|
||||
|
||||
@@ -5,7 +5,6 @@ interface PackageLock {
|
||||
[key: string]: {
|
||||
name?: string;
|
||||
version: string;
|
||||
peerDependencies?: { [key: string]: string };
|
||||
} | undefined;
|
||||
};
|
||||
}
|
||||
@@ -62,14 +61,6 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
||||
}
|
||||
});
|
||||
|
||||
// Legacy (Internet Explorer) "behavior" syntax
|
||||
build.onResolve({ filter: /^#default#/, namespace: "esm" }, (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
external: true,
|
||||
};
|
||||
});
|
||||
|
||||
// Handle bare imports like "react"
|
||||
build.onResolve({ filter: /^[^./].*/ }, (args) => {
|
||||
const packageName = args.path.startsWith("@")
|
||||
@@ -78,13 +69,8 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
||||
|
||||
// Handle transitive dependency versions
|
||||
const keys: string[] = [];
|
||||
let importerPackage: string | undefined;
|
||||
try {
|
||||
const { pathname } = new URL(args.importer);
|
||||
if (/\.css$/.test(pathname)) {
|
||||
return; // CSS imports don't have external dependencies
|
||||
}
|
||||
importerPackage = extractPackageName(args.importer);
|
||||
const importerPackage = extractPackageName(args.importer);
|
||||
keys.push(
|
||||
`node_modules/${importerPackage}/node_modules/${packageName}`,
|
||||
);
|
||||
@@ -103,13 +89,12 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
||||
.find((info) => info);
|
||||
|
||||
const packagePath = args.path.slice(packageName.length);
|
||||
const version = packageInfo?.version
|
||||
|| packageLock.packages[`node_modules/${importerPackage}`]?.peerDependencies?.[packageName];
|
||||
const version = packageInfo?.version;
|
||||
|
||||
const name = packageInfo?.name ?? packageName;
|
||||
const specifier = version
|
||||
? `${name}@${version}${packagePath}`
|
||||
: `${name}${packagePath}`;
|
||||
if (!version) return;
|
||||
|
||||
const name = packageInfo.name ?? packageName;
|
||||
const specifier = `${name}@${version}${packagePath}`;
|
||||
|
||||
const url = new URL(`https://esm.sh/*${specifier}`);
|
||||
|
||||
@@ -146,14 +131,6 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
||||
}
|
||||
}
|
||||
|
||||
// Skip static assets
|
||||
if (/\.(woff2?|ttf|otf|eot)$/.test(fullURL.pathname)) {
|
||||
return {
|
||||
path: fullURL.toString(),
|
||||
external: true,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
path: fullURL.toString(),
|
||||
namespace: "esm",
|
||||
|
||||
+10
-31
@@ -1,4 +1,4 @@
|
||||
import { join, dirname, extname } from "path-browserify";
|
||||
import path from "path-browserify";
|
||||
|
||||
import type { Loader, Plugin } from "esbuild-wasm";
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
@@ -8,37 +8,27 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin {
|
||||
name: "fs",
|
||||
|
||||
setup(build) {
|
||||
build.onResolve({ filter: /^data:/ }, (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
external: true,
|
||||
};
|
||||
});
|
||||
|
||||
build.onResolve({ filter: /.*/ }, async (args) => {
|
||||
let resolved: string;
|
||||
|
||||
if (args.path.startsWith("@/")) {
|
||||
resolved = join(cwd, args.path.slice(2));
|
||||
resolved = path.join(cwd, args.path.slice(2));
|
||||
} else if (args.kind === "entry-point") {
|
||||
resolved = join(cwd, args.path);
|
||||
resolved = path.join(cwd, args.path);
|
||||
} else if (args.importer) {
|
||||
resolved = join(dirname(args.importer), args.path);
|
||||
resolved = path.join(path.dirname(args.importer), args.path);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
// Vite query parameters https://vite.dev/guide/assets
|
||||
const [cleaned, query] = resolved.split("?");
|
||||
|
||||
try {
|
||||
resolved = await tryFileVariants(fs, cleaned);
|
||||
resolved = await tryFileVariants(fs, resolved);
|
||||
} catch {
|
||||
return; // Let other plugins handle this
|
||||
}
|
||||
|
||||
return {
|
||||
path: resolved + (typeof query === "string" ? "?" + query : ""),
|
||||
path: resolved,
|
||||
namespace: "fs",
|
||||
};
|
||||
});
|
||||
@@ -46,25 +36,14 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin {
|
||||
build.onLoad(
|
||||
{ filter: /.*/, namespace: "fs" },
|
||||
async (args) => {
|
||||
const [path, query] = args.path.split("?");
|
||||
const params = new URLSearchParams(query);
|
||||
const ext = path.extname(args.path).slice(1);
|
||||
|
||||
// https://vite.dev/guide/assets.html#importing-asset-as-string
|
||||
if (params.has("raw")) {
|
||||
return {
|
||||
contents: await fs.readFile(path, "utf8"),
|
||||
loader: "text",
|
||||
};
|
||||
}
|
||||
|
||||
const ext = extname(path).slice(1);
|
||||
|
||||
if (!["ts", "tsx", "js", "jsx", "css", "json"].includes(ext)) {
|
||||
if (!["ts", "tsx", "js", "jsx", "css"].includes(ext)) {
|
||||
return;
|
||||
}
|
||||
|
||||
return {
|
||||
contents: await fs.readFile(path, "utf8"),
|
||||
contents: await fs.readFile(args.path, "utf8"),
|
||||
loader: ext as Loader,
|
||||
};
|
||||
},
|
||||
@@ -88,7 +67,7 @@ async function tryFileVariants(
|
||||
// If it's a directory, try index files
|
||||
if (stat.isDirectory()) {
|
||||
for (const ext of extensions) {
|
||||
const indexFile = join(basePath, "index" + ext);
|
||||
const indexFile = path.join(basePath, "index" + ext);
|
||||
const indexStat = await statSafe(fs, indexFile);
|
||||
if (indexStat.isFile()) {
|
||||
return indexFile;
|
||||
|
||||
+6
-11
@@ -1,7 +1,6 @@
|
||||
import { getEsbuild } from "@/lib/esbuild";
|
||||
import { copyFiles } from "@/lib/copyFiles";
|
||||
|
||||
import { shakespearePlugin } from "./shakespearePlugin";
|
||||
import { esmPlugin } from "./esmPlugin";
|
||||
import { fsPlugin } from "./fsPlugin";
|
||||
|
||||
@@ -50,7 +49,6 @@ async function bundle(
|
||||
outdir: "/",
|
||||
jsx: "automatic",
|
||||
plugins: [
|
||||
shakespearePlugin(), // Takes precedence over esmPlugin
|
||||
fsPlugin(fs, `${projectPath}/src`),
|
||||
esmPlugin(JSON.parse(packageLockText), target),
|
||||
],
|
||||
@@ -73,7 +71,7 @@ async function bundle(
|
||||
}
|
||||
|
||||
// Update index.html with proper script and link tags
|
||||
updateIndexHtml(doc, dist);
|
||||
updateIndexHtml(doc);
|
||||
|
||||
const updatedHtml = "<!DOCTYPE html>\n" + doc.documentElement.outerHTML;
|
||||
dist["index.html"] = new TextEncoder().encode(updatedHtml);
|
||||
@@ -156,7 +154,7 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
|
||||
};
|
||||
}
|
||||
|
||||
function updateIndexHtml(doc: Document, dist: Record<string, Uint8Array>): void {
|
||||
function updateIndexHtml(doc: Document): void {
|
||||
const entrypoint = doc.querySelector('script[src="/src/main.tsx"]');
|
||||
|
||||
if (!entrypoint) {
|
||||
@@ -165,11 +163,8 @@ function updateIndexHtml(doc: Document, dist: Record<string, Uint8Array>): void
|
||||
|
||||
entrypoint.setAttribute("src", "/main.js");
|
||||
|
||||
const css = dist["main.css"];
|
||||
if (css) {
|
||||
const style = doc.createElement("style");
|
||||
style.setAttribute("type", "text/tailwindcss");
|
||||
style.textContent = new TextDecoder().decode(css);
|
||||
doc.head.appendChild(style);
|
||||
}
|
||||
const style = doc.createElement("link");
|
||||
style.setAttribute("rel", "stylesheet");
|
||||
style.setAttribute("href", "/main.css");
|
||||
doc.head.appendChild(style);
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
import type { Plugin } from "esbuild-wasm";
|
||||
|
||||
/**
|
||||
* Shakespeare plugin for dependency polyfills and workarounds.
|
||||
* This plugin handles specific dependencies that need custom implementations
|
||||
* or dummy APIs to work correctly in the browser environment.
|
||||
*/
|
||||
export function shakespearePlugin(): Plugin {
|
||||
return {
|
||||
name: "shakespeare",
|
||||
|
||||
setup(build) {
|
||||
// Handle "sonner" imports with a dummy API
|
||||
build.onResolve({ filter: /^sonner$/ }, (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
namespace: "shakespeare-sonner",
|
||||
};
|
||||
});
|
||||
|
||||
// Provide dummy sonner implementation
|
||||
build.onLoad({ filter: /.*/, namespace: "shakespeare-sonner" }, () => {
|
||||
return {
|
||||
contents: `
|
||||
// Dummy implementation of sonner toast library
|
||||
|
||||
// Toast function that does nothing
|
||||
const toast = (message, options) => {
|
||||
console.log('[Shakespeare Sonner Mock]:', message, options);
|
||||
return { id: Math.random().toString(36) };
|
||||
};
|
||||
|
||||
// Add common toast methods
|
||||
toast.success = (message, options) => {
|
||||
console.log('[Shakespeare Sonner Mock] Success:', message, options);
|
||||
return { id: Math.random().toString(36) };
|
||||
};
|
||||
|
||||
toast.error = (message, options) => {
|
||||
console.log('[Shakespeare Sonner Mock] Error:', message, options);
|
||||
return { id: Math.random().toString(36) };
|
||||
};
|
||||
|
||||
toast.info = (message, options) => {
|
||||
console.log('[Shakespeare Sonner Mock] Info:', message, options);
|
||||
return { id: Math.random().toString(36) };
|
||||
};
|
||||
|
||||
toast.warning = (message, options) => {
|
||||
console.log('[Shakespeare Sonner Mock] Warning:', message, options);
|
||||
return { id: Math.random().toString(36) };
|
||||
};
|
||||
|
||||
toast.loading = (message, options) => {
|
||||
console.log('[Shakespeare Sonner Mock] Loading:', message, options);
|
||||
return { id: Math.random().toString(36) };
|
||||
};
|
||||
|
||||
toast.promise = (promise, options) => {
|
||||
console.log('[Shakespeare Sonner Mock] Promise:', promise, options);
|
||||
return promise;
|
||||
};
|
||||
|
||||
toast.dismiss = (id) => {
|
||||
console.log('[Shakespeare Sonner Mock] Dismiss:', id);
|
||||
};
|
||||
|
||||
// Toaster component (dummy React component)
|
||||
const Toaster = (props) => {
|
||||
console.log('[Shakespeare Sonner Mock] Toaster component rendered:', props);
|
||||
return null;
|
||||
};
|
||||
|
||||
// Export both named and default exports to match sonner API
|
||||
export { toast, Toaster };
|
||||
export default toast;
|
||||
`,
|
||||
loader: "js",
|
||||
};
|
||||
});
|
||||
|
||||
// Handle "next-themes" imports with a dummy API
|
||||
build.onResolve({ filter: /^next-themes$/ }, (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
namespace: "shakespeare-next-themes",
|
||||
};
|
||||
});
|
||||
|
||||
// Provide dummy next-themes implementation
|
||||
build.onLoad({ filter: /.*/, namespace: "shakespeare-next-themes" }, () => {
|
||||
return {
|
||||
contents: `
|
||||
// Dummy implementation of next-themes
|
||||
|
||||
// useTheme hook that returns system theme
|
||||
const useTheme = () => {
|
||||
return { theme: "system" };
|
||||
};
|
||||
|
||||
// ThemeProvider component (dummy React component)
|
||||
const ThemeProvider = ({ children, ...props }) => {
|
||||
console.log('[Shakespeare next-themes Mock] ThemeProvider rendered:', props);
|
||||
return children;
|
||||
};
|
||||
|
||||
// Export both named and default exports to match next-themes API
|
||||
export { useTheme, ThemeProvider };
|
||||
`,
|
||||
loader: "js",
|
||||
};
|
||||
});
|
||||
|
||||
// Handle "virtual:pwa-register/react" imports with a dummy API
|
||||
build.onResolve({ filter: /^virtual:pwa-register\/react$/ }, (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
namespace: "shakespeare-pwa-register",
|
||||
};
|
||||
});
|
||||
|
||||
// Provide dummy PWA register implementation
|
||||
build.onLoad({ filter: /.*/, namespace: "shakespeare-pwa-register" }, () => {
|
||||
return {
|
||||
contents: `
|
||||
// Dummy implementation of virtual:pwa-register/react
|
||||
|
||||
// useRegisterSW hook that returns dummy functions
|
||||
const useRegisterSW = (options = {}) => {
|
||||
console.log('[Shakespeare PWA Mock] useRegisterSW called:', options);
|
||||
|
||||
return {
|
||||
needRefresh: [false, () => {}],
|
||||
offlineReady: [false, () => {}],
|
||||
updateServiceWorker: (reloadPage) => {
|
||||
console.log('[Shakespeare PWA Mock] updateServiceWorker called:', reloadPage);
|
||||
if (reloadPage) {
|
||||
window.location.reload();
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
// Export the hook
|
||||
export { useRegisterSW };
|
||||
`,
|
||||
loader: "js",
|
||||
};
|
||||
});
|
||||
|
||||
// Add more dependency polyfills here as needed
|
||||
// Example structure for future dependencies:
|
||||
// build.onResolve({ filter: /^some-other-package$/ }, (args) => {
|
||||
// return {
|
||||
// path: args.path,
|
||||
// namespace: "shakespeare-other-package",
|
||||
// };
|
||||
// });
|
||||
//
|
||||
// build.onLoad({ filter: /.*/, namespace: "shakespeare-other-package" }, () => {
|
||||
// return {
|
||||
// contents: `// Custom implementation for some-other-package`,
|
||||
// loader: "js",
|
||||
// };
|
||||
// });
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,275 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { GitAddCommand } from './add';
|
||||
import type { JSRuntimeFS } from '../../JSRuntime';
|
||||
import type { Git } from '../../git';
|
||||
|
||||
// Mock filesystem
|
||||
const createMockFS = (): JSRuntimeFS => ({
|
||||
readFile: vi.fn().mockResolvedValue('mock content'),
|
||||
writeFile: vi.fn().mockResolvedValue(undefined),
|
||||
readdir: vi.fn().mockResolvedValue([]),
|
||||
mkdir: vi.fn().mockResolvedValue(undefined),
|
||||
stat: vi.fn().mockImplementation((path: string) => {
|
||||
if (path.endsWith('/.git')) {
|
||||
return Promise.resolve({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
size: 0,
|
||||
mtimeMs: Date.now(),
|
||||
});
|
||||
}
|
||||
return Promise.resolve({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
size: 100,
|
||||
mtimeMs: Date.now(),
|
||||
});
|
||||
}),
|
||||
lstat: vi.fn().mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
size: 100,
|
||||
mtimeMs: Date.now(),
|
||||
}),
|
||||
unlink: vi.fn().mockResolvedValue(undefined),
|
||||
rmdir: vi.fn().mockResolvedValue(undefined),
|
||||
rename: vi.fn().mockResolvedValue(undefined),
|
||||
readlink: vi.fn().mockResolvedValue('mock link'),
|
||||
symlink: vi.fn().mockResolvedValue(undefined),
|
||||
});
|
||||
|
||||
// Mock Git
|
||||
const createMockGit = (): Git => ({
|
||||
statusMatrix: vi.fn(),
|
||||
add: vi.fn(),
|
||||
remove: vi.fn(),
|
||||
} as unknown as Git);
|
||||
|
||||
describe('GitAddCommand', () => {
|
||||
let addCommand: GitAddCommand;
|
||||
let mockFS: JSRuntimeFS;
|
||||
let mockGit: Git;
|
||||
const testCwd = '/test';
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = createMockFS();
|
||||
mockGit = createMockGit();
|
||||
addCommand = new GitAddCommand({
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: testCwd,
|
||||
});
|
||||
});
|
||||
|
||||
it('should have correct command properties', () => {
|
||||
expect(addCommand.name).toBe('add');
|
||||
expect(addCommand.description).toBe('Add file contents to the index');
|
||||
expect(addCommand.usage).toBe('git add [--all | -A] [--] [<pathspec>...]');
|
||||
});
|
||||
|
||||
it('should return error when not in a git repository', async () => {
|
||||
// Mock stat to throw error for .git directory
|
||||
vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT'));
|
||||
|
||||
const result = await addCommand.execute(['file.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: not a git repository');
|
||||
});
|
||||
|
||||
it('should return error when no files specified', async () => {
|
||||
const result = await addCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('Nothing specified, nothing added');
|
||||
expect(result.stderr).toContain('Maybe you wanted to say \'git add .\'?');
|
||||
});
|
||||
|
||||
it('should add all modified files with --all flag', async () => {
|
||||
// Mock status matrix with modified and untracked files
|
||||
// [filepath, headStatus, workdirStatus, stageStatus]
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['modified.txt', 1, 2, 1], // Modified file (not staged)
|
||||
['untracked.txt', 0, 2, 0], // Untracked file
|
||||
['unchanged.txt', 1, 1, 1], // Unchanged file
|
||||
['staged.txt', 1, 2, 2], // Already staged file
|
||||
]);
|
||||
|
||||
const result = await addCommand.execute(['--all']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe(''); // Git add is silent on success
|
||||
|
||||
// Should add modified and untracked files, but not unchanged or already staged
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'modified.txt',
|
||||
});
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'untracked.txt',
|
||||
});
|
||||
expect(mockGit.add).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('should handle deleted files with --all flag', async () => {
|
||||
// Mock status matrix with deleted file
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['deleted.txt', 1, 0, 1], // Deleted file (not staged)
|
||||
]);
|
||||
|
||||
const result = await addCommand.execute(['--all']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
|
||||
// Should remove the deleted file
|
||||
expect(mockGit.remove).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'deleted.txt',
|
||||
});
|
||||
expect(mockGit.remove).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should add specific file', async () => {
|
||||
const result = await addCommand.execute(['file.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'file.txt',
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle git add . (current directory)', async () => {
|
||||
// Mock status matrix with various files
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['file1.txt', 1, 2, 1], // Modified file
|
||||
['file2.txt', 0, 2, 0], // Untracked file
|
||||
['deleted.txt', 1, 0, 1], // Deleted file
|
||||
]);
|
||||
|
||||
const result = await addCommand.execute(['.']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
|
||||
// Should add modified and untracked files
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'file1.txt',
|
||||
});
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'file2.txt',
|
||||
});
|
||||
|
||||
// Should remove deleted file
|
||||
expect(mockGit.remove).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'deleted.txt',
|
||||
});
|
||||
});
|
||||
|
||||
it('should reject absolute paths', async () => {
|
||||
const result = await addCommand.execute(['/absolute/path/file.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('absolute paths are not supported');
|
||||
});
|
||||
|
||||
it('should handle non-existent files', async () => {
|
||||
// Mock stat to throw error for non-existent file
|
||||
vi.mocked(mockFS.stat).mockImplementation((path: string) => {
|
||||
if (path.endsWith('/.git')) {
|
||||
return Promise.resolve({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
size: 0,
|
||||
mtimeMs: Date.now(),
|
||||
});
|
||||
}
|
||||
if (path.includes('nonexistent')) {
|
||||
throw new Error('ENOENT');
|
||||
}
|
||||
return Promise.resolve({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
size: 100,
|
||||
mtimeMs: Date.now(),
|
||||
});
|
||||
});
|
||||
|
||||
// Mock git.remove to also throw error (file doesn't exist in git either)
|
||||
vi.mocked(mockGit.remove).mockRejectedValueOnce(new Error('File not found'));
|
||||
|
||||
const result = await addCommand.execute(['nonexistent.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('pathspec \'nonexistent.txt\' did not match any files');
|
||||
});
|
||||
|
||||
it('should handle -A flag (same as --all)', async () => {
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['modified.txt', 1, 2, 1], // Modified file
|
||||
]);
|
||||
|
||||
const result = await addCommand.execute(['-A']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'modified.txt',
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle mixed options and paths', async () => {
|
||||
// Mock status matrix for --all to work
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['modified.txt', 1, 2, 1], // Modified file
|
||||
]);
|
||||
|
||||
const result = await addCommand.execute(['--all', 'specific.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
|
||||
// When --all is specified, it should ignore specific paths and add all files
|
||||
expect(mockGit.statusMatrix).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle double dash separator', async () => {
|
||||
const result = await addCommand.execute(['--', 'file.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'file.txt',
|
||||
});
|
||||
});
|
||||
|
||||
it('should continue with other files if one fails', async () => {
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['good.txt', 1, 2, 1], // This should succeed
|
||||
['bad.txt', 1, 2, 1], // This will fail
|
||||
]);
|
||||
|
||||
// Mock git.add to fail for bad.txt but succeed for good.txt
|
||||
vi.mocked(mockGit.add).mockImplementation(({ filepath }) => {
|
||||
if (filepath === 'bad.txt') {
|
||||
throw new Error('Permission denied');
|
||||
}
|
||||
return Promise.resolve();
|
||||
});
|
||||
|
||||
const result = await addCommand.execute(['--all']);
|
||||
|
||||
expect(result.exitCode).toBe(0); // Should still succeed overall
|
||||
expect(mockGit.add).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
+39
-20
@@ -77,22 +77,27 @@ export class GitAddCommand implements GitSubcommand {
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
||||
let addedCount = 0;
|
||||
let removedCount = 0;
|
||||
|
||||
for (const [filepath, headStatus, workdirStatus] of statusMatrix) {
|
||||
try {
|
||||
if (workdirStatus === 0 && headStatus === 1) {
|
||||
// File was deleted in working directory
|
||||
// File was deleted
|
||||
await this.git.remove({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
} else if (workdirStatus === 2 && stageStatus !== 2) {
|
||||
// File exists and has changes that aren't staged yet
|
||||
removedCount++;
|
||||
} else if (workdirStatus === 1) {
|
||||
// File exists (new or modified)
|
||||
await this.git.add({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
addedCount++;
|
||||
}
|
||||
} catch {
|
||||
// Continue with other files if one fails
|
||||
@@ -100,8 +105,19 @@ export class GitAddCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
// Git add is typically silent on success, like real git
|
||||
return createSuccessResult('');
|
||||
const messages: string[] = [];
|
||||
if (addedCount > 0) {
|
||||
messages.push(`Added ${addedCount} file${addedCount !== 1 ? 's' : ''}`);
|
||||
}
|
||||
if (removedCount > 0) {
|
||||
messages.push(`Removed ${removedCount} file${removedCount !== 1 ? 's' : ''}`);
|
||||
}
|
||||
|
||||
if (messages.length === 0) {
|
||||
return createSuccessResult('');
|
||||
}
|
||||
|
||||
return createSuccessResult(messages.join(', ') + '\n');
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`Failed to add all files: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
@@ -117,24 +133,24 @@ export class GitAddCommand implements GitSubcommand {
|
||||
if (path === '.') {
|
||||
// Add current directory (all files in it)
|
||||
const statusMatrix = await this.git.statusMatrix({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
||||
for (const [filepath, headStatus, workdirStatus] of statusMatrix) {
|
||||
try {
|
||||
if (workdirStatus === 0 && headStatus === 1) {
|
||||
// File was deleted in working directory
|
||||
// File was deleted
|
||||
await this.git.remove({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
addedFiles.push(filepath);
|
||||
} else if (workdirStatus === 2 && stageStatus !== 2) {
|
||||
// File exists and has changes that aren't staged yet
|
||||
} else if (workdirStatus === 1) {
|
||||
// File exists
|
||||
await this.git.add({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
@@ -163,7 +179,7 @@ export class GitAddCommand implements GitSubcommand {
|
||||
} else {
|
||||
// Add single file
|
||||
await this.git.add({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath: path,
|
||||
});
|
||||
@@ -173,7 +189,7 @@ export class GitAddCommand implements GitSubcommand {
|
||||
// Check if it's a deleted file
|
||||
try {
|
||||
await this.git.remove({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath: path,
|
||||
});
|
||||
@@ -192,8 +208,11 @@ export class GitAddCommand implements GitSubcommand {
|
||||
return createErrorResult(errors.join('\n'));
|
||||
}
|
||||
|
||||
// Git add is typically silent on success, like real git
|
||||
return createSuccessResult('');
|
||||
if (addedFiles.length === 0) {
|
||||
return createSuccessResult('');
|
||||
}
|
||||
|
||||
return createSuccessResult(`Added ${addedFiles.length} file${addedFiles.length !== 1 ? 's' : ''}\n`);
|
||||
}
|
||||
|
||||
private async addDirectory(dirPath: string, addedFiles: string[]): Promise<void> {
|
||||
@@ -212,7 +231,7 @@ export class GitAddCommand implements GitSubcommand {
|
||||
} else {
|
||||
try {
|
||||
await this.git.add({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath: entryPath,
|
||||
});
|
||||
|
||||
@@ -1,218 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { GitStatusCommand } from './status';
|
||||
import type { JSRuntimeFS } from '../../JSRuntime';
|
||||
import type { Git } from '../../git';
|
||||
|
||||
// Mock filesystem
|
||||
const createMockFS = (): JSRuntimeFS => ({
|
||||
readFile: vi.fn().mockResolvedValue('mock content'),
|
||||
writeFile: vi.fn().mockResolvedValue(undefined),
|
||||
readdir: vi.fn().mockResolvedValue([]),
|
||||
mkdir: vi.fn().mockResolvedValue(undefined),
|
||||
stat: vi.fn().mockImplementation((path: string) => {
|
||||
if (path.endsWith('/.git')) {
|
||||
return Promise.resolve({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
size: 0,
|
||||
mtimeMs: Date.now(),
|
||||
});
|
||||
}
|
||||
throw new Error('ENOENT: no such file or directory');
|
||||
}),
|
||||
lstat: vi.fn().mockResolvedValue({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
size: 0,
|
||||
mtimeMs: Date.now(),
|
||||
}),
|
||||
unlink: vi.fn().mockResolvedValue(undefined),
|
||||
rmdir: vi.fn().mockResolvedValue(undefined),
|
||||
rename: vi.fn().mockResolvedValue(undefined),
|
||||
readlink: vi.fn().mockResolvedValue('mock link'),
|
||||
symlink: vi.fn().mockResolvedValue(undefined),
|
||||
});
|
||||
|
||||
// Mock Git
|
||||
const createMockGit = (): Git => ({
|
||||
statusMatrix: vi.fn(),
|
||||
currentBranch: vi.fn(),
|
||||
stat: vi.fn(),
|
||||
} as unknown as Git);
|
||||
|
||||
describe('GitStatusCommand', () => {
|
||||
let statusCommand: GitStatusCommand;
|
||||
let mockFS: JSRuntimeFS;
|
||||
let mockGit: Git;
|
||||
const testCwd = '/test';
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = createMockFS();
|
||||
mockGit = createMockGit();
|
||||
statusCommand = new GitStatusCommand({
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: testCwd,
|
||||
});
|
||||
});
|
||||
|
||||
it('should have correct command properties', () => {
|
||||
expect(statusCommand.name).toBe('status');
|
||||
expect(statusCommand.description).toBe('Show the working tree status');
|
||||
expect(statusCommand.usage).toBe('git status [--porcelain] [--short]');
|
||||
});
|
||||
|
||||
it('should return error when not in a git repository', async () => {
|
||||
// Mock stat to throw error for .git directory
|
||||
vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT'));
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: not a git repository');
|
||||
});
|
||||
|
||||
it('should show clean status when no changes', async () => {
|
||||
// Mock git status matrix with no changes
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch main');
|
||||
expect(result.stdout).toContain('nothing to commit, working tree clean');
|
||||
});
|
||||
|
||||
it('should show untracked files correctly', async () => {
|
||||
// Mock git status matrix with untracked file
|
||||
// [filepath, headStatus, workdirStatus, stageStatus]
|
||||
// Untracked: headStatus=0, stageStatus=0, workdirStatus=2
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['newfile.txt', 0, 2, 0]
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch main');
|
||||
expect(result.stdout).toContain('Untracked files:');
|
||||
expect(result.stdout).toContain('newfile.txt');
|
||||
});
|
||||
|
||||
it('should show staged files correctly', async () => {
|
||||
// Mock git status matrix with staged file
|
||||
// Staged new file: headStatus=0, stageStatus=2, workdirStatus=2
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['newfile.txt', 0, 2, 2]
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch main');
|
||||
expect(result.stdout).toContain('Changes to be committed:');
|
||||
expect(result.stdout).toContain('new file: newfile.txt');
|
||||
});
|
||||
|
||||
it('should show modified files correctly', async () => {
|
||||
// Mock git status matrix with modified file
|
||||
// Modified file: headStatus=1, stageStatus=1, workdirStatus=2
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['existing.txt', 1, 2, 1]
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch main');
|
||||
expect(result.stdout).toContain('Changes not staged for commit:');
|
||||
expect(result.stdout).toContain('modified: existing.txt');
|
||||
});
|
||||
|
||||
it('should show deleted files correctly', async () => {
|
||||
// Mock git status matrix with deleted file
|
||||
// Deleted file: headStatus=1, stageStatus=1, workdirStatus=0
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['deleted.txt', 1, 0, 1]
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch main');
|
||||
expect(result.stdout).toContain('Changes not staged for commit:');
|
||||
expect(result.stdout).toContain('deleted: deleted.txt');
|
||||
});
|
||||
|
||||
it('should format porcelain output correctly', async () => {
|
||||
// Mock git status matrix with various changes
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['untracked.txt', 0, 2, 0], // Untracked
|
||||
['staged.txt', 0, 2, 2], // Staged new file
|
||||
['modified.txt', 1, 2, 1], // Modified
|
||||
['deleted.txt', 1, 0, 1], // Deleted
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute(['--porcelain']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('?? untracked.txt');
|
||||
expect(result.stdout).toContain('A staged.txt');
|
||||
expect(result.stdout).toContain(' M modified.txt');
|
||||
expect(result.stdout).toContain(' D deleted.txt');
|
||||
});
|
||||
|
||||
it('should handle short format', async () => {
|
||||
// Mock git status matrix with changes
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['untracked.txt', 0, 2, 0], // Untracked
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute(['--short']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('?? untracked.txt');
|
||||
});
|
||||
|
||||
it('should handle complex status matrix correctly', async () => {
|
||||
// Mock git status matrix with a complex scenario
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['file1.txt', 1, 2, 2], // Modified and staged
|
||||
['file2.txt', 0, 2, 0], // Untracked
|
||||
['file3.txt', 1, 0, 0], // Deleted (staged)
|
||||
['file4.txt', 1, 2, 1], // Modified (not staged)
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('feature-branch');
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch feature-branch');
|
||||
expect(result.stdout).toContain('Changes to be committed:');
|
||||
expect(result.stdout).toContain('modified: file1.txt');
|
||||
expect(result.stdout).toContain('deleted: file3.txt');
|
||||
expect(result.stdout).toContain('Untracked files:');
|
||||
expect(result.stdout).toContain('file2.txt');
|
||||
expect(result.stdout).toContain('Changes not staged for commit:');
|
||||
expect(result.stdout).toContain('modified: file4.txt');
|
||||
});
|
||||
|
||||
it('should handle detached HEAD state', async () => {
|
||||
// Mock git status matrix with no current branch
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue(undefined);
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('HEAD detached at unknown');
|
||||
expect(result.stdout).toContain('nothing to commit, working tree clean');
|
||||
});
|
||||
});
|
||||
@@ -39,6 +39,7 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
let currentBranch: string | null = null;
|
||||
try {
|
||||
currentBranch = await this.git.currentBranch({
|
||||
|
||||
dir: this.pwd,
|
||||
}) || null;
|
||||
} catch {
|
||||
@@ -77,26 +78,22 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
let indexStatus = ' ';
|
||||
let workingStatus = ' ';
|
||||
|
||||
// Determine index status (staged changes - comparing HEAD to stage)
|
||||
if (headStatus === 0 && stageStatus === 2) {
|
||||
indexStatus = 'A'; // Added to stage
|
||||
// Determine index status (staged changes)
|
||||
if (headStatus === 0 && stageStatus === 1) {
|
||||
indexStatus = 'A'; // Added
|
||||
} else if (headStatus === 1 && stageStatus === 0) {
|
||||
indexStatus = 'D'; // Deleted from stage
|
||||
} else if (headStatus === 1 && stageStatus === 2) {
|
||||
indexStatus = 'M'; // Modified in stage
|
||||
indexStatus = 'D'; // Deleted
|
||||
} else if (headStatus === 1 && stageStatus === 1 && headStatus !== stageStatus) {
|
||||
indexStatus = 'M'; // Modified
|
||||
}
|
||||
|
||||
// Determine working directory status (comparing stage to working dir)
|
||||
if (headStatus === 0 && stageStatus === 0 && workdirStatus === 2) {
|
||||
// Untracked files show as ?? in porcelain format
|
||||
indexStatus = '?';
|
||||
workingStatus = '?';
|
||||
} else if (stageStatus === 2 && workdirStatus === 0) {
|
||||
workingStatus = 'D'; // Deleted in working dir
|
||||
// Determine working directory status
|
||||
if (headStatus === 0 && stageStatus === 0 && workdirStatus === 1) {
|
||||
workingStatus = '?'; // Untracked
|
||||
} else if (stageStatus === 1 && workdirStatus === 0) {
|
||||
workingStatus = 'D'; // Deleted in working dir (was same as HEAD)
|
||||
} else if (stageStatus !== workdirStatus && workdirStatus === 2) {
|
||||
workingStatus = 'M'; // Modified in working dir
|
||||
workingStatus = 'D'; // Deleted
|
||||
} else if (stageStatus !== workdirStatus) {
|
||||
workingStatus = 'M'; // Modified
|
||||
}
|
||||
|
||||
// Only show files with changes
|
||||
@@ -115,7 +112,7 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
if (currentBranch) {
|
||||
lines.push(`On branch ${currentBranch}`);
|
||||
} else {
|
||||
lines.push('HEAD detached at unknown');
|
||||
lines.push('On branch main');
|
||||
}
|
||||
|
||||
// Categorize changes
|
||||
@@ -125,26 +122,24 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
const deleted: string[] = [];
|
||||
|
||||
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
||||
// Staged changes (stage differs from HEAD)
|
||||
if (headStatus === 0 && stageStatus === 2) {
|
||||
// Staged changes (index differs from HEAD)
|
||||
if (headStatus === 0 && stageStatus === 1) {
|
||||
staged.push(`\tnew file: ${filepath}`);
|
||||
} else if (headStatus === 1 && stageStatus === 0) {
|
||||
staged.push(`\tdeleted: ${filepath}`);
|
||||
} else if (headStatus === 1 && stageStatus === 2) {
|
||||
} else if (headStatus !== stageStatus && headStatus === 1 && stageStatus === 1) {
|
||||
staged.push(`\tmodified: ${filepath}`);
|
||||
}
|
||||
|
||||
// Working directory changes (working dir differs from stage)
|
||||
if (stageStatus === 2 && workdirStatus === 0) {
|
||||
// Working directory changes (working dir differs from index)
|
||||
if (stageStatus === 1 && workdirStatus === 0) {
|
||||
deleted.push(`\tdeleted: ${filepath}`);
|
||||
} else if (stageStatus === 1 && workdirStatus === 0) {
|
||||
deleted.push(`\tdeleted: ${filepath}`);
|
||||
} else if (stageStatus !== workdirStatus && workdirStatus === 2) {
|
||||
} else if (stageStatus !== workdirStatus && stageStatus === 1 && workdirStatus === 1) {
|
||||
modified.push(`\tmodified: ${filepath}`);
|
||||
}
|
||||
|
||||
// Untracked files (not in HEAD, not in stage, but in working dir)
|
||||
if (headStatus === 0 && stageStatus === 0 && workdirStatus === 2) {
|
||||
// Untracked files
|
||||
if (headStatus === 0 && stageStatus === 0 && workdirStatus === 1) {
|
||||
untracked.push(`\t${filepath}`);
|
||||
}
|
||||
}
|
||||
@@ -153,7 +148,7 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
if (staged.length > 0) {
|
||||
lines.push('');
|
||||
lines.push('Changes to be committed:');
|
||||
lines.push(' (use "git restore --staged <file>..." to unstage)');
|
||||
lines.push(' (use "git reset HEAD <file>..." to unstage)');
|
||||
lines.push('');
|
||||
lines.push(...staged);
|
||||
}
|
||||
@@ -163,7 +158,7 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
lines.push('');
|
||||
lines.push('Changes not staged for commit:');
|
||||
lines.push(' (use "git add <file>..." to update what will be committed)');
|
||||
lines.push(' (use "git restore <file>..." to discard changes in working directory)');
|
||||
lines.push(' (use "git checkout -- <file>..." to discard changes in working directory)');
|
||||
lines.push('');
|
||||
lines.push(...modified);
|
||||
lines.push(...deleted);
|
||||
|
||||
@@ -61,7 +61,7 @@ describe('configUtils', () => {
|
||||
apiKey: 'sk-test123',
|
||||
},
|
||||
],
|
||||
recentlyUsedModels: ['openai/gpt-4', 'openai/gpt-3.5-turbo'],
|
||||
recentlyUsedModels: ['gpt-4', 'gpt-3.5-turbo'],
|
||||
};
|
||||
|
||||
describe('readAISettings', () => {
|
||||
@@ -97,6 +97,26 @@ describe('configUtils', () => {
|
||||
recentlyUsedModels: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('should migrate from localStorage if VFS file does not exist', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
|
||||
vi.mocked(mockFS.stat).mockRejectedValue(new Error('Directory not found'));
|
||||
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
mockLocalStorage.getItem.mockReturnValue(JSON.stringify(sampleAISettings));
|
||||
|
||||
const result = await readAISettings(mockFS);
|
||||
|
||||
expect(result).toEqual(sampleAISettings);
|
||||
expect(mockLocalStorage.getItem).toHaveBeenCalledWith('ai-settings');
|
||||
expect(mockLocalStorage.removeItem).toHaveBeenCalledWith('ai-settings');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
'/config/ai.json',
|
||||
JSON.stringify(sampleAISettings, null, 2),
|
||||
'utf8'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('writeAISettings', () => {
|
||||
@@ -168,6 +188,26 @@ describe('configUtils', () => {
|
||||
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
|
||||
});
|
||||
});
|
||||
|
||||
it('should migrate from localStorage if VFS file does not exist', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
|
||||
vi.mocked(mockFS.stat).mockRejectedValue(new Error('Directory not found'));
|
||||
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
mockLocalStorage.getItem.mockReturnValue(JSON.stringify(sampleGitSettings));
|
||||
|
||||
const result = await readGitSettings(mockFS);
|
||||
|
||||
expect(result).toEqual(sampleGitSettings);
|
||||
expect(mockLocalStorage.getItem).toHaveBeenCalledWith('git-settings');
|
||||
expect(mockLocalStorage.removeItem).toHaveBeenCalledWith('git-settings');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
'/config/git.json',
|
||||
JSON.stringify(sampleGitSettings, null, 2),
|
||||
'utf8'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('writeGitSettings', () => {
|
||||
|
||||
+130
-39
@@ -1,40 +1,11 @@
|
||||
import z from 'zod';
|
||||
import { filteredArray } from '@/lib/schema';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import type { AIProvider, AISettings } from '@/contexts/AISettingsContext';
|
||||
import type { AISettings, AIProvider } from '@/contexts/AISettingsContext';
|
||||
import type { GitSettings } from '@/contexts/GitSettingsContext';
|
||||
|
||||
const CONFIG_DIR = '/config';
|
||||
const AI_CONFIG_PATH = `${CONFIG_DIR}/ai.json`;
|
||||
const GIT_CONFIG_PATH = `${CONFIG_DIR}/git.json`;
|
||||
|
||||
const aiProviderSchema: z.ZodType<AIProvider> = z.object({
|
||||
id: z.string(),
|
||||
baseURL: z.string().url(),
|
||||
apiKey: z.string().optional(),
|
||||
nostr: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const providerModelSchema = z.string().regex(
|
||||
/^[^/]+\/.+$/,
|
||||
'Must be in format provider/model (e.g., "openai/gpt-4o")',
|
||||
);
|
||||
|
||||
const aiSettingsSchema = z.object({
|
||||
providers: filteredArray(aiProviderSchema),
|
||||
recentlyUsedModels: filteredArray(providerModelSchema),
|
||||
});
|
||||
|
||||
const gitCredentialSchema = z.object({
|
||||
username: z.string(),
|
||||
password: z.string(),
|
||||
});
|
||||
|
||||
const gitSettingsSchema = z.object({
|
||||
credentials: z.record(z.string(), gitCredentialSchema),
|
||||
corsProxy: z.string().url().catch('https://proxy.shakespeare.diy/?url={href}')
|
||||
});
|
||||
|
||||
/**
|
||||
* Ensures the config directory exists
|
||||
*/
|
||||
@@ -46,6 +17,49 @@ async function ensureConfigDir(fs: JSRuntimeFS): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrate AI settings from localStorage to VFS (internal function)
|
||||
*/
|
||||
async function migrateAISettingsFromLocalStorage(fs: JSRuntimeFS): Promise<AISettings | null> {
|
||||
// If not in VFS, try to migrate from localStorage
|
||||
const stored = localStorage.getItem('ai-settings');
|
||||
if (stored) {
|
||||
try {
|
||||
const parsed = JSON.parse(stored);
|
||||
if (parsed && typeof parsed === 'object' && 'providers' in parsed) {
|
||||
// Handle migration from old map format to new array format
|
||||
let providers;
|
||||
if (Array.isArray(parsed.providers)) {
|
||||
providers = parsed.providers;
|
||||
} else if (parsed.providers && typeof parsed.providers === 'object') {
|
||||
// Convert map to array
|
||||
providers = Object.entries(parsed.providers).map(([id, connection]) => ({
|
||||
id,
|
||||
...(connection as Omit<AIProvider, 'id'>),
|
||||
}));
|
||||
} else {
|
||||
providers = [];
|
||||
}
|
||||
|
||||
const settings: AISettings = {
|
||||
providers,
|
||||
recentlyUsedModels: parsed.recentlyUsedModels || [],
|
||||
};
|
||||
|
||||
// Write to VFS and remove from localStorage
|
||||
await writeAISettings(fs, settings);
|
||||
localStorage.removeItem('ai-settings');
|
||||
|
||||
return settings;
|
||||
}
|
||||
} catch {
|
||||
// If parsing fails, return null
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read AI settings from VFS (with automatic migration from localStorage)
|
||||
*/
|
||||
@@ -55,16 +69,50 @@ export async function readAISettings(fs: JSRuntimeFS): Promise<AISettings> {
|
||||
recentlyUsedModels: [],
|
||||
};
|
||||
|
||||
// Try to read from VFS first
|
||||
try {
|
||||
const content = await fs.readFile(AI_CONFIG_PATH, 'utf8');
|
||||
const data = JSON.parse(content);
|
||||
return aiSettingsSchema.parse(data);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
console.error('AI settings parsing error:', error.errors);
|
||||
const parsed = JSON.parse(content);
|
||||
|
||||
if (parsed && typeof parsed === 'object' && 'providers' in parsed) {
|
||||
// Handle migration from old map format to new array format
|
||||
let providers;
|
||||
if (Array.isArray(parsed.providers)) {
|
||||
providers = parsed.providers;
|
||||
} else if (parsed.providers && typeof parsed.providers === 'object') {
|
||||
// Convert map to array
|
||||
providers = Object.entries(parsed.providers).map(([id, connection]) => ({
|
||||
id,
|
||||
...(connection as Omit<AIProvider, 'id'>),
|
||||
}));
|
||||
|
||||
// Write back the migrated format
|
||||
const migratedSettings: AISettings = {
|
||||
providers,
|
||||
recentlyUsedModels: parsed.recentlyUsedModels || [],
|
||||
};
|
||||
await writeAISettings(fs, migratedSettings);
|
||||
return migratedSettings;
|
||||
} else {
|
||||
providers = [];
|
||||
}
|
||||
|
||||
return {
|
||||
providers,
|
||||
recentlyUsedModels: parsed.recentlyUsedModels || [],
|
||||
};
|
||||
}
|
||||
return defaultSettings;
|
||||
} catch {
|
||||
// File doesn't exist or is invalid, try migration
|
||||
}
|
||||
|
||||
// If not in VFS, try to migrate from localStorage
|
||||
const migratedSettings = await migrateAISettingsFromLocalStorage(fs);
|
||||
if (migratedSettings) {
|
||||
return migratedSettings;
|
||||
}
|
||||
|
||||
return defaultSettings;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -75,6 +123,35 @@ export async function writeAISettings(fs: JSRuntimeFS, settings: AISettings): Pr
|
||||
await fs.writeFile(AI_CONFIG_PATH, JSON.stringify(settings, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrate Git settings from localStorage to VFS (internal function)
|
||||
*/
|
||||
async function migrateGitSettingsFromLocalStorage(fs: JSRuntimeFS): Promise<GitSettings | null> {
|
||||
// If not in VFS, try to migrate from localStorage
|
||||
const stored = localStorage.getItem('git-settings');
|
||||
if (stored) {
|
||||
try {
|
||||
const parsed = JSON.parse(stored);
|
||||
if (parsed && typeof parsed === 'object' && 'credentials' in parsed) {
|
||||
const settings: GitSettings = {
|
||||
credentials: parsed.credentials || {},
|
||||
corsProxy: parsed.corsProxy || 'https://proxy.shakespeare.diy/?url={href}',
|
||||
};
|
||||
|
||||
// Write to VFS and remove from localStorage
|
||||
await writeGitSettings(fs, settings);
|
||||
localStorage.removeItem('git-settings');
|
||||
|
||||
return settings;
|
||||
}
|
||||
} catch {
|
||||
// If parsing fails, return null
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read Git settings from VFS (with automatic migration from localStorage)
|
||||
*/
|
||||
@@ -87,11 +164,25 @@ export async function readGitSettings(fs: JSRuntimeFS): Promise<GitSettings> {
|
||||
// Try to read from VFS first
|
||||
try {
|
||||
const content = await fs.readFile(GIT_CONFIG_PATH, 'utf8');
|
||||
const data = JSON.parse(content);
|
||||
return gitSettingsSchema.parse(data);
|
||||
const parsed = JSON.parse(content);
|
||||
|
||||
if (parsed && typeof parsed === 'object' && 'credentials' in parsed) {
|
||||
return {
|
||||
credentials: parsed.credentials || {},
|
||||
corsProxy: parsed.corsProxy || 'https://proxy.shakespeare.diy/?url={href}',
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
return defaultSettings;
|
||||
// File doesn't exist or is invalid, try migration
|
||||
}
|
||||
|
||||
// If not in VFS, try to migrate from localStorage
|
||||
const migratedSettings = await migrateGitSettingsFromLocalStorage(fs);
|
||||
if (migratedSettings) {
|
||||
return migratedSettings;
|
||||
}
|
||||
|
||||
return defaultSettings;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { ConsoleMessage } from '@/contexts/ConsoleContext';
|
||||
|
||||
/**
|
||||
* Custom error class for project preview console errors
|
||||
*/
|
||||
export class ProjectPreviewConsoleError extends Error {
|
||||
public readonly logs: ConsoleMessage[];
|
||||
|
||||
constructor(message: string, logs: ConsoleMessage[]) {
|
||||
super(message);
|
||||
this.name = 'ProjectPreviewConsoleError';
|
||||
this.logs = logs;
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -911,6 +911,7 @@ export class Git {
|
||||
const gitRelays = new Set<string>([
|
||||
'wss://git.shakespeare.diy/',
|
||||
'wss://relay.ngit.dev/',
|
||||
'wss://gitnostr.com/',
|
||||
'wss://relay.nostr.band/', // General purpose relay as fallback
|
||||
]);
|
||||
|
||||
@@ -1312,7 +1313,6 @@ export class Git {
|
||||
dir: options.dir,
|
||||
ref: `refs/heads/${currentBranch}`,
|
||||
value: upstreamCommit,
|
||||
force: true,
|
||||
});
|
||||
|
||||
// Update the working directory
|
||||
@@ -1395,6 +1395,7 @@ export class Git {
|
||||
relayUrls.push(
|
||||
'wss://git.shakespeare.diy/',
|
||||
'wss://relay.ngit.dev/',
|
||||
'wss://gitnostr.com/',
|
||||
'wss://relay.nostr.band/'
|
||||
);
|
||||
}
|
||||
|
||||
@@ -81,6 +81,9 @@ const resources = {
|
||||
dataSettingsDescription: 'Export files and manage local data',
|
||||
emailUpdates: 'Email Updates',
|
||||
emailUpdatesDescription: 'Subscribe to Shakespeare updates and resources',
|
||||
emailUpdatesDescriptionLong: 'Stay updated with the latest Shakespeare features, tutorials, and resources.',
|
||||
aboutShakespeareSettings: 'About Shakespeare',
|
||||
aboutShakespeareSettingsDescription: 'Information about Shakespeare',
|
||||
|
||||
// Project Sidebar
|
||||
newProject: 'New Project',
|
||||
@@ -204,6 +207,7 @@ const resources = {
|
||||
aboutShakespeare: 'About Shakespeare',
|
||||
aboutShakespeareDescription: 'Information about Shakespeare',
|
||||
sourceCode: 'Source Code',
|
||||
viewOnGitLab: 'View on GitLab',
|
||||
description: 'Description',
|
||||
license: 'License',
|
||||
loadingLicense: 'Loading license...',
|
||||
@@ -390,6 +394,9 @@ const resources = {
|
||||
dataSettingsDescription: 'Exporte arquivos e gerencie dados locais',
|
||||
emailUpdates: 'Atualizações por Email',
|
||||
emailUpdatesDescription: 'Inscreva-se para receber atualizações e recursos do Shakespeare',
|
||||
emailUpdatesDescriptionLong: 'Mantenha-se atualizado com os recursos mais recentes do Shakespeare, tutoriais e recursos. Enviamos apenas atualizações ocasionais e você pode cancelar a inscrição a qualquer momento.',
|
||||
aboutShakespeareSettings: 'Sobre o Shakespeare',
|
||||
aboutShakespeareSettingsDescription: 'Informações sobre o Shakespeare',
|
||||
|
||||
// Project Sidebar
|
||||
newProject: 'Novo Projeto',
|
||||
@@ -554,6 +561,7 @@ const resources = {
|
||||
aboutShakespeare: 'Sobre o Shakespeare',
|
||||
aboutShakespeareDescription: 'Informações sobre o Shakespeare.',
|
||||
sourceCode: 'Código-fonte',
|
||||
viewOnGitLab: 'Ver no GitLab',
|
||||
description: 'Descrição',
|
||||
license: 'Licença',
|
||||
loadingLicense: 'Carregando licença...',
|
||||
@@ -699,6 +707,9 @@ const resources = {
|
||||
dataSettingsDescription: '导出文件和管理本地数据',
|
||||
emailUpdates: '邮件更新',
|
||||
emailUpdatesDescription: '订阅Shakespeare更新和资源',
|
||||
emailUpdatesDescriptionLong: '及时了解最新的Shakespeare功能、教程和资源。我们只会偶尔发送更新,您可以随时取消订阅。',
|
||||
aboutShakespeareSettings: '关于Shakespeare',
|
||||
aboutShakespeareSettingsDescription: '关于Shakespeare的信息',
|
||||
|
||||
// Project Sidebar
|
||||
newProject: '新项目',
|
||||
@@ -863,6 +874,7 @@ const resources = {
|
||||
aboutShakespeare: '关于Shakespeare',
|
||||
aboutShakespeareDescription: '关于Shakespeare的信息。',
|
||||
sourceCode: '源代码',
|
||||
viewOnGitLab: '在GitLab上查看',
|
||||
description: '描述',
|
||||
license: '许可证',
|
||||
loadingLicense: '加载许可证中...',
|
||||
@@ -1008,6 +1020,9 @@ const resources = {
|
||||
dataSettingsDescription: 'Fitar da fayiloli da sarrafa bayanan gida',
|
||||
emailUpdates: 'Sabuntawar Imel',
|
||||
emailUpdatesDescription: 'Yi rajista don karbar sabuntawar Shakespeare da albarkatu',
|
||||
emailUpdatesDescriptionLong: 'Kasance da sabuntawa game da sabbin fasalolin Shakespeare, koyarwa, da albarkatu. Muna aika sabuntawa lokaci-lokaci kawai kuma kuna iya dakatar da rajista koyaushe.',
|
||||
aboutShakespeareSettings: 'Game da Shakespeare',
|
||||
aboutShakespeareSettingsDescription: 'Bayani game da Shakespeare',
|
||||
|
||||
// Project Sidebar
|
||||
newProject: 'Sabon Aikin',
|
||||
@@ -1172,6 +1187,7 @@ const resources = {
|
||||
aboutShakespeare: 'Game da Shakespeare',
|
||||
aboutShakespeareDescription: 'Bayani game da Shakespeare.',
|
||||
sourceCode: 'Lambar Tushe',
|
||||
viewOnGitLab: 'Duba akan GitLab',
|
||||
description: 'Bayanin',
|
||||
license: 'Lasisi',
|
||||
loadingLicense: 'Ana lodin lasisi...',
|
||||
@@ -1317,6 +1333,9 @@ const resources = {
|
||||
dataSettingsDescription: 'Gbe awọn faili jade ati ṣakoso data agbegbe',
|
||||
emailUpdates: 'Awọn Imudojuiwọn Imeeli',
|
||||
emailUpdatesDescription: 'Forukọsilẹ fun awọn imudojuiwọn Shakespeare ati awọn ohun elo',
|
||||
emailUpdatesDescriptionLong: 'Wa pẹlu imudojuiwọn pẹlu awọn ẹya Shakespeare tuntun, awọn ikẹkọ, ati awọn ohun elo. A nfi awọn imudojuiwọn lọọrọọ nikan ranṣẹ ati pe o le da forukọsilẹ duro nigbakugba.',
|
||||
aboutShakespeareSettings: 'Nipa Shakespeare',
|
||||
aboutShakespeareSettingsDescription: 'Alaye nipa Shakespeare',
|
||||
|
||||
// Project Sidebar
|
||||
newProject: 'Iṣẹ akanṣe Tuntun',
|
||||
@@ -1481,6 +1500,7 @@ const resources = {
|
||||
aboutShakespeare: 'Nipa Shakespeare',
|
||||
aboutShakespeareDescription: 'Alaye nipa Shakespeare.',
|
||||
sourceCode: 'Koodu Orisun',
|
||||
viewOnGitLab: 'Wo lori GitLab',
|
||||
description: 'Apejuwe',
|
||||
license: 'Iwe-aṣẹ',
|
||||
loadingLicense: 'N gbe iwe-aṣẹ...',
|
||||
@@ -1621,6 +1641,9 @@ const resources = {
|
||||
dataSettingsDescription: 'Bupụta faịlụ na jikwaa data mpaghara',
|
||||
emailUpdates: 'Nmelite Email',
|
||||
emailUpdatesDescription: 'Debanye aha maka nmelite Shakespeare na akụrụngwa',
|
||||
emailUpdatesDescriptionLong: 'Nọrọ na-emelite na atụmatụ Shakespeare ọhụrụ, nkuzi, na akụrụngwa. Anyị na-eziga naanị nmelite mgbe ụfọdụ ma ị nwere ike ịkwụsị ndebanye aha mgbe ọ bụla.',
|
||||
aboutShakespeareSettings: 'Gbasara Shakespeare',
|
||||
aboutShakespeareSettingsDescription: 'Ozi gbasara Shakespeare',
|
||||
|
||||
// Project Sidebar
|
||||
newProject: 'Ọrụ Ọhụrụ',
|
||||
@@ -1785,6 +1808,7 @@ const resources = {
|
||||
aboutShakespeare: 'Gbasara Shakespeare',
|
||||
aboutShakespeareDescription: 'Ozi gbasara Shakespeare.',
|
||||
sourceCode: 'Koodu Isi',
|
||||
viewOnGitLab: 'Lee na GitLab',
|
||||
description: 'Nkọwa',
|
||||
license: 'Ikike',
|
||||
loadingLicense: 'Na-ebu ikike...',
|
||||
|
||||
@@ -1,149 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import z from 'zod';
|
||||
import { filteredArray } from './schema';
|
||||
|
||||
describe('filteredArray', () => {
|
||||
it('filters out invalid items and keeps valid ones', () => {
|
||||
const numberSchema = z.number();
|
||||
const schema = filteredArray(numberSchema);
|
||||
|
||||
const input = [1, 'invalid', 2, null, 3, undefined, 4];
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual([1, 2, 3, 4]);
|
||||
});
|
||||
|
||||
it('returns empty array when all items are invalid', () => {
|
||||
const numberSchema = z.number();
|
||||
const schema = filteredArray(numberSchema);
|
||||
|
||||
const input = ['string', null, undefined, {}, []];
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns all items when all are valid', () => {
|
||||
const stringSchema = z.string();
|
||||
const schema = filteredArray(stringSchema);
|
||||
|
||||
const input = ['hello', 'world', 'test'];
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual(['hello', 'world', 'test']);
|
||||
});
|
||||
|
||||
it('works with complex object schemas', () => {
|
||||
const userSchema = z.object({
|
||||
id: z.number(),
|
||||
name: z.string(),
|
||||
email: z.string().email(),
|
||||
});
|
||||
const schema = filteredArray(userSchema);
|
||||
|
||||
const input = [
|
||||
{ id: 1, name: 'John', email: '[email protected]' },
|
||||
{ id: 'invalid', name: 'Jane', email: '[email protected]' }, // invalid id
|
||||
{ id: 2, name: 'Bob', email: 'invalid-email' }, // invalid email
|
||||
{ id: 3, name: 'Alice', email: '[email protected]' },
|
||||
'not an object',
|
||||
null,
|
||||
];
|
||||
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual([
|
||||
{ id: 1, name: 'John', email: '[email protected]' },
|
||||
{ id: 3, name: 'Alice', email: '[email protected]' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('handles empty array input', () => {
|
||||
const numberSchema = z.number();
|
||||
const schema = filteredArray(numberSchema);
|
||||
|
||||
const result = schema.parse([]);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it('catches non-array input and returns empty array', () => {
|
||||
const numberSchema = z.number();
|
||||
const schema = filteredArray(numberSchema);
|
||||
|
||||
const result1 = schema.parse('not an array');
|
||||
const result2 = schema.parse(null);
|
||||
const result3 = schema.parse(undefined);
|
||||
const result4 = schema.parse(123);
|
||||
|
||||
expect(result1).toEqual([]);
|
||||
expect(result2).toEqual([]);
|
||||
expect(result3).toEqual([]);
|
||||
expect(result4).toEqual([]);
|
||||
});
|
||||
|
||||
it('works with union schemas', () => {
|
||||
const unionSchema = z.union([z.string(), z.number()]);
|
||||
const schema = filteredArray(unionSchema);
|
||||
|
||||
const input = ['hello', 42, true, 'world', null, 99, {}];
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual(['hello', 42, 'world', 99]);
|
||||
});
|
||||
|
||||
it('preserves transformed values from schema', () => {
|
||||
const transformSchema = z.string().transform((str) => str.toUpperCase());
|
||||
const schema = filteredArray(transformSchema);
|
||||
|
||||
const input = ['hello', 123, 'world', null, 'test'];
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual(['HELLO', 'WORLD', 'TEST']);
|
||||
});
|
||||
|
||||
it('works with optional fields in object schemas', () => {
|
||||
const optionalSchema = z.object({
|
||||
required: z.string(),
|
||||
optional: z.string().optional(),
|
||||
});
|
||||
const schema = filteredArray(optionalSchema);
|
||||
|
||||
const input = [
|
||||
{ required: 'test1' },
|
||||
{ required: 'test2', optional: 'value' },
|
||||
{ optional: 'value' }, // missing required field
|
||||
{ required: 'test3', optional: undefined },
|
||||
];
|
||||
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual([
|
||||
{ required: 'test1' },
|
||||
{ required: 'test2', optional: 'value' },
|
||||
{ required: 'test3', optional: undefined },
|
||||
]);
|
||||
});
|
||||
|
||||
it('handles nested arrays', () => {
|
||||
const nestedSchema = z.object({
|
||||
name: z.string(),
|
||||
tags: z.string().array(),
|
||||
});
|
||||
const schema = filteredArray(nestedSchema);
|
||||
|
||||
const input = [
|
||||
{ name: 'item1', tags: ['tag1', 'tag2'] },
|
||||
{ name: 'item2', tags: 'not an array' }, // invalid tags
|
||||
{ name: 'item3', tags: [] },
|
||||
'invalid item',
|
||||
];
|
||||
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual([
|
||||
{ name: 'item1', tags: ['tag1', 'tag2'] },
|
||||
{ name: 'item3', tags: [] },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,12 +0,0 @@
|
||||
import z from "zod";
|
||||
|
||||
/** Validates individual items in an array, dropping any that aren't valid. */
|
||||
export function filteredArray<T extends z.ZodTypeAny>(schema: T) {
|
||||
return z.any().array().catch([])
|
||||
.transform((arr) => (
|
||||
arr.map((item) => {
|
||||
const parsed = schema.safeParse(item);
|
||||
return parsed.success ? parsed.data : undefined;
|
||||
}).filter((item): item is z.infer<T> => Boolean(item))
|
||||
));
|
||||
}
|
||||
@@ -195,25 +195,6 @@ describe('NpmAddPackageTool', () => {
|
||||
}
|
||||
};
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(packageJson, null, 2));
|
||||
|
||||
const result = await tool.execute({ name: 'lodash' });
|
||||
|
||||
// Should not fetch from registry when no version specified and package already installed
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
expect(mockFS.writeFile).not.toHaveBeenCalled();
|
||||
expect(result).toContain('ℹ️ Package lodash is already installed in dependencies with version ^4.17.21.');
|
||||
});
|
||||
|
||||
it('should handle package already installed with specific version', async () => {
|
||||
const packageJson = {
|
||||
name: 'test-project',
|
||||
version: '1.0.0',
|
||||
dependencies: {
|
||||
'lodash': '^4.17.21'
|
||||
}
|
||||
};
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(packageJson, null, 2));
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
@@ -227,10 +208,10 @@ describe('NpmAddPackageTool', () => {
|
||||
})
|
||||
});
|
||||
|
||||
const result = await tool.execute({ name: 'lodash', version: '4.17.21' });
|
||||
const result = await tool.execute({ name: 'lodash' });
|
||||
|
||||
expect(mockFS.writeFile).not.toHaveBeenCalled();
|
||||
expect(result).toContain('ℹ️ Package [email protected] is already installed in dependencies.');
|
||||
expect(result).toContain('ℹ️ Package [email protected] is already installed');
|
||||
});
|
||||
|
||||
it('should handle missing package.json', async () => {
|
||||
|
||||
@@ -88,16 +88,6 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
|
||||
throw new Error(`❌ Invalid package.json format. Could not parse JSON.`);
|
||||
}
|
||||
|
||||
// Check if package already exists
|
||||
const dependencyKey = dev ? 'devDependencies' : 'dependencies';
|
||||
const otherKey = dev ? 'dependencies' : 'devDependencies';
|
||||
|
||||
// If no version is specified and package is already installed, it's a no-op
|
||||
if (!version && packageJson[dependencyKey]?.[name]) {
|
||||
const currentVersion = packageJson[dependencyKey][name];
|
||||
return `ℹ️ Package ${name} is already installed in ${dependencyKey} with version ${currentVersion}.`;
|
||||
}
|
||||
|
||||
// Determine version to use and fetch package metadata
|
||||
let targetVersion = version;
|
||||
let packageMetadata: NpmRegistryResponse;
|
||||
@@ -117,7 +107,10 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
|
||||
}
|
||||
}
|
||||
|
||||
// Check if package already exists with the specific version
|
||||
// Check if package already exists
|
||||
const dependencyKey = dev ? 'devDependencies' : 'dependencies';
|
||||
const otherKey = dev ? 'dependencies' : 'devDependencies';
|
||||
|
||||
if (packageJson[dependencyKey]?.[name]) {
|
||||
const currentVersion = packageJson[dependencyKey][name];
|
||||
if (currentVersion === `^${targetVersion}`) {
|
||||
|
||||
@@ -1,25 +1,24 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import {
|
||||
ReadConsoleMessagesTool,
|
||||
addConsoleMessage,
|
||||
clearConsoleMessages,
|
||||
ProjectPreviewConsoleError,
|
||||
addErrorListener,
|
||||
removeErrorListener
|
||||
} from './ReadConsoleMessagesTool';
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { ReadConsoleMessagesTool } from './ReadConsoleMessagesTool';
|
||||
import { ConsoleMessage, ProjectPreviewConsoleError } from '@/contexts/ConsoleContext';
|
||||
|
||||
describe('ReadConsoleMessagesTool', () => {
|
||||
let mockMessages: ConsoleMessage[];
|
||||
let getMessages: () => ConsoleMessage[];
|
||||
|
||||
beforeEach(() => {
|
||||
clearConsoleMessages();
|
||||
// Add test messages
|
||||
addConsoleMessage('log', 'App started');
|
||||
addConsoleMessage('warn', 'Deprecated API used');
|
||||
addConsoleMessage('error', 'Network request failed');
|
||||
addConsoleMessage('info', 'User logged in');
|
||||
// Set up test messages
|
||||
mockMessages = [
|
||||
{ level: 'log', message: 'App started' },
|
||||
{ level: 'warn', message: 'Deprecated API used' },
|
||||
{ level: 'error', message: 'Network request failed' },
|
||||
{ level: 'info', message: 'User logged in' },
|
||||
];
|
||||
getMessages = () => mockMessages;
|
||||
});
|
||||
|
||||
it('should return all messages by default', async () => {
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
const tool = new ReadConsoleMessagesTool(getMessages);
|
||||
const result = await tool.execute({});
|
||||
|
||||
expect(result).toContain('Found 4 console messages');
|
||||
@@ -30,7 +29,7 @@ describe('ReadConsoleMessagesTool', () => {
|
||||
});
|
||||
|
||||
it('should filter messages by level', async () => {
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
const tool = new ReadConsoleMessagesTool(getMessages);
|
||||
const result = await tool.execute({ filter: 'error' });
|
||||
|
||||
expect(result).toContain('Found 1 console message (level: error)');
|
||||
@@ -39,7 +38,7 @@ describe('ReadConsoleMessagesTool', () => {
|
||||
});
|
||||
|
||||
it('should limit number of messages', async () => {
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
const tool = new ReadConsoleMessagesTool(getMessages);
|
||||
const result = await tool.execute({ limit: 2 });
|
||||
|
||||
expect(result).toContain('Found 2 console messages');
|
||||
@@ -50,15 +49,15 @@ describe('ReadConsoleMessagesTool', () => {
|
||||
});
|
||||
|
||||
it('should handle no messages found', async () => {
|
||||
clearConsoleMessages();
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
const emptyGetMessages = () => [];
|
||||
const tool = new ReadConsoleMessagesTool(emptyGetMessages);
|
||||
const result = await tool.execute({});
|
||||
|
||||
expect(result).toBe('No console messages found.');
|
||||
});
|
||||
|
||||
it('should handle no messages found with filter', async () => {
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
const tool = new ReadConsoleMessagesTool(getMessages);
|
||||
const result = await tool.execute({ filter: 'debug' });
|
||||
|
||||
expect(result).toBe('No console messages found for level: debug.');
|
||||
@@ -80,89 +79,5 @@ describe('ProjectPreviewConsoleError', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Console Error Listeners', () => {
|
||||
beforeEach(() => {
|
||||
clearConsoleMessages();
|
||||
});
|
||||
|
||||
it('should trigger error listener when console error is added', async () => {
|
||||
const errorListener = vi.fn();
|
||||
addErrorListener(errorListener);
|
||||
|
||||
// Add an error message
|
||||
addConsoleMessage('error', 'Test error message');
|
||||
|
||||
// Wait a bit for the listener to be called
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
|
||||
expect(errorListener).toHaveBeenCalledTimes(1);
|
||||
expect(errorListener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
message: 'Console error detected: Test error message',
|
||||
logs: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
level: 'error',
|
||||
message: 'Test error message'
|
||||
})
|
||||
])
|
||||
})
|
||||
);
|
||||
|
||||
removeErrorListener(errorListener);
|
||||
});
|
||||
|
||||
it('should not trigger error listener for non-error messages', async () => {
|
||||
const errorListener = vi.fn();
|
||||
addErrorListener(errorListener);
|
||||
|
||||
// Add non-error messages
|
||||
addConsoleMessage('log', 'Test log message');
|
||||
addConsoleMessage('warn', 'Test warning message');
|
||||
addConsoleMessage('info', 'Test info message');
|
||||
|
||||
// Wait a bit
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
|
||||
expect(errorListener).not.toHaveBeenCalled();
|
||||
|
||||
removeErrorListener(errorListener);
|
||||
});
|
||||
|
||||
it('should remove error listener correctly', async () => {
|
||||
const errorListener = vi.fn();
|
||||
addErrorListener(errorListener);
|
||||
removeErrorListener(errorListener);
|
||||
|
||||
// Add an error message
|
||||
addConsoleMessage('error', 'Test error message');
|
||||
|
||||
// Wait a bit
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
|
||||
expect(errorListener).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle listener errors gracefully', async () => {
|
||||
const faultyListener = vi.fn(() => {
|
||||
throw new Error('Listener error');
|
||||
});
|
||||
const workingListener = vi.fn();
|
||||
|
||||
addErrorListener(faultyListener);
|
||||
addErrorListener(workingListener);
|
||||
|
||||
// Should not throw despite faulty listener
|
||||
expect(() => {
|
||||
addConsoleMessage('error', 'Test error message');
|
||||
}).not.toThrow();
|
||||
|
||||
// Wait a bit
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
|
||||
expect(faultyListener).toHaveBeenCalled();
|
||||
expect(workingListener).toHaveBeenCalled();
|
||||
|
||||
removeErrorListener(faultyListener);
|
||||
removeErrorListener(workingListener);
|
||||
});
|
||||
});
|
||||
// Console error listener tests are now handled by the ConsoleContext
|
||||
// These tests should be moved to a separate ConsoleContext test file
|
||||
@@ -1,82 +1,18 @@
|
||||
import { Tool } from './Tool';
|
||||
|
||||
export interface ConsoleMessage {
|
||||
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface ReadConsoleMessagesParams {
|
||||
filter?: 'error' | 'warn' | 'info' | 'debug' | 'log' | 'all';
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom error class for project preview console errors
|
||||
*/
|
||||
export class ProjectPreviewConsoleError extends Error {
|
||||
public readonly logs: ConsoleMessage[];
|
||||
|
||||
constructor(message: string, logs: ConsoleMessage[]) {
|
||||
super(message);
|
||||
this.name = 'ProjectPreviewConsoleError';
|
||||
this.logs = logs;
|
||||
}
|
||||
}
|
||||
|
||||
// Simple global console messages storage
|
||||
const consoleMessages: ConsoleMessage[] = [];
|
||||
const errorListeners: Array<(error: ProjectPreviewConsoleError) => void> = [];
|
||||
|
||||
export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => {
|
||||
const consoleMessage: ConsoleMessage = {
|
||||
level,
|
||||
message,
|
||||
};
|
||||
|
||||
consoleMessages.push(consoleMessage);
|
||||
|
||||
// If this is an error, notify listeners
|
||||
if (level === 'error') {
|
||||
const error = new ProjectPreviewConsoleError(
|
||||
`Console error detected: ${message}`,
|
||||
consoleMessages.filter(msg => msg.level === 'error')
|
||||
);
|
||||
|
||||
errorListeners.forEach(listener => {
|
||||
try {
|
||||
listener(error);
|
||||
} catch (err) {
|
||||
console.warn('Error listener failed:', err);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const getConsoleMessages = (): ConsoleMessage[] => {
|
||||
return [...consoleMessages];
|
||||
};
|
||||
|
||||
export const addErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => {
|
||||
errorListeners.push(listener);
|
||||
};
|
||||
|
||||
export const removeErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => {
|
||||
const index = errorListeners.indexOf(listener);
|
||||
if (index > -1) {
|
||||
errorListeners.splice(index, 1);
|
||||
}
|
||||
};
|
||||
|
||||
export const clearConsoleMessages = () => {
|
||||
consoleMessages.length = 0;
|
||||
};
|
||||
|
||||
export class ReadConsoleMessagesTool implements Tool<ReadConsoleMessagesParams> {
|
||||
constructor(private getMessages: () => import('@/contexts/ConsoleContext').ConsoleMessage[]) {}
|
||||
|
||||
async execute(params: ReadConsoleMessagesParams): Promise<string> {
|
||||
const { filter = 'all', limit } = params;
|
||||
|
||||
// Filter and limit messages in one chain
|
||||
const filteredMessages = getConsoleMessages()
|
||||
const filteredMessages = this.getMessages()
|
||||
.filter(msg => filter === 'all' || msg.level === filter)
|
||||
.slice(limit && limit > 0 ? -limit : 0);
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { AboutSettings } from './AboutSettings';
|
||||
|
||||
// Mock fetch
|
||||
global.fetch = vi.fn();
|
||||
|
||||
describe('AboutSettings', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders about settings page with project information', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<AboutSettings />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('About Shakespeare')).toBeInTheDocument();
|
||||
expect(screen.getByText(/Information about Shakespeare/)).toBeInTheDocument();
|
||||
expect(screen.getByText('Source Code')).toBeInTheDocument();
|
||||
expect(screen.getByText('View on GitLab')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('fetches and displays license text', async () => {
|
||||
const mockLicense = 'MIT License\n\nCopyright (c) 2024 Shakespeare';
|
||||
const mockFetch = global.fetch as ReturnType<typeof vi.fn>;
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
text: () => Promise.resolve(mockLicense),
|
||||
} as Response);
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AboutSettings />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Initially shows loading
|
||||
expect(screen.getByText('Loading license...')).toBeInTheDocument();
|
||||
|
||||
// Wait for license to load
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/MIT License/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Copyright \(c\) 2024 Shakespeare/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Verify fetch was called with correct URL
|
||||
expect(global.fetch).toHaveBeenCalledWith('/LICENSE.txt');
|
||||
});
|
||||
|
||||
it('shows error when license fetch fails', async () => {
|
||||
const mockFetch = global.fetch as ReturnType<typeof vi.fn>;
|
||||
mockFetch.mockRejectedValueOnce(new Error('Network error'));
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AboutSettings />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Wait for error to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Failed to load license/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
+62
-52
@@ -1,12 +1,12 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Info, ExternalLink, Loader2, AlertTriangle, ArrowLeft, Code } from 'lucide-react';
|
||||
import { Info, ExternalLink, Loader2, AlertTriangle, ArrowLeft } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { EmailSubscription } from '@/components/EmailSubscription';
|
||||
|
||||
export function AboutSettings() {
|
||||
const { t } = useTranslation();
|
||||
@@ -22,7 +22,7 @@ export function AboutSettings() {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
const response = await fetch('/LICENSE.html');
|
||||
const response = await fetch('/LICENSE.txt');
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch license: ${response.status} ${response.statusText}`);
|
||||
@@ -78,56 +78,66 @@ export function AboutSettings() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-6 max-w-xl">
|
||||
{/* Email Updates */}
|
||||
<EmailSubscription />
|
||||
|
||||
<div className="space-y-3">
|
||||
{/* Project Information */}
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full h-12 flex items-center gap-2 justify-start text-base"
|
||||
asChild
|
||||
>
|
||||
<a href="https://gitlab.com/soapbox-pub/shakespeare" target="_blank">
|
||||
<Code className="!size-5" />
|
||||
<div className="space-y-4">
|
||||
{/* Project Information */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Info className="h-5 w-5" />
|
||||
{t('sourceCode')}
|
||||
<ExternalLink className="ml-auto" />
|
||||
</a>
|
||||
</Button>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div>
|
||||
<Button
|
||||
variant="outline"
|
||||
asChild
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
<a
|
||||
href="https://gitlab.com/soapbox-pub/act2"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
{t('viewOnGitLab')}
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* License */}
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="license-text" className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center gap-2">
|
||||
<Info className="h-5 w-5" />
|
||||
{t('license')}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center gap-2 text-muted-foreground py-4">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
<span className="text-sm">{t('loadingLicense')}</span>
|
||||
</div>
|
||||
) : error ? (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
{t('failedToLoadLicense')}: {error}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : license ? (
|
||||
<div
|
||||
className="prose text-sm dark:prose-invert mx-auto"
|
||||
dangerouslySetInnerHTML={{ __html: license }}
|
||||
/>
|
||||
) : null}
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</div>
|
||||
{/* License */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Info className="h-5 w-5" />
|
||||
{t('license')}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading ? (
|
||||
<div className="flex items-center gap-2 text-muted-foreground py-4">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
<span className="text-sm">{t('loadingLicense')}</span>
|
||||
</div>
|
||||
) : error ? (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
{t('failedToLoadLicense')}: {error}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : license ? (
|
||||
<ScrollArea className="h-96 w-full rounded-md border p-4">
|
||||
<pre className="text-xs font-mono whitespace-pre-wrap break-words">
|
||||
{license}
|
||||
</pre>
|
||||
</ScrollArea>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
+2
-55
@@ -4,12 +4,11 @@ import { useTranslation } from 'react-i18next';
|
||||
import { AppLayout } from '@/components/AppLayout';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { GitBranch, Loader2, AlertCircle, FileArchive, MoreHorizontal } from 'lucide-react';
|
||||
import { GitBranch, Loader2, AlertCircle } from 'lucide-react';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { ProjectImportDialog } from '@/components/ProjectImportDialog';
|
||||
|
||||
import { useSeoMeta } from '@unhead/react';
|
||||
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '@/components/ui/dropdown-menu';
|
||||
|
||||
export default function Clone() {
|
||||
const { t } = useTranslation();
|
||||
@@ -21,7 +20,6 @@ export default function Clone() {
|
||||
const projectsManager = useProjectsManager();
|
||||
const { toast } = useToast();
|
||||
const autoCloneInitiatedRef = useRef(false);
|
||||
const [isZipDialogOpen, setIsZipDialogOpen] = useState(false);
|
||||
|
||||
useSeoMeta({
|
||||
title: `${t('importRepository')} - Shakespeare`,
|
||||
@@ -173,28 +171,6 @@ export default function Clone() {
|
||||
}
|
||||
}, [handleClone, searchParams]);
|
||||
|
||||
const handleImportZip = async (
|
||||
data: { file: File; projectId?: string },
|
||||
overwrite: boolean
|
||||
) => {
|
||||
try {
|
||||
// Single project import from ZIP file
|
||||
const project = await projectsManager.importProjectFromZip(data.file, data.projectId, overwrite);
|
||||
|
||||
// Show success toast
|
||||
toast({
|
||||
title: overwrite ? "Project Overwritten Successfully" : "Project Imported Successfully",
|
||||
description: `"${project.name}" has been ${overwrite ? 'overwritten' : 'imported'} and is ready to use.`,
|
||||
});
|
||||
|
||||
// Navigate to the imported project
|
||||
navigate(`/project/${project.id}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to import project:', error);
|
||||
throw error; // Re-throw to let the dialog handle the error display
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AppLayout title={t('importRepository')}>
|
||||
<div className="max-w-2xl mx-auto">
|
||||
@@ -250,36 +226,7 @@ export default function Clone() {
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Import ZIP File Link */}
|
||||
<div className="mt-8 text-center">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="text-muted-foreground hover:text-primary hover:bg-transparent">
|
||||
<MoreHorizontal className="h-5 w-5" />
|
||||
<span className="sr-only">More options</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="center">
|
||||
<DropdownMenuItem
|
||||
className="flex items-center gap-2 w-full"
|
||||
onClick={() => setIsZipDialogOpen(true)}
|
||||
>
|
||||
<FileArchive className="h-4 w-4" />
|
||||
Import ZIP File
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ZIP Import Dialog */}
|
||||
<ProjectImportDialog
|
||||
mode="single"
|
||||
onImport={handleImportZip}
|
||||
open={isZipDialogOpen}
|
||||
onOpenChange={setIsZipDialogOpen}
|
||||
/>
|
||||
</AppLayout>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Shield, Upload } from 'lucide-react';
|
||||
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Shield } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||
@@ -11,8 +10,6 @@ import { Switch } from '@/components/ui/switch';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { ProjectImportDialog } from '@/components/ProjectImportDialog';
|
||||
import {
|
||||
isPersistentStorageSupported,
|
||||
isPersistentStorageGranted,
|
||||
@@ -42,13 +39,10 @@ export function DataSettings() {
|
||||
const [storageInfo, setStorageInfo] = useState<StorageInfo | null>(null);
|
||||
const [storageError, setStorageError] = useState<string | null>(null);
|
||||
const [isPersistent, setIsPersistent] = useState<boolean | null>(null);
|
||||
const [isBulkImportOpen, setIsBulkImportOpen] = useState(false);
|
||||
const { toast } = useToast();
|
||||
const { fs } = useFS();
|
||||
const navigate = useNavigate();
|
||||
const isMobile = useIsMobile();
|
||||
const projectsManager = useProjectsManager();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Format bytes to human readable format
|
||||
const formatBytes = (bytes: number): string => {
|
||||
@@ -223,67 +217,6 @@ export function DataSettings() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleBulkImport = async (
|
||||
data: { file: File; projectId?: string } | { projects: { id: string; files: { [path: string]: Uint8Array } }[] },
|
||||
overwrite: boolean
|
||||
) => {
|
||||
try {
|
||||
let successCount = 0;
|
||||
const errors: string[] = [];
|
||||
|
||||
// Handle both single and bulk import data
|
||||
if ('projects' in data) {
|
||||
// Bulk import
|
||||
for (const project of data.projects) {
|
||||
try {
|
||||
// Import the project directly using files (bypasses ZIP creation)
|
||||
await projectsManager.importProject(
|
||||
{ files: project.files },
|
||||
{ projectId: project.id, overwrite, projectName: project.id }
|
||||
);
|
||||
successCount++;
|
||||
} catch (error) {
|
||||
console.error(`Failed to import project ${project.id}:`, error);
|
||||
errors.push(`${project.id}: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Single import (shouldn't happen in bulk mode, but handle gracefully)
|
||||
throw new Error('Single import not supported in bulk import mode');
|
||||
}
|
||||
|
||||
// Show success/error toast and refresh project list
|
||||
if (successCount > 0) {
|
||||
// Refresh projects list to show newly imported projects
|
||||
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||
|
||||
toast({
|
||||
title: `${successCount} Project${successCount !== 1 ? 's' : ''} Imported Successfully`,
|
||||
description: errors.length > 0
|
||||
? `${errors.length} project${errors.length !== 1 ? 's' : ''} failed to import.`
|
||||
: `All projects have been imported and are ready to use.`,
|
||||
variant: errors.length > 0 ? "destructive" : "default",
|
||||
});
|
||||
}
|
||||
|
||||
if (errors.length > 0 && successCount === 0) {
|
||||
toast({
|
||||
title: "Import Failed",
|
||||
description: `Failed to import projects: ${errors.slice(0, 3).join(', ')}${errors.length > 3 ? '...' : ''}`,
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Bulk import failed:', error);
|
||||
toast({
|
||||
title: "Import Failed",
|
||||
description: error instanceof Error ? error.message : 'Unknown error occurred',
|
||||
variant: "destructive",
|
||||
});
|
||||
throw error; // Re-throw to let the dialog handle the error display
|
||||
}
|
||||
};
|
||||
|
||||
const handleClearAllData = async () => {
|
||||
setIsClearing(true);
|
||||
try {
|
||||
@@ -458,28 +391,6 @@ export function DataSettings() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Import Projects */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Upload className="h-5 w-5" />
|
||||
Import Projects
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Import multiple projects from a ZIP file exported from Shakespeare. You can choose which projects to import and handle conflicts with existing projects.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Button
|
||||
onClick={() => setIsBulkImportOpen(true)}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
<Upload className="h-4 w-4 mr-2" />
|
||||
Import Projects
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Clear All Data */}
|
||||
<Card className="border-destructive/20">
|
||||
<CardHeader>
|
||||
@@ -548,14 +459,6 @@ export function DataSettings() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Bulk Project Import Dialog */}
|
||||
<ProjectImportDialog
|
||||
mode="bulk"
|
||||
onImport={handleBulkImport}
|
||||
open={isBulkImportOpen}
|
||||
onOpenChange={setIsBulkImportOpen}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { ArrowLeft, Mail, CheckCircle } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
export function EmailSettings() {
|
||||
const { t } = useTranslation();
|
||||
const isMobile = useIsMobile();
|
||||
const navigate = useNavigate();
|
||||
const { user } = useCurrentUser();
|
||||
const { toast } = useToast();
|
||||
|
||||
const [email, setEmail] = useState('');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [isSubmitted, setIsSubmitted] = useState(false);
|
||||
|
||||
// Check localStorage on component mount
|
||||
useEffect(() => {
|
||||
const hasSubscribed = localStorage.getItem('shakespeare-email-subscribed');
|
||||
if (hasSubscribed === 'true') {
|
||||
setIsSubmitted(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!email.trim()) {
|
||||
toast({
|
||||
title: "Email required",
|
||||
description: "Please enter your email address",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Basic email validation
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
toast({
|
||||
title: "Invalid email",
|
||||
description: "Please enter a valid email address",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
// Prepare form data
|
||||
const formData = new FormData();
|
||||
formData.append('email', email.trim());
|
||||
formData.append('tag_id', '8982396');
|
||||
|
||||
// Include npub if user is signed in
|
||||
if (user?.pubkey) {
|
||||
const npub = nip19.npubEncode(user.pubkey);
|
||||
formData.append('npub', npub);
|
||||
}
|
||||
|
||||
// Submit to Mailchimp using the same setup as soapbox2
|
||||
const form = document.createElement('form');
|
||||
form.method = 'POST';
|
||||
form.action = 'https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&id=f7271442a0&f_id=00ffa3e4f0';
|
||||
form.target = '_blank'; // Open in new tab
|
||||
form.style.display = 'none';
|
||||
|
||||
// Add email field
|
||||
const emailInput = document.createElement('input');
|
||||
emailInput.type = 'email';
|
||||
emailInput.name = 'EMAIL';
|
||||
emailInput.value = email.trim();
|
||||
form.appendChild(emailInput);
|
||||
|
||||
// Add tag field with the new Shakespeare tag ID
|
||||
const tagInput = document.createElement('input');
|
||||
tagInput.type = 'hidden';
|
||||
tagInput.name = 'tags';
|
||||
tagInput.value = '8982396';
|
||||
form.appendChild(tagInput);
|
||||
|
||||
// Add npub if available
|
||||
if (user?.pubkey) {
|
||||
const npubInput = document.createElement('input');
|
||||
npubInput.type = 'text';
|
||||
npubInput.name = 'NPUB';
|
||||
npubInput.value = nip19.npubEncode(user.pubkey);
|
||||
npubInput.style.display = 'none';
|
||||
form.appendChild(npubInput);
|
||||
}
|
||||
|
||||
// Add honeypot field
|
||||
const honeypotInput = document.createElement('input');
|
||||
honeypotInput.type = 'text';
|
||||
honeypotInput.name = 'b_f1f718a93795f42a604d558d8_f7271442a0';
|
||||
honeypotInput.tabIndex = -1;
|
||||
honeypotInput.style.position = 'absolute';
|
||||
honeypotInput.style.left = '-5000px';
|
||||
form.appendChild(honeypotInput);
|
||||
|
||||
// Add form to document and submit
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
|
||||
// Clean up after a short delay
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(form);
|
||||
}, 1000);
|
||||
|
||||
// Save subscription status to localStorage
|
||||
localStorage.setItem('shakespeare-email-subscribed', 'true');
|
||||
|
||||
setIsSubmitted(true);
|
||||
toast({
|
||||
title: "Successfully subscribed!",
|
||||
description: "You'll receive Shakespeare updates and resources occasionally.",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Email signup error:', error);
|
||||
toast({
|
||||
title: "Subscription failed",
|
||||
description: "There was an error subscribing you to updates. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isSubmitted) {
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
{isMobile && (
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => navigate('/settings')}
|
||||
className="h-8 w-auto px-2 -ml-2"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
{t('backToSettings')}
|
||||
</Button>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Mail className="h-6 w-6 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('emailUpdatesDescriptionLong')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isMobile && (
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Mail className="h-6 w-6 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('emailUpdatesDescriptionLong')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="max-w-md">
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="text-center space-y-4">
|
||||
<CheckCircle className="h-12 w-12 mx-auto text-green-500" />
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-lg font-semibold">
|
||||
Thanks for subscribing!
|
||||
</h3>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
You can opt out at any time using the unsubscribe link in our emails.
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Button
|
||||
onClick={() => navigate('/settings')}
|
||||
className="w-full"
|
||||
>
|
||||
Back to Settings
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
localStorage.removeItem('shakespeare-email-subscribed');
|
||||
setIsSubmitted(false);
|
||||
setEmail('');
|
||||
}}
|
||||
variant="outline"
|
||||
className="w-full text-xs"
|
||||
>
|
||||
Subscribe with different email
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
{isMobile && (
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => navigate('/settings')}
|
||||
className="h-8 w-auto px-2 -ml-2"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
{t('backToSettings')}
|
||||
</Button>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Mail className="h-6 w-6 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('emailUpdatesDescriptionLong')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isMobile && (
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Mail className="h-6 w-6 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('emailUpdatesDescriptionLong')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="max-w-md">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">
|
||||
Stay Updated with Shakespeare
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">
|
||||
Email Address
|
||||
</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="[email protected]"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
disabled={isSubmitting}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{isSubmitting ? 'Subscribing...' : 'Subscribe to Updates'}
|
||||
</Button>
|
||||
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
You can opt out at any time using the unsubscribe link in our emails.
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default EmailSettings;
|
||||
+47
-56
@@ -7,11 +7,11 @@ import { useFS } from '@/hooks/useFS';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { AppLayout } from '@/components/AppLayout';
|
||||
import { OnboardingDialog } from '@/components/OnboardingDialog';
|
||||
import { Act1Dialog } from '@/components/Act1Dialog';
|
||||
import { Quilly } from '@/components/Quilly';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import { saveFileToTmp } from '@/lib/fileUtils';
|
||||
import type OpenAI from 'openai';
|
||||
@@ -19,9 +19,9 @@ import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { ModelSelector } from '@/components/ModelSelector';
|
||||
import { FileAttachment } from '@/components/ui/file-attachment';
|
||||
import { ToastAction } from '@/components/ui/toast';
|
||||
import { Plus } from 'lucide-react';
|
||||
import { useSeoMeta } from '@unhead/react';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
|
||||
export default function Index() {
|
||||
const { t } = useTranslation();
|
||||
@@ -29,12 +29,12 @@ export default function Index() {
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [storedPrompt, setStoredPrompt] = useLocalStorage('shakespeare-draft-prompt', '');
|
||||
const [showOnboarding, setShowOnboarding] = useState(false);
|
||||
const [showAct1Dialog, setShowAct1Dialog] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
const projectsManager = useProjectsManager();
|
||||
const { fs } = useFS();
|
||||
const { generateProjectId, isLoading: isGeneratingId } = useAIProjectId();
|
||||
const { settings, addRecentlyUsedModel } = useAISettings();
|
||||
const { toast } = useToast();
|
||||
const [providerModel, setProviderModel] = useState(() => {
|
||||
// Initialize with first recently used model if available, otherwise empty
|
||||
return settings.recentlyUsedModels?.[0] || '';
|
||||
@@ -42,11 +42,45 @@ export default function Index() {
|
||||
const isMobile = useIsMobile();
|
||||
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
const [quillyError, setQuillyError] = useState<Error | null>(null);
|
||||
|
||||
// Check if any providers are configured
|
||||
const hasProvidersConfigured = settings.providers.length > 0;
|
||||
|
||||
// Check for API key failures and show appropriate toast
|
||||
const checkForKeyFailure = (error: unknown): boolean => {
|
||||
// Check for authentication errors
|
||||
// Note: useAIProjectId re-throws OpenAI errors as generic Error objects
|
||||
const isAuthError = error instanceof Error && error.message === '401 No auth credentials found';
|
||||
|
||||
if (isAuthError) {
|
||||
// Get provider name inline
|
||||
let providerName = 'Provider';
|
||||
try {
|
||||
const { provider } = parseProviderModel(providerModel, settings.providers);
|
||||
providerName = provider.id.charAt(0).toUpperCase() + provider.id.slice(1);
|
||||
} catch {
|
||||
// Keep default 'Provider'
|
||||
}
|
||||
|
||||
toast({
|
||||
title: t('apiAuthenticationFailed'),
|
||||
description: t('invalidApiKey', { provider: providerName }),
|
||||
variant: 'destructive',
|
||||
action: (
|
||||
<ToastAction
|
||||
altText={t('checkApiKeySettings')}
|
||||
onClick={() => navigate('/settings/ai')}
|
||||
>
|
||||
{t('checkApiKeySettings')}
|
||||
</ToastAction>
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
return isAuthError;
|
||||
};
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
if (!providerModel && settings.recentlyUsedModels?.length) {
|
||||
setProviderModel(settings.recentlyUsedModels[0]);
|
||||
@@ -65,13 +99,6 @@ export default function Index() {
|
||||
}
|
||||
}, [storedPrompt]);
|
||||
|
||||
// Check for Act 1 users and show welcome dialog
|
||||
useEffect(() => {
|
||||
if (localStorage.getItem('selectedNSPAddr')) {
|
||||
setShowAct1Dialog(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Sync prompt with local storage
|
||||
const handlePromptChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const newPrompt = e.target.value;
|
||||
@@ -160,27 +187,6 @@ export default function Index() {
|
||||
}
|
||||
};
|
||||
|
||||
// Quilly handlers
|
||||
const handleQuillyDismiss = () => {
|
||||
setQuillyError(null);
|
||||
};
|
||||
|
||||
const handleQuillyNewChat = () => {
|
||||
// Clear current prompt and start fresh
|
||||
setPrompt('');
|
||||
setStoredPrompt('');
|
||||
setAttachedFiles([]);
|
||||
setQuillyError(null);
|
||||
};
|
||||
|
||||
const handleQuillyOpenModelSelector = () => {
|
||||
// Focus on model selector or open AI settings if no providers
|
||||
if (!hasProvidersConfigured) {
|
||||
setShowOnboarding(true);
|
||||
}
|
||||
setQuillyError(null);
|
||||
};
|
||||
|
||||
const handleCreateProject = async () => {
|
||||
if (!prompt.trim() || !providerModel.trim()) return;
|
||||
|
||||
@@ -255,7 +261,13 @@ export default function Index() {
|
||||
navigate(`/project/${project.id}?${searchParams.toString()}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to create project:', error);
|
||||
setQuillyError(error instanceof Error ? error : new Error("An unexpected error occurred"));
|
||||
if (!checkForKeyFailure(error)) {
|
||||
toast({
|
||||
title: "Project Creation Failed",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
setIsCreating(false);
|
||||
}
|
||||
@@ -268,9 +280,7 @@ export default function Index() {
|
||||
<AppLayout headerContent={headerContent}>
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<div className="text-center mb-8 md:mb-12">
|
||||
<div className="mb-4 md:mb-6">
|
||||
<ShakespeareLogo className="w-20 h-20 md:w-24 md:h-24 mx-auto" />
|
||||
</div>
|
||||
<div className="text-4xl md:text-6xl mb-4 md:mb-6">🎭</div>
|
||||
<h1 className="text-3xl md:text-4xl font-bold mb-3 md:mb-4 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
{t('buildNostrApps')}
|
||||
</h1>
|
||||
@@ -280,19 +290,6 @@ export default function Index() {
|
||||
</div>
|
||||
|
||||
<div className="mb-8 md:mb-12">
|
||||
{/* Quilly Helper - shows when there are errors */}
|
||||
{quillyError && (
|
||||
<div className="mb-4">
|
||||
<Quilly
|
||||
error={quillyError}
|
||||
onDismiss={handleQuillyDismiss}
|
||||
onNewChat={handleQuillyNewChat}
|
||||
onOpenModelSelector={handleQuillyOpenModelSelector}
|
||||
providerModel={providerModel}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Chat Input Container - matching the ChatPane style */}
|
||||
<div
|
||||
className={`relative 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' : ''
|
||||
@@ -386,12 +383,6 @@ export default function Index() {
|
||||
open={showOnboarding}
|
||||
onOpenChange={setShowOnboarding}
|
||||
/>
|
||||
|
||||
{/* Act 1 Welcome Dialog */}
|
||||
<Act1Dialog
|
||||
open={showAct1Dialog}
|
||||
onOpenChange={setShowAct1Dialog}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -92,13 +92,15 @@ export function NostrSettings() {
|
||||
{isLoading ? (
|
||||
<div className="border rounded-lg overflow-hidden">
|
||||
{/* Loading skeleton for accounts */}
|
||||
<div className="flex items-center gap-3 p-3 border-b last:border-b-0">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="flex-1 space-y-1">
|
||||
<Skeleton className="h-4 w-32" />
|
||||
{[...Array(2)].map((_, i) => (
|
||||
<div key={i} className="flex items-center gap-3 p-3 border-b last:border-b-0">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="flex-1 space-y-1">
|
||||
<Skeleton className="h-4 w-32" />
|
||||
</div>
|
||||
<Skeleton className="h-8 w-8 rounded" />
|
||||
</div>
|
||||
<Skeleton className="h-8 w-8 rounded" />
|
||||
</div>
|
||||
))}
|
||||
{/* Add account button skeleton */}
|
||||
<div className="flex items-center gap-3 p-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
|
||||
+12
-29
@@ -18,7 +18,7 @@ import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
import { StarButton } from '@/components/StarButton';
|
||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable';
|
||||
import { clearConsoleMessages, ProjectPreviewConsoleError, addErrorListener, removeErrorListener } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { useConsole } from '@/contexts/ConsoleContext';
|
||||
|
||||
export function ProjectView() {
|
||||
const { projectId } = useParams<{ projectId: string }>();
|
||||
@@ -29,12 +29,12 @@ export function ProjectView() {
|
||||
const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat');
|
||||
const [isAILoading, setIsAILoading] = useState(false);
|
||||
const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false);
|
||||
const [consoleError, setConsoleError] = useState<ProjectPreviewConsoleError | null>(null);
|
||||
|
||||
const projectsManager = useProjectsManager();
|
||||
const chatPaneRef = useRef<ChatPaneRef>(null);
|
||||
const navigate = useNavigate();
|
||||
const isMobile = useIsMobile();
|
||||
const { clearMessages: clearConsoleMessages } = useConsole();
|
||||
|
||||
const [isSidebarVisible, setIsSidebarVisible] = useState(!isMobile);
|
||||
|
||||
@@ -47,15 +47,14 @@ export function ProjectView() {
|
||||
try {
|
||||
const projectData = await projectsManager.getProject(projectId);
|
||||
setProject(projectData);
|
||||
// Clear console messages and error state when switching projects
|
||||
// Clear console messages when switching projects
|
||||
clearConsoleMessages();
|
||||
setConsoleError(null);
|
||||
} catch (error) {
|
||||
console.error('Failed to load project:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [projectId, projectsManager]);
|
||||
}, [projectId, projectsManager, clearConsoleMessages]);
|
||||
|
||||
useEffect(() => {
|
||||
loadProject();
|
||||
@@ -81,16 +80,6 @@ export function ProjectView() {
|
||||
}
|
||||
}, [isPreviewable, mobileView, activeTab]);
|
||||
|
||||
// Global console error listener (always active regardless of current tab)
|
||||
useEffect(() => {
|
||||
const handleConsoleError = (error: ProjectPreviewConsoleError) => {
|
||||
setConsoleError(error);
|
||||
};
|
||||
|
||||
addErrorListener(handleConsoleError);
|
||||
return () => removeErrorListener(handleConsoleError);
|
||||
}, []);
|
||||
|
||||
const handleNewChat = () => {
|
||||
// Reset to chat view on mobile when starting new chat
|
||||
if (isMobile) {
|
||||
@@ -112,10 +101,6 @@ export function ProjectView() {
|
||||
// when isAILoading becomes true after user interaction
|
||||
};
|
||||
|
||||
const handleDismissConsoleError = () => {
|
||||
setConsoleError(null);
|
||||
};
|
||||
|
||||
const handleProjectDeleted = async () => {
|
||||
setProject(null);
|
||||
navigate('/');
|
||||
@@ -137,7 +122,7 @@ export function ProjectView() {
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<div className="h-dvh flex flex-col bg-background safe-area-inset-top">
|
||||
<div className="h-dvh flex flex-col bg-background">
|
||||
<header className="overflow-hidden border-b bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur supports-[backdrop-filter]:bg-gradient-to-r supports-[backdrop-filter]:from-primary/10 supports-[backdrop-filter]:via-accent/5 supports-[backdrop-filter]:to-primary/10 px-4 py-3 flex items-center justify-between">
|
||||
<div className="flex items-center space-x-2 overflow-hidden">
|
||||
<Button
|
||||
@@ -228,8 +213,6 @@ export function ProjectView() {
|
||||
onLoadingChange={handleAILoadingChange}
|
||||
isLoading={isAILoading}
|
||||
isBuildLoading={build.isPending}
|
||||
consoleError={consoleError}
|
||||
onDismissConsoleError={handleDismissConsoleError}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full p-4 space-y-4">
|
||||
@@ -257,13 +240,13 @@ export function ProjectView() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="border-t bg-gradient-to-r from-primary/5 via-background to-accent/5 backdrop-blur safe-area-inset-bottom">
|
||||
<div className="border-t bg-gradient-to-r from-primary/5 via-background to-accent/5 backdrop-blur">
|
||||
<div className="flex">
|
||||
<Button
|
||||
variant="ghost"
|
||||
variant={mobileView === 'chat' ? 'default' : 'ghost'}
|
||||
size="sm"
|
||||
onClick={() => setMobileView('chat')}
|
||||
className={`flex-1 rounded-none mobile-nav-button ${mobileView === 'chat' ? 'mobile-nav-button-active' : ''}`}
|
||||
className="flex-1 rounded-none"
|
||||
disabled={!project}
|
||||
>
|
||||
<MessageSquare className="h-4 w-4 mr-1" />
|
||||
@@ -271,10 +254,10 @@ export function ProjectView() {
|
||||
</Button>
|
||||
{isPreviewable && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
variant={mobileView === 'preview' ? 'default' : 'ghost'}
|
||||
size="sm"
|
||||
onClick={() => setMobileView('preview')}
|
||||
className={`flex-1 rounded-none mobile-nav-button ${mobileView === 'preview' ? 'mobile-nav-button-active' : ''}`}
|
||||
className="flex-1 rounded-none"
|
||||
disabled={!project}
|
||||
>
|
||||
<Eye className="h-4 w-4 mr-1" />
|
||||
@@ -282,10 +265,10 @@ export function ProjectView() {
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
variant={mobileView === 'code' ? 'default' : 'ghost'}
|
||||
size="sm"
|
||||
onClick={() => setMobileView('code')}
|
||||
className={`flex-1 rounded-none mobile-nav-button ${mobileView === 'code' ? 'mobile-nav-button-active' : ''}`}
|
||||
className="flex-1 rounded-none"
|
||||
disabled={!project}
|
||||
>
|
||||
<Code className="h-4 w-4 mr-1" />
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react';
|
||||
import { Bot, GitBranch, Database, Wifi, Settings2, Info, Mail } from 'lucide-react';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
|
||||
interface SettingsItem {
|
||||
@@ -48,6 +48,13 @@ const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [
|
||||
icon: Database,
|
||||
href: '/settings/data',
|
||||
},
|
||||
{
|
||||
id: 'email',
|
||||
title: t('emailUpdates'),
|
||||
description: t('emailUpdatesDescription'),
|
||||
icon: Mail,
|
||||
href: '/settings/email',
|
||||
},
|
||||
{
|
||||
id: 'about',
|
||||
title: t('aboutShakespeare'),
|
||||
|
||||
+16
-13
@@ -7,6 +7,7 @@ import NostrProvider from '@/components/NostrProvider';
|
||||
import { AppProvider } from '@/components/AppProvider';
|
||||
import { AppConfig } from '@/contexts/AppContext';
|
||||
import { FSProvider } from '@/components/FSProvider';
|
||||
import { ConsoleProvider } from '@/contexts/ConsoleContext';
|
||||
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
|
||||
import { AISettingsProvider } from '@/components/AISettingsProvider';
|
||||
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
|
||||
@@ -43,19 +44,21 @@ export function TestApp({ children }: TestAppProps) {
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AppProvider storageKey='test-app-config' defaultConfig={defaultConfig}>
|
||||
<FSProvider fs={fs}>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<NostrLoginProvider storageKey='test-login'>
|
||||
<NostrProvider>
|
||||
<SessionManagerProvider>
|
||||
<BrowserRouter>
|
||||
{children}
|
||||
</BrowserRouter>
|
||||
</SessionManagerProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
<ConsoleProvider>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<NostrLoginProvider storageKey='test-login'>
|
||||
<NostrProvider>
|
||||
<SessionManagerProvider>
|
||||
<BrowserRouter>
|
||||
{children}
|
||||
</BrowserRouter>
|
||||
</SessionManagerProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</ConsoleProvider>
|
||||
</FSProvider>
|
||||
</AppProvider>
|
||||
</QueryClientProvider>
|
||||
|
||||
Reference in new issue
Block a user