mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 08:23:34 +00:00
Compare commits
73
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
525c525f3b | ||
|
|
a03d3c2e31 | ||
|
|
ca1d73be11 | ||
|
|
6f17774309 | ||
|
|
ca334d7585 | ||
|
|
57a80ad33d | ||
|
|
a05ad13e67 | ||
|
|
247919a24b | ||
|
|
9b43f07372 | ||
|
|
af8fb22438 | ||
|
|
fc4e82c26d | ||
|
|
3b305b5b86 | ||
|
|
456ea946e7 | ||
|
|
6c770630d8 | ||
|
|
8f4598b9b8 | ||
|
|
64c06ec430 | ||
|
|
29aae4f55b | ||
|
|
fb12bda5fa | ||
|
|
7348aaf9ce | ||
|
|
8948507b6f | ||
|
|
2dbb9a23e3 | ||
|
|
11867b3bb2 | ||
|
|
0f82ab15ec | ||
|
|
80ae098323 | ||
|
|
fa64a5ce52 | ||
|
|
870e2f6b9b | ||
|
|
26c09733f8 | ||
|
|
2a80e586ba | ||
|
|
9f20fd6196 | ||
|
|
94bcc7eccb | ||
|
|
f62b2f807c | ||
|
|
374d2804ad | ||
|
|
c0f906ae7e | ||
|
|
92e2ac1ce5 | ||
|
|
e81fb33ffe | ||
|
|
9a65d5d086 | ||
|
|
61d5a5fefc | ||
|
|
75e961d281 | ||
|
|
93e992f128 | ||
|
|
7ab30af944 | ||
|
|
6296fc4366 | ||
|
|
147c7cdf3a | ||
|
|
18a276a44e | ||
|
|
a20bbfdf29 | ||
|
|
980cb60f1b | ||
|
|
2956c86f88 | ||
|
|
c46077af67 | ||
|
|
ad5902cdc6 | ||
|
|
ce4a602270 | ||
|
|
5e352e60e9 | ||
|
|
37147a69d4 | ||
|
|
4f9d3ae1d1 | ||
|
|
fdfdcb4b16 | ||
|
|
50e16e1b57 | ||
|
|
662f95d35d | ||
|
|
458eec0e27 | ||
|
|
74e472338d | ||
|
|
2b5e3013ff | ||
|
|
951eefb7b8 | ||
|
|
a68d37452b | ||
|
|
c8653e67dc | ||
|
|
660f25656c | ||
|
|
804efb4d23 | ||
|
|
8108407478 | ||
|
|
adeb3bf53f | ||
|
|
588e32a43d | ||
|
|
57e12261af | ||
|
|
797984c5d3 | ||
|
|
6d49648580 | ||
|
|
4d6bc91650 | ||
|
|
2fdf8a3740 | ||
|
|
f4ccc2d924 | ||
|
|
6f4aa264eb |
No files matched your search
@@ -51,6 +51,7 @@ Shakespeare provides AI agents with specialized tools for project development (n
|
|||||||
- **NostrReadNipsIndexTool**: Read the full list of NIPs, kinds, and tags
|
- **NostrReadNipsIndexTool**: Read the full list of NIPs, kinds, and tags
|
||||||
- **NostrFetchEventTool**: Fetch Nostr events using NIP-19 identifiers
|
- **NostrFetchEventTool**: Fetch Nostr events using NIP-19 identifiers
|
||||||
- **NostrGenerateKindTool**: Generate unused Nostr event kind numbers
|
- **NostrGenerateKindTool**: Generate unused Nostr event kind numbers
|
||||||
|
- **ReadConsoleMessagesTool**: Read console messages from project preview with filtering capabilities
|
||||||
|
|
||||||
#### Shell Commands
|
#### Shell Commands
|
||||||
|
|
||||||
@@ -168,6 +169,8 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
|||||||
- `/src/components/ai/`: AI-related components (GitCommit, GitHistoryDialog)
|
- `/src/components/ai/`: AI-related components (GitCommit, GitHistoryDialog)
|
||||||
- `/src/components/comments/`: Comment system components (Comment, CommentForm, CommentsSection)
|
- `/src/components/comments/`: Comment system components (Comment, CommentForm, CommentsSection)
|
||||||
- `/src/components/Shakespeare/`: Core Shakespeare editor components (ChatPane, FileEditor, FileTree, PreviewPane)
|
- `/src/components/Shakespeare/`: Core Shakespeare editor components (ChatPane, FileEditor, FileTree, PreviewPane)
|
||||||
|
- `/src/components/ProjectSidebar.tsx`: Sidebar component containing project list and import options
|
||||||
|
- `/src/components/ZipImportDialog.tsx`: Dialog component for importing projects from ZIP files
|
||||||
- Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments
|
- Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments
|
||||||
- `/src/hooks/`: Custom hooks including:
|
- `/src/hooks/`: Custom hooks including:
|
||||||
- `useNostr`: Core Nostr protocol integration
|
- `useNostr`: Core Nostr protocol integration
|
||||||
@@ -182,7 +185,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
|||||||
- `useSessionManager`: Access session management for AI chat sessions
|
- `useSessionManager`: Access session management for AI chat sessions
|
||||||
- `useGitStatus`: Real-time Git repository status monitoring
|
- `useGitStatus`: Real-time Git repository status monitoring
|
||||||
- `useProjects`: Project management and CRUD operations
|
- `useProjects`: Project management and CRUD operations
|
||||||
- `useProjectsManager`: Advanced project operations (creation, cloning, building)
|
- `useProjectsManager`: Advanced project operations (creation, cloning, building, ZIP import)
|
||||||
- `useTheme`: Theme management
|
- `useTheme`: Theme management
|
||||||
- `useToast`: Toast notifications
|
- `useToast`: Toast notifications
|
||||||
- `useLocalStorage`: Persistent local storage
|
- `useLocalStorage`: Persistent local storage
|
||||||
|
|||||||
+2
-2
@@ -2,13 +2,13 @@
|
|||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
|
||||||
<title>Shakespeare - AI-Powered Nostr Development</title>
|
<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 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:type" content="website">
|
||||||
<meta property="og:title" content="Shakespeare - AI-Powered Nostr Development">
|
<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 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'; 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:"> -->
|
<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="/favicon.png">
|
<link rel="icon" type="image/png" href="/favicon.png">
|
||||||
<link rel="manifest" href="/manifest.webmanifest">
|
<link rel="manifest" href="/manifest.webmanifest">
|
||||||
</head>
|
</head>
|
||||||
|
|||||||
@@ -1,35 +1,45 @@
|
|||||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
|
||||||
Version 3, 19 November 2007
|
<!-- 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">
|
||||||
|
|
||||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
<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>
|
||||||
|
|
||||||
|
<p>Copyright © 2007 Free Software Foundation,
|
||||||
|
Inc. <<a href="https://fsf.org/">https://fsf.org/</a>>
|
||||||
|
<br>
|
||||||
Everyone is permitted to copy and distribute verbatim copies
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
of this license document, but changing it is not allowed.
|
of this license document, but changing it is not allowed.</p>
|
||||||
|
|
||||||
Preamble
|
<h4 id="preamble">Preamble</h4>
|
||||||
|
|
||||||
The GNU Affero General Public License is a free, copyleft license for
|
<p>The GNU Affero General Public License is a free, copyleft license
|
||||||
software and other kinds of works, specifically designed to ensure
|
for software and other kinds of works, specifically designed to ensure
|
||||||
cooperation with the community in the case of network server software.
|
cooperation with the community in the case of network server software.</p>
|
||||||
|
|
||||||
The licenses for most software and other practical works are designed
|
<p>The licenses for most software and other practical works are
|
||||||
to take away your freedom to share and change the works. By contrast,
|
designed to take away your freedom to share and change the works. By
|
||||||
our General Public Licenses are intended to guarantee your freedom to
|
contrast, our General Public Licenses are intended to guarantee your
|
||||||
share and change all versions of a program--to make sure it remains free
|
freedom to share and change all versions of a program--to make sure it
|
||||||
software for all its users.
|
remains free software for all its users.</p>
|
||||||
|
|
||||||
When we speak of free software, we are referring to freedom, not
|
<p>When we speak of free software, we are referring to freedom, not
|
||||||
price. Our General Public Licenses are designed to make sure that you
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
have the freedom to distribute copies of free software (and charge for
|
have the freedom to distribute copies of free software (and charge for
|
||||||
them if you wish), that you receive source code or can get it if you
|
them if you wish), that you receive source code or can get it if you
|
||||||
want it, that you can change the software or use pieces of it in new
|
want it, that you can change the software or use pieces of it in new
|
||||||
free programs, and that you know you can do these things.
|
free programs, and that you know you can do these things.</p>
|
||||||
|
|
||||||
Developers that use our General Public Licenses protect your rights
|
<p>Developers that use our General Public Licenses protect your rights
|
||||||
with two steps: (1) assert copyright on the software, and (2) offer
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
you this License which gives you legal permission to copy, distribute
|
you this License which gives you legal permission to copy, distribute
|
||||||
and/or modify the software.
|
and/or modify the software.</p>
|
||||||
|
|
||||||
A secondary benefit of defending all users' freedom is that
|
<p>A secondary benefit of defending all users' freedom is that
|
||||||
improvements made in alternate versions of the program, if they
|
improvements made in alternate versions of the program, if they
|
||||||
receive widespread use, become available for other developers to
|
receive widespread use, become available for other developers to
|
||||||
incorporate. Many developers of free software are heartened and
|
incorporate. Many developers of free software are heartened and
|
||||||
@@ -37,78 +47,79 @@ encouraged by the resulting cooperation. However, in the case of
|
|||||||
software used on network servers, this result may fail to come about.
|
software used on network servers, this result may fail to come about.
|
||||||
The GNU General Public License permits making a modified version and
|
The GNU General Public License permits making a modified version and
|
||||||
letting the public access it on a server without ever releasing its
|
letting the public access it on a server without ever releasing its
|
||||||
source code to the public.
|
source code to the public.</p>
|
||||||
|
|
||||||
The GNU Affero General Public License is designed specifically to
|
<p>The GNU Affero General Public License is designed specifically to
|
||||||
ensure that, in such cases, the modified source code becomes available
|
ensure that, in such cases, the modified source code becomes available
|
||||||
to the community. It requires the operator of a network server to
|
to the community. It requires the operator of a network server to
|
||||||
provide the source code of the modified version running there to the
|
provide the source code of the modified version running there to the
|
||||||
users of that server. Therefore, public use of a modified version, on
|
users of that server. Therefore, public use of a modified version, on
|
||||||
a publicly accessible server, gives the public access to the source
|
a publicly accessible server, gives the public access to the source
|
||||||
code of the modified version.
|
code of the modified version.</p>
|
||||||
|
|
||||||
An older license, called the Affero General Public License and
|
<p>An older license, called the Affero General Public License and
|
||||||
published by Affero, was designed to accomplish similar goals. This is
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
a different license, not a version of the Affero GPL, but Affero has
|
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
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
this license.
|
this license.</p>
|
||||||
|
|
||||||
The precise terms and conditions for copying, distribution and
|
<p>The precise terms and conditions for copying, distribution and
|
||||||
modification follow.
|
modification follow.</p>
|
||||||
|
|
||||||
TERMS AND CONDITIONS
|
<h4 id="terms">TERMS AND CONDITIONS</h4>
|
||||||
|
|
||||||
0. Definitions.
|
<h4 id="section0">0. Definitions.</h4>
|
||||||
|
|
||||||
"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
|
<p>"Copyright" also means copyright-like laws that apply to other kinds
|
||||||
works, such as semiconductor masks.
|
of works, such as semiconductor masks.</p>
|
||||||
|
|
||||||
"The Program" refers to any copyrightable work licensed under this
|
<p>"The Program" refers to any copyrightable work licensed under this
|
||||||
License. Each licensee is addressed as "you". "Licensees" and
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
"recipients" may be individuals or organizations.
|
"recipients" may be individuals or organizations.</p>
|
||||||
|
|
||||||
To "modify" a work means to copy from or adapt all or part of the work
|
<p>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
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
exact copy. The resulting work is called a "modified version" of the
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
earlier work or a work "based on" the earlier work.
|
earlier work or a work "based on" the earlier work.</p>
|
||||||
|
|
||||||
A "covered work" means either the unmodified Program or a work based
|
<p>A "covered work" means either the unmodified Program or a work based
|
||||||
on the Program.
|
on the Program.</p>
|
||||||
|
|
||||||
To "propagate" a work means to do anything with it that, without
|
<p>To "propagate" a work means to do anything with it that, without
|
||||||
permission, would make you directly or secondarily liable for
|
permission, would make you directly or secondarily liable for
|
||||||
infringement under applicable copyright law, except executing it on a
|
infringement under applicable copyright law, except executing it on a
|
||||||
computer or modifying a private copy. Propagation includes copying,
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
distribution (with or without modification), making available to the
|
distribution (with or without modification), making available to the
|
||||||
public, and in some countries other activities as well.
|
public, and in some countries other activities as well.</p>
|
||||||
|
|
||||||
To "convey" a work means any kind of propagation that enables other
|
<p>To "convey" a work means any kind of propagation that enables other
|
||||||
parties to make or receive copies. Mere interaction with a user through
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
a computer network, with no transfer of a copy, is not conveying.
|
a computer network, with no transfer of a copy, is not conveying.</p>
|
||||||
|
|
||||||
An interactive user interface displays "Appropriate Legal Notices"
|
<p>An interactive user interface displays "Appropriate Legal Notices"
|
||||||
to the extent that it includes a convenient and prominently visible
|
to the extent that it includes a convenient and prominently visible
|
||||||
feature that (1) displays an appropriate copyright notice, and (2)
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
tells the user that there is no warranty for the work (except to the
|
tells the user that there is no warranty for the work (except to the
|
||||||
extent that warranties are provided), that licensees may convey 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
|
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
|
the interface presents a list of user commands or options, such as a
|
||||||
menu, a prominent item in the list meets this criterion.
|
menu, a prominent item in the list meets this criterion.</p>
|
||||||
|
|
||||||
1. Source Code.
|
<h4 id="section1">1. Source Code.</h4>
|
||||||
|
|
||||||
The "source code" for a work means the preferred form of the work
|
<p>The "source code" for a work means the preferred form of the work
|
||||||
for making modifications to it. "Object code" means any non-source
|
for making modifications to it. "Object code" means any non-source
|
||||||
form of a work.
|
form of a work.</p>
|
||||||
|
|
||||||
A "Standard Interface" means an interface that either is an official
|
<p>A "Standard Interface" means an interface that either is an official
|
||||||
standard defined by a recognized standards body, or, in the case of
|
standard defined by a recognized standards body, or, in the case of
|
||||||
interfaces specified for a particular programming language, one that
|
interfaces specified for a particular programming language, one that
|
||||||
is widely used among developers working in that language.
|
is widely used among developers working in that language.</p>
|
||||||
|
|
||||||
The "System Libraries" of an executable work include anything, other
|
<p>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
|
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
|
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
|
Component, and (b) serves only to enable use of the work with that
|
||||||
@@ -117,9 +128,9 @@ implementation is available to the public in source code form. A
|
|||||||
"Major Component", in this context, means a major essential component
|
"Major Component", in this context, means a major essential component
|
||||||
(kernel, window system, and so on) of the specific operating system
|
(kernel, window system, and so on) of the specific operating system
|
||||||
(if any) on which the executable work runs, or a compiler used to
|
(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.
|
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
|
<p>The "Corresponding Source" for a work in object code form means all
|
||||||
the source code needed to generate, install, and (for an executable
|
the source code needed to generate, install, and (for an executable
|
||||||
work) run the object code and to modify the work, including scripts to
|
work) run the object code and to modify the work, including scripts to
|
||||||
control those activities. However, it does not include the work's
|
control those activities. However, it does not include the work's
|
||||||
@@ -130,26 +141,26 @@ includes interface definition files associated with source files for
|
|||||||
the work, and the source code for shared libraries and dynamically
|
the work, and the source code for shared libraries and dynamically
|
||||||
linked subprograms that the work is specifically designed to require,
|
linked subprograms that the work is specifically designed to require,
|
||||||
such as by intimate data communication or control flow between those
|
such as by intimate data communication or control flow between those
|
||||||
subprograms and other parts of the work.
|
subprograms and other parts of the work.</p>
|
||||||
|
|
||||||
The Corresponding Source need not include anything that users
|
<p>The Corresponding Source need not include anything that users
|
||||||
can regenerate automatically from other parts of the Corresponding
|
can regenerate automatically from other parts of the Corresponding
|
||||||
Source.
|
Source.</p>
|
||||||
|
|
||||||
The Corresponding Source for a work in source code form is that
|
<p>The Corresponding Source for a work in source code form is that
|
||||||
same work.
|
same work.</p>
|
||||||
|
|
||||||
2. Basic Permissions.
|
<h4 id="section2">2. Basic Permissions.</h4>
|
||||||
|
|
||||||
All rights granted under this License are granted for the term of
|
<p>All rights granted under this License are granted for the term of
|
||||||
copyright on the Program, and are irrevocable provided the stated
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
conditions are met. This License explicitly affirms your unlimited
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
permission to run the unmodified Program. The output from running a
|
permission to run the unmodified Program. The output from running a
|
||||||
covered work is covered by this License only if the output, given its
|
covered work is covered by this License only if the output, given its
|
||||||
content, constitutes a covered work. This License acknowledges your
|
content, constitutes a covered work. This License acknowledges your
|
||||||
rights of fair use or other equivalent, as provided by copyright law.
|
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
|
<p>You may make, run and propagate covered works that you do not
|
||||||
convey, without conditions so long as your license otherwise remains
|
convey, without conditions so long as your license otherwise remains
|
||||||
in force. You may convey covered works to others for the sole purpose
|
in force. You may convey covered works to others for the sole purpose
|
||||||
of having them make modifications exclusively for you, or provide you
|
of having them make modifications exclusively for you, or provide you
|
||||||
@@ -158,69 +169,73 @@ the terms of this License in conveying all material for which you do
|
|||||||
not control copyright. Those thus making or running the covered works
|
not control copyright. Those thus making or running the covered works
|
||||||
for you must do so exclusively on your behalf, under your direction
|
for you must do so exclusively on your behalf, under your direction
|
||||||
and control, on terms that prohibit them from making any copies of
|
and control, on terms that prohibit them from making any copies of
|
||||||
your copyrighted material outside their relationship with you.
|
your copyrighted material outside their relationship with you.</p>
|
||||||
|
|
||||||
Conveying under any other circumstances is permitted solely under
|
<p>Conveying under any other circumstances is permitted solely under
|
||||||
the conditions stated below. Sublicensing is not allowed; section 10
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
makes it unnecessary.
|
makes it unnecessary.</p>
|
||||||
|
|
||||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
<h4 id="section3">3. Protecting Users' Legal Rights From Anti-Circumvention Law.</h4>
|
||||||
|
|
||||||
No covered work shall be deemed part of an effective technological
|
<p>No covered work shall be deemed part of an effective technological
|
||||||
measure under any applicable law fulfilling obligations under article
|
measure under any applicable law fulfilling obligations under article
|
||||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
similar laws prohibiting or restricting circumvention of such
|
similar laws prohibiting or restricting circumvention of such
|
||||||
measures.
|
measures.</p>
|
||||||
|
|
||||||
When you convey a covered work, you waive any legal power to forbid
|
<p>When you convey a covered work, you waive any legal power to forbid
|
||||||
circumvention of technological measures to the extent such circumvention
|
circumvention of technological measures to the extent such circumvention
|
||||||
is effected by exercising rights under this License with respect to
|
is effected by exercising rights under this License with respect to
|
||||||
the covered work, and you disclaim any intention to limit operation or
|
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
|
modification of the work as a means of enforcing, against the work's
|
||||||
users, your or third parties' legal rights to forbid circumvention of
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
technological measures.
|
technological measures.</p>
|
||||||
|
|
||||||
4. Conveying Verbatim Copies.
|
<h4 id="section4">4. Conveying Verbatim Copies.</h4>
|
||||||
|
|
||||||
You may convey verbatim copies of the Program's source code as you
|
<p>You may convey verbatim copies of the Program's source code as you
|
||||||
receive it, in any medium, provided that you conspicuously and
|
receive it, in any medium, provided that you conspicuously and
|
||||||
appropriately publish on each copy an appropriate copyright notice;
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
keep intact all notices stating that this License and any
|
keep intact all notices stating that this License and any
|
||||||
non-permissive terms added in accord with section 7 apply to the code;
|
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
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
recipients a copy of this License along with the Program.
|
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,
|
<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.
|
and you may offer support or warranty protection for a fee.</p>
|
||||||
|
|
||||||
5. Conveying Modified Source Versions.
|
<h4 id="section5">5. Conveying Modified Source Versions.</h4>
|
||||||
|
|
||||||
You may convey a work based on the Program, or the modifications to
|
<p>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
|
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:
|
terms of section 4, provided that you also meet all of these conditions:</p>
|
||||||
|
|
||||||
a) The work must carry prominent notices stating that you modified
|
<ul>
|
||||||
it, and giving a relevant date.
|
|
||||||
|
|
||||||
b) The work must carry prominent notices stating that it is
|
<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
|
||||||
released under this License and any conditions added under section
|
released under this License and any conditions added under section
|
||||||
7. This requirement modifies the requirement in section 4 to
|
7. This requirement modifies the requirement in section 4 to
|
||||||
"keep intact all notices".
|
"keep intact all notices".</li>
|
||||||
|
|
||||||
c) You must license the entire work, as a whole, under this
|
<li>c) You must license the entire work, as a whole, under this
|
||||||
License to anyone who comes into possession of a copy. This
|
License to anyone who comes into possession of a copy. This
|
||||||
License will therefore apply, along with any applicable section 7
|
License will therefore apply, along with any applicable section 7
|
||||||
additional terms, to the whole of the work, and all its parts,
|
additional terms, to the whole of the work, and all its parts,
|
||||||
regardless of how they are packaged. This License gives no
|
regardless of how they are packaged. This License gives no
|
||||||
permission to license the work in any other way, but it does not
|
permission to license the work in any other way, but it does not
|
||||||
invalidate such permission if you have separately received it.
|
invalidate such permission if you have separately received it.</li>
|
||||||
|
|
||||||
d) If the work has interactive user interfaces, each must display
|
<li>d) If the work has interactive user interfaces, each must display
|
||||||
Appropriate Legal Notices; however, if the Program has interactive
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
interfaces that do not display Appropriate Legal Notices, your
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
work need not make them do so.
|
work need not make them do so.</li>
|
||||||
|
|
||||||
A compilation of a covered work with other separate and independent
|
</ul>
|
||||||
|
|
||||||
|
<p>A compilation of a covered work with other separate and independent
|
||||||
works, which are not by their nature extensions of the covered work,
|
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,
|
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
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
@@ -228,21 +243,23 @@ 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
|
used to limit the access or legal rights of the compilation's users
|
||||||
beyond what the individual works permit. Inclusion of a covered work
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
in an aggregate does not cause this License to apply to the other
|
in an aggregate does not cause this License to apply to the other
|
||||||
parts of the aggregate.
|
parts of the aggregate.</p>
|
||||||
|
|
||||||
6. Conveying Non-Source Forms.
|
<h4 id="section6">6. Conveying Non-Source Forms.</h4>
|
||||||
|
|
||||||
You may convey a covered work in object code form under the terms
|
<p>You may convey a covered work in object code form under the terms
|
||||||
of sections 4 and 5, provided that you also convey the
|
of sections 4 and 5, provided that you also convey the
|
||||||
machine-readable Corresponding Source under the terms of this License,
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
in one of these ways:
|
in one of these ways:</p>
|
||||||
|
|
||||||
a) Convey the object code in, or embodied in, a physical product
|
<ul>
|
||||||
|
|
||||||
|
<li>a) Convey the object code in, or embodied in, a physical product
|
||||||
(including a physical distribution medium), accompanied by the
|
(including a physical distribution medium), accompanied by the
|
||||||
Corresponding Source fixed on a durable physical medium
|
Corresponding Source fixed on a durable physical medium
|
||||||
customarily used for software interchange.
|
customarily used for software interchange.</li>
|
||||||
|
|
||||||
b) Convey the object code in, or embodied in, a physical product
|
<li>b) Convey the object code in, or embodied in, a physical product
|
||||||
(including a physical distribution medium), accompanied by a
|
(including a physical distribution medium), accompanied by a
|
||||||
written offer, valid for at least three years and valid for as
|
written offer, valid for at least three years and valid for as
|
||||||
long as you offer spare parts or customer support for that product
|
long as you offer spare parts or customer support for that product
|
||||||
@@ -252,15 +269,15 @@ in one of these ways:
|
|||||||
medium customarily used for software interchange, for a price no
|
medium customarily used for software interchange, for a price no
|
||||||
more than your reasonable cost of physically performing this
|
more than your reasonable cost of physically performing this
|
||||||
conveying of source, or (2) access to copy the
|
conveying of source, or (2) access to copy the
|
||||||
Corresponding Source from a network server at no charge.
|
Corresponding Source from a network server at no charge.</li>
|
||||||
|
|
||||||
c) Convey individual copies of the object code with a copy of the
|
<li>c) Convey individual copies of the object code with a copy of the
|
||||||
written offer to provide the Corresponding Source. This
|
written offer to provide the Corresponding Source. This
|
||||||
alternative is allowed only occasionally and noncommercially, and
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
only if you received the object code with such an offer, in accord
|
only if you received the object code with such an offer, in accord
|
||||||
with subsection 6b.
|
with subsection 6b.</li>
|
||||||
|
|
||||||
d) Convey the object code by offering access from a designated
|
<li>d) Convey the object code by offering access from a designated
|
||||||
place (gratis or for a charge), and offer equivalent access to the
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
Corresponding Source in the same way through the same place at no
|
Corresponding Source in the same way through the same place at no
|
||||||
further charge. You need not require recipients to copy the
|
further charge. You need not require recipients to copy the
|
||||||
@@ -271,18 +288,20 @@ in one of these ways:
|
|||||||
clear directions next to the object code saying where to find the
|
clear directions next to the object code saying where to find the
|
||||||
Corresponding Source. Regardless of what server hosts the
|
Corresponding Source. Regardless of what server hosts the
|
||||||
Corresponding Source, you remain obligated to ensure that it is
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
available for as long as needed to satisfy these requirements.
|
available for as long as needed to satisfy these requirements.</li>
|
||||||
|
|
||||||
e) Convey the object code using peer-to-peer transmission, provided
|
<li>e) Convey the object code using peer-to-peer transmission, provided
|
||||||
you inform other peers where the object code and Corresponding
|
you inform other peers where the object code and Corresponding
|
||||||
Source of the work are being offered to the general public at no
|
Source of the work are being offered to the general public at no
|
||||||
charge under subsection 6d.
|
charge under subsection 6d.</li>
|
||||||
|
|
||||||
A separable portion of the object code, whose source code is excluded
|
</ul>
|
||||||
|
|
||||||
|
<p>A separable portion of the object code, whose source code is excluded
|
||||||
from the Corresponding Source as a System Library, need not be
|
from the Corresponding Source as a System Library, need not be
|
||||||
included in conveying the object code work.
|
included in conveying the object code work.</p>
|
||||||
|
|
||||||
A "User Product" is either (1) a "consumer product", which means any
|
<p>A "User Product" is either (1) a "consumer product", which means any
|
||||||
tangible personal property which is normally used for personal, family,
|
tangible personal property which is normally used for personal, family,
|
||||||
or household purposes, or (2) anything designed or sold for incorporation
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
into a dwelling. In determining whether a product is a consumer product,
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
@@ -293,17 +312,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
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
is a consumer product regardless of whether the product has substantial
|
is a consumer product regardless of whether the product has substantial
|
||||||
commercial, industrial or non-consumer uses, unless such uses represent
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
the only significant mode of use of the product.
|
the only significant mode of use of the product.</p>
|
||||||
|
|
||||||
"Installation Information" for a User Product means any methods,
|
<p>"Installation Information" for a User Product means any methods,
|
||||||
procedures, authorization keys, or other information required to install
|
procedures, authorization keys, or other information required to install
|
||||||
and execute modified versions of a covered work in that User Product from
|
and execute modified versions of a covered work in that User Product from
|
||||||
a modified version of its Corresponding Source. The information must
|
a modified version of its Corresponding Source. The information must
|
||||||
suffice to ensure that the continued functioning of the modified object
|
suffice to ensure that the continued functioning of the modified object
|
||||||
code is in no case prevented or interfered with solely because
|
code is in no case prevented or interfered with solely because
|
||||||
modification has been made.
|
modification has been made.</p>
|
||||||
|
|
||||||
If you convey an object code work under this section in, or with, or
|
<p>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
|
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
|
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
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
@@ -312,133 +331,137 @@ Corresponding Source conveyed under this section must be accompanied
|
|||||||
by the Installation Information. But this requirement does not apply
|
by the Installation Information. But this requirement does not apply
|
||||||
if neither you nor any third party retains the ability to install
|
if neither you nor any third party retains the ability to install
|
||||||
modified object code on the User Product (for example, the work has
|
modified object code on the User Product (for example, the work has
|
||||||
been installed in ROM).
|
been installed in ROM).</p>
|
||||||
|
|
||||||
The requirement to provide Installation Information does not include a
|
<p>The requirement to provide Installation Information does not include a
|
||||||
requirement to continue to provide support service, warranty, or updates
|
requirement to continue to provide support service, warranty, or updates
|
||||||
for a work that has been modified or installed by the recipient, or for
|
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
|
the User Product in which it has been modified or installed. Access to a
|
||||||
network may be denied when the modification itself materially and
|
network may be denied when the modification itself materially and
|
||||||
adversely affects the operation of the network or violates the rules and
|
adversely affects the operation of the network or violates the rules and
|
||||||
protocols for communication across the network.
|
protocols for communication across the network.</p>
|
||||||
|
|
||||||
Corresponding Source conveyed, and Installation Information provided,
|
<p>Corresponding Source conveyed, and Installation Information provided,
|
||||||
in accord with this section must be in a format that is publicly
|
in accord with this section must be in a format that is publicly
|
||||||
documented (and with an implementation available to the public in
|
documented (and with an implementation available to the public in
|
||||||
source code form), and must require no special password or key for
|
source code form), and must require no special password or key for
|
||||||
unpacking, reading or copying.
|
unpacking, reading or copying.</p>
|
||||||
|
|
||||||
7. Additional Terms.
|
<h4 id="section7">7. Additional Terms.</h4>
|
||||||
|
|
||||||
"Additional permissions" are terms that supplement the terms of this
|
<p>"Additional permissions" are terms that supplement the terms of this
|
||||||
License by making exceptions from one or more of its conditions.
|
License by making exceptions from one or more of its conditions.
|
||||||
Additional permissions that are applicable to the entire Program shall
|
Additional permissions that are applicable to the entire Program shall
|
||||||
be treated as though they were included in this License, to the extent
|
be treated as though they were included in this License, to the extent
|
||||||
that they are valid under applicable law. If additional permissions
|
that they are valid under applicable law. If additional permissions
|
||||||
apply only to part of the Program, that part may be used separately
|
apply only to part of the Program, that part may be used separately
|
||||||
under those permissions, but the entire Program remains governed by
|
under those permissions, but the entire Program remains governed by
|
||||||
this License without regard to the additional permissions.
|
this License without regard to the additional permissions.</p>
|
||||||
|
|
||||||
When you convey a copy of a covered work, you may at your option
|
<p>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
|
remove any additional permissions from that copy, or from any part of
|
||||||
it. (Additional permissions may be written to require their own
|
it. (Additional permissions may be written to require their own
|
||||||
removal in certain cases when you modify the work.) You may place
|
removal in certain cases when you modify the work.) You may place
|
||||||
additional permissions on material, added by you to a covered work,
|
additional permissions on material, added by you to a covered work,
|
||||||
for which you have or can give appropriate copyright permission.
|
for which you have or can give appropriate copyright permission.</p>
|
||||||
|
|
||||||
Notwithstanding any other provision of this License, for material you
|
<p>Notwithstanding any other provision of this License, for material you
|
||||||
add to a covered work, you may (if authorized by the copyright holders of
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
that material) supplement the terms of this License with terms:
|
that material) supplement the terms of this License with terms:</p>
|
||||||
|
|
||||||
a) Disclaiming warranty or limiting liability differently from the
|
<ul>
|
||||||
terms of sections 15 and 16 of this License; or
|
|
||||||
|
|
||||||
b) Requiring preservation of specified reasonable legal notices 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
|
||||||
author attributions in that material or in the Appropriate Legal
|
author attributions in that material or in the Appropriate Legal
|
||||||
Notices displayed by works containing it; or
|
Notices displayed by works containing it; or</li>
|
||||||
|
|
||||||
c) Prohibiting misrepresentation of the origin of that material, or
|
<li>c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
requiring that modified versions of such material be marked in
|
requiring that modified versions of such material be marked in
|
||||||
reasonable ways as different from the original version; or
|
reasonable ways as different from the original version; or</li>
|
||||||
|
|
||||||
d) Limiting the use for publicity purposes of names of licensors or
|
<li>d) Limiting the use for publicity purposes of names of licensors or
|
||||||
authors of the material; or
|
authors of the material; or</li>
|
||||||
|
|
||||||
e) Declining to grant rights under trademark law for use of some
|
<li>e) Declining to grant rights under trademark law for use of some
|
||||||
trade names, trademarks, or service marks; or
|
trade names, trademarks, or service marks; or</li>
|
||||||
|
|
||||||
f) Requiring indemnification of licensors and authors of that
|
<li>f) Requiring indemnification of licensors and authors of that
|
||||||
material by anyone who conveys the material (or modified versions of
|
material by anyone who conveys the material (or modified versions of
|
||||||
it) with contractual assumptions of liability to the recipient, for
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
any liability that these contractual assumptions directly impose on
|
any liability that these contractual assumptions directly impose on
|
||||||
those licensors and authors.
|
those licensors and authors.</li>
|
||||||
|
|
||||||
All other non-permissive additional terms are considered "further
|
</ul>
|
||||||
|
|
||||||
|
<p>All other non-permissive additional terms are considered "further
|
||||||
restrictions" within the meaning of section 10. If the Program as you
|
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
|
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
|
governed by this License along with a term that is a further restriction,
|
||||||
restriction, you may remove that term. If a license document contains
|
you may remove that term. If a license document contains a further
|
||||||
a further restriction but permits relicensing or conveying under this
|
restriction but permits relicensing or conveying under this License, you
|
||||||
License, you may add to a covered work material governed by the terms
|
may add to a covered work material governed by the terms of that license
|
||||||
of that license document, provided that the further restriction does
|
document, provided that the further restriction does not survive such
|
||||||
not survive such relicensing or conveying.
|
relicensing or conveying.</p>
|
||||||
|
|
||||||
If you add terms to a covered work in accord with this section, you
|
<p>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
|
must place, in the relevant source files, a statement of the
|
||||||
additional terms that apply to those files, or a notice indicating
|
additional terms that apply to those files, or a notice indicating
|
||||||
where to find the applicable terms.
|
where to find the applicable terms.</p>
|
||||||
|
|
||||||
Additional terms, permissive or non-permissive, may be stated in the
|
<p>Additional terms, permissive or non-permissive, may be stated in the
|
||||||
form of a separately written license, or stated as exceptions;
|
form of a separately written license, or stated as exceptions;
|
||||||
the above requirements apply either way.
|
the above requirements apply either way.</p>
|
||||||
|
|
||||||
8. Termination.
|
<h4 id="section8">8. Termination.</h4>
|
||||||
|
|
||||||
You may not propagate or modify a covered work except as expressly
|
<p>You may not propagate or modify a covered work except as expressly
|
||||||
provided under this License. Any attempt otherwise to propagate or
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
modify it is void, and will automatically terminate your rights under
|
modify it is void, and will automatically terminate your rights under
|
||||||
this License (including any patent licenses granted under the third
|
this License (including any patent licenses granted under the third
|
||||||
paragraph of section 11).
|
paragraph of section 11).</p>
|
||||||
|
|
||||||
However, if you cease all violation of this License, then your
|
<p>However, if you cease all violation of this License, then your
|
||||||
license from a particular copyright holder is reinstated (a)
|
license from a particular copyright holder is reinstated (a)
|
||||||
provisionally, unless and until the copyright holder explicitly and
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
finally terminates your license, and (b) permanently, if the copyright
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
holder fails to notify you of the violation by some reasonable means
|
holder fails to notify you of the violation by some reasonable means
|
||||||
prior to 60 days after the cessation.
|
prior to 60 days after the cessation.</p>
|
||||||
|
|
||||||
Moreover, your license from a particular copyright holder is
|
<p>Moreover, your license from a particular copyright holder is
|
||||||
reinstated permanently if the copyright holder notifies you of the
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
violation by some reasonable means, this is the first time you have
|
violation by some reasonable means, this is the first time you have
|
||||||
received notice of violation of this License (for any work) from that
|
received notice of violation of this License (for any work) from that
|
||||||
copyright holder, and you cure the violation prior to 30 days after
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
your receipt of the notice.
|
your receipt of the notice.</p>
|
||||||
|
|
||||||
Termination of your rights under this section does not terminate the
|
<p>Termination of your rights under this section does not terminate the
|
||||||
licenses of parties who have received copies or rights from you under
|
licenses of parties who have received copies or rights from you under
|
||||||
this License. If your rights have been terminated and not permanently
|
this License. If your rights have been terminated and not permanently
|
||||||
reinstated, you do not qualify to receive new licenses for the same
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
material under section 10.
|
material under section 10.</p>
|
||||||
|
|
||||||
9. Acceptance Not Required for Having Copies.
|
<h4 id="section9">9. Acceptance Not Required for Having Copies.</h4>
|
||||||
|
|
||||||
You are not required to accept this License in order to receive or
|
<p>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
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
occurring solely as a consequence of using peer-to-peer transmission
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
to receive a copy likewise does not require acceptance. However,
|
to receive a copy likewise does not require acceptance. However,
|
||||||
nothing other than this License grants you permission to propagate or
|
nothing other than this License grants you permission to propagate or
|
||||||
modify any covered work. These actions infringe copyright if you do
|
modify any covered work. These actions infringe copyright if you do
|
||||||
not accept this License. Therefore, by modifying or propagating a
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
covered work, you indicate your acceptance of this License to do so.
|
covered work, you indicate your acceptance of this License to do so.</p>
|
||||||
|
|
||||||
10. Automatic Licensing of Downstream Recipients.
|
<h4 id="section10">10. Automatic Licensing of Downstream Recipients.</h4>
|
||||||
|
|
||||||
Each time you convey a covered work, the recipient automatically
|
<p>Each time you convey a covered work, the recipient automatically
|
||||||
receives a license from the original licensors, to run, modify and
|
receives a license from the original licensors, to run, modify and
|
||||||
propagate that work, subject to this License. You are not responsible
|
propagate that work, subject to this License. You are not responsible
|
||||||
for enforcing compliance by third parties with this License.
|
for enforcing compliance by third parties with this License.</p>
|
||||||
|
|
||||||
An "entity transaction" is a transaction transferring control of an
|
<p>An "entity transaction" is a transaction transferring control of an
|
||||||
organization, or substantially all assets of one, or subdividing an
|
organization, or substantially all assets of one, or subdividing an
|
||||||
organization, or merging organizations. If propagation of a covered
|
organization, or merging organizations. If propagation of a covered
|
||||||
work results from an entity transaction, each party to that
|
work results from an entity transaction, each party to that
|
||||||
@@ -446,23 +469,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
|
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
|
give under the previous paragraph, plus a right to possession of the
|
||||||
Corresponding Source of the work from the predecessor in interest, if
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
the predecessor has it or can get it with reasonable efforts.
|
the predecessor has it or can get it with reasonable efforts.</p>
|
||||||
|
|
||||||
You may not impose any further restrictions on the exercise of the
|
<p>You may not impose any further restrictions on the exercise of the
|
||||||
rights granted or affirmed under this License. For example, you may
|
rights granted or affirmed under this License. For example, you may
|
||||||
not impose a license fee, royalty, or other charge for exercise of
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
rights granted under this License, and you may not initiate litigation
|
rights granted under this License, and you may not initiate litigation
|
||||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
any patent claim is infringed by making, using, selling, offering for
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
sale, or importing the Program or any portion of it.
|
sale, or importing the Program or any portion of it.</p>
|
||||||
|
|
||||||
11. Patents.
|
<h4 id="section11">11. Patents.</h4>
|
||||||
|
|
||||||
A "contributor" is a copyright holder who authorizes use under this
|
<p>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
|
License of the Program or a work on which the Program is based. The
|
||||||
work thus licensed is called the contributor's "contributor version".
|
work thus licensed is called the contributor's "contributor version".</p>
|
||||||
|
|
||||||
A contributor's "essential patent claims" are all patent claims
|
<p>A contributor's "essential patent claims" are all patent claims
|
||||||
owned or controlled by the contributor, whether already acquired or
|
owned or controlled by the contributor, whether already acquired or
|
||||||
hereafter acquired, that would be infringed by some manner, permitted
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
by this License, of making, using, or selling its contributor version,
|
by this License, of making, using, or selling its contributor version,
|
||||||
@@ -470,21 +493,21 @@ but do not include claims that would be infringed only as a
|
|||||||
consequence of further modification of the contributor version. For
|
consequence of further modification of the contributor version. For
|
||||||
purposes of this definition, "control" includes the right to grant
|
purposes of this definition, "control" includes the right to grant
|
||||||
patent sublicenses in a manner consistent with the requirements of
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
this License.
|
this License.</p>
|
||||||
|
|
||||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
<p>Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
patent license under the contributor's essential patent claims, to
|
patent license under the contributor's essential patent claims, to
|
||||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
propagate the contents of its contributor version.
|
propagate the contents of its contributor version.</p>
|
||||||
|
|
||||||
In the following three paragraphs, a "patent license" is any express
|
<p>In the following three paragraphs, a "patent license" is any express
|
||||||
agreement or commitment, however denominated, not to enforce a patent
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
(such as an express permission to practice a patent or covenant not to
|
(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
|
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
|
party means to make such an agreement or commitment not to enforce a
|
||||||
patent against the party.
|
patent against the party.</p>
|
||||||
|
|
||||||
If you convey a covered work, knowingly relying on a patent license,
|
<p>If you convey a covered work, knowingly relying on a patent license,
|
||||||
and the Corresponding Source of the work is not available for anyone
|
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
|
to copy, free of charge and under the terms of this License, through a
|
||||||
publicly available network server or other readily accessible means,
|
publicly available network server or other readily accessible means,
|
||||||
@@ -496,17 +519,17 @@ license to downstream recipients. "Knowingly relying" means you have
|
|||||||
actual knowledge that, but for the patent license, your conveying the
|
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
|
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
|
in a country, would infringe one or more identifiable patents in that
|
||||||
country that you have reason to believe are valid.
|
country that you have reason to believe are valid.</p>
|
||||||
|
|
||||||
If, pursuant to or in connection with a single transaction or
|
<p>If, pursuant to or in connection with a single transaction or
|
||||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
covered work, and grant a patent license to some of the parties
|
covered work, and grant a patent license to some of the parties
|
||||||
receiving the covered work authorizing them to use, propagate, modify
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
or convey a specific copy of the covered work, then the patent license
|
or convey a specific copy of the covered work, then the patent license
|
||||||
you grant is automatically extended to all recipients of the covered
|
you grant is automatically extended to all recipients of the covered
|
||||||
work and works based on it.
|
work and works based on it.</p>
|
||||||
|
|
||||||
A patent license is "discriminatory" if it does not include within
|
<p>A patent license is "discriminatory" if it does not include within
|
||||||
the scope of its coverage, prohibits the exercise of, or is
|
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
|
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
|
specifically granted under this License. You may not convey a covered
|
||||||
@@ -519,15 +542,15 @@ patent license (a) in connection with copies of the covered work
|
|||||||
conveyed by you (or copies made from those copies), or (b) primarily
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
for and in connection with specific products or compilations that
|
for and in connection with specific products or compilations that
|
||||||
contain the covered work, unless you entered into that arrangement,
|
contain the covered work, unless you entered into that arrangement,
|
||||||
or that patent license was granted, prior to 28 March 2007.
|
or that patent license was granted, prior to 28 March 2007.</p>
|
||||||
|
|
||||||
Nothing in this License shall be construed as excluding or limiting
|
<p>Nothing in this License shall be construed as excluding or limiting
|
||||||
any implied license or other defenses to infringement that may
|
any implied license or other defenses to infringement that may
|
||||||
otherwise be available to you under applicable patent law.
|
otherwise be available to you under applicable patent law.</p>
|
||||||
|
|
||||||
12. No Surrender of Others' Freedom.
|
<h4 id="section12">12. No Surrender of Others' Freedom.</h4>
|
||||||
|
|
||||||
If conditions are imposed on you (whether by court order, agreement or
|
<p>If conditions are imposed on you (whether by court order, agreement or
|
||||||
otherwise) that contradict the conditions of this License, they do not
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
excuse you from the conditions of this License. If you cannot convey a
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
covered work so as to satisfy simultaneously your obligations under this
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
@@ -535,11 +558,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
|
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
|
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
|
the Program, the only way you could satisfy both those terms and this
|
||||||
License would be to refrain entirely from conveying the Program.
|
License would be to refrain entirely from conveying the Program.</p>
|
||||||
|
|
||||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
<h4 id="section13">13. Remote Network Interaction; Use with the GNU General Public License.</h4>
|
||||||
|
|
||||||
Notwithstanding any other provision of this License, if you modify the
|
<p>Notwithstanding any other provision of this License, if you modify the
|
||||||
Program, your modified version must prominently offer all users
|
Program, your modified version must prominently offer all users
|
||||||
interacting with it remotely through a computer network (if your version
|
interacting with it remotely through a computer network (if your version
|
||||||
supports such interaction) an opportunity to receive the Corresponding
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
@@ -548,56 +571,56 @@ from a network server at no charge, through some standard or customary
|
|||||||
means of facilitating copying of software. This Corresponding Source
|
means of facilitating copying of software. This Corresponding Source
|
||||||
shall include the Corresponding Source for any work covered by version 3
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
of the GNU General Public License that is incorporated pursuant to the
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
following paragraph.
|
following paragraph.</p>
|
||||||
|
|
||||||
Notwithstanding any other provision of this License, you have
|
<p>Notwithstanding any other provision of this License, you have permission
|
||||||
permission to link or combine any covered work with a work licensed
|
to link or combine any covered work with a work licensed under version 3
|
||||||
under version 3 of the GNU General Public License into a single
|
of the GNU General Public License into a single combined work, and to
|
||||||
combined work, and to convey the resulting work. The terms of this
|
convey the resulting work. The terms of this License will continue to
|
||||||
License will continue to apply to the part which is the covered work,
|
apply to the part which is the covered work, but the work with which it is
|
||||||
but the work with which it is combined will remain governed by version
|
combined will remain governed by version 3 of the GNU General Public
|
||||||
3 of the GNU General Public License.
|
License.</p>
|
||||||
|
|
||||||
14. Revised Versions of this License.
|
<h4 id="section14">14. Revised Versions of this License.</h4>
|
||||||
|
|
||||||
The Free Software Foundation may publish revised and/or new versions of
|
<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
|
the GNU Affero General Public License from time to time. Such new
|
||||||
will be similar in spirit to the present version, but may differ in detail to
|
versions will be similar in spirit to the present version, but may differ
|
||||||
address new problems or concerns.
|
in detail to address new problems or concerns.</p>
|
||||||
|
|
||||||
Each version is given a distinguishing version number. If the
|
<p>Each version is given a distinguishing version number. If the
|
||||||
Program specifies that a certain numbered version of the GNU Affero General
|
Program specifies that a certain numbered version of the GNU Affero
|
||||||
Public License "or any later version" applies to it, you have the
|
General Public License "or any later version" applies to it, you have
|
||||||
option of following the terms and conditions either of that numbered
|
the option of following the terms and conditions either of that
|
||||||
version or of any later version published by the Free Software
|
numbered version or of any later version published by the Free
|
||||||
Foundation. If the Program does not specify a version number of the
|
Software Foundation. If the Program does not specify a version number
|
||||||
GNU Affero General Public License, you may choose any version ever published
|
of the GNU Affero General Public License, you may choose any version
|
||||||
by the Free Software Foundation.
|
ever published by the Free Software Foundation.</p>
|
||||||
|
|
||||||
If the Program specifies that a proxy can decide which future
|
<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
|
versions of the GNU Affero General Public License can be used, that
|
||||||
public statement of acceptance of a version permanently authorizes you
|
proxy's public statement of acceptance of a version permanently
|
||||||
to choose that version for the Program.
|
authorizes you to choose that version for the Program.</p>
|
||||||
|
|
||||||
Later license versions may give you additional or different
|
<p>Later license versions may give you additional or different
|
||||||
permissions. However, no additional obligations are imposed on any
|
permissions. However, no additional obligations are imposed on any
|
||||||
author or copyright holder as a result of your choosing to follow a
|
author or copyright holder as a result of your choosing to follow a
|
||||||
later version.
|
later version.</p>
|
||||||
|
|
||||||
15. Disclaimer of Warranty.
|
<h4 id="section15">15. Disclaimer of Warranty.</h4>
|
||||||
|
|
||||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
<p>THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
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
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.</p>
|
||||||
|
|
||||||
16. Limitation of Liability.
|
<h4 id="section16">16. Limitation of Liability.</h4>
|
||||||
|
|
||||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
<p>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
|
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
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
@@ -605,37 +628,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
|
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),
|
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
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
SUCH DAMAGES.
|
SUCH DAMAGES.</p>
|
||||||
|
|
||||||
17. Interpretation of Sections 15 and 16.
|
<h4 id="section17">17. Interpretation of Sections 15 and 16.</h4>
|
||||||
|
|
||||||
If the disclaimer of warranty and limitation of liability provided
|
<p>If the disclaimer of warranty and limitation of liability provided
|
||||||
above cannot be given local legal effect according to their terms,
|
above cannot be given local legal effect according to their terms,
|
||||||
reviewing courts shall apply local law that most closely approximates
|
reviewing courts shall apply local law that most closely approximates
|
||||||
an absolute waiver of all civil liability in connection with the
|
an absolute waiver of all civil liability in connection with the
|
||||||
Program, unless a warranty or assumption of liability accompanies a
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
copy of the Program in return for a fee.
|
copy of the Program in return for a fee.</p>
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
<p>END OF TERMS AND CONDITIONS</p>
|
||||||
|
|
||||||
How to Apply These Terms to Your New Programs
|
<h4 id="howto">How to Apply These Terms to Your New Programs</h4>
|
||||||
|
|
||||||
If you develop a new program, and you want it to be of the greatest
|
<p>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
|
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.
|
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
|
<p>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
|
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
|
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.
|
the "copyright" line and a pointer to where the full notice is found.</p>
|
||||||
|
|
||||||
<one line to give the program's name and a brief idea of what it does.>
|
<pre> <one line to give the program's name and a brief idea of what it does.>
|
||||||
Copyright (C) <year> <name of author>
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify
|
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
|
it under the terms of the GNU Affero General Public License as
|
||||||
the Free Software Foundation, either version 3 of the License, or
|
published by the Free Software Foundation, either version 3 of the
|
||||||
(at your option) any later version.
|
License, or (at your option) any later version.
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful,
|
This program is distributed in the hope that it will be useful,
|
||||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
@@ -643,19 +666,23 @@ the "copyright" line and a pointer to where the full notice is found.
|
|||||||
GNU Affero General Public License for more details.
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
You should have received a copy of the GNU Affero General Public License
|
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/>.
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
</pre>
|
||||||
|
|
||||||
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
|
<p>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
|
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
|
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
|
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
|
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
|
solutions will be better for different programs; see section 13 for the
|
||||||
specific requirements.
|
specific requirements.</p>
|
||||||
|
|
||||||
You should also get your employer (if you work as a programmer) or school,
|
<p>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.
|
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
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
<https://www.gnu.org/licenses/>.
|
<<a href="https://www.gnu.org/licenses/">https://www.gnu.org/licenses/</a>>.</p>
|
||||||
|
|
||||||
|
|
||||||
|
</body></html>
|
||||||
@@ -57,6 +57,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
|||||||
// If providers are being updated, invalidate the provider-models query
|
// If providers are being updated, invalidate the provider-models query
|
||||||
if ('providers' in newSettings) {
|
if ('providers' in newSettings) {
|
||||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -80,6 +81,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
|
||||||
};
|
};
|
||||||
|
|
||||||
const removeProvider = (id: string) => {
|
const removeProvider = (id: string) => {
|
||||||
@@ -88,6 +90,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
|||||||
providers: prev.providers.filter(provider => provider.id !== id),
|
providers: prev.providers.filter(provider => provider.id !== id),
|
||||||
}));
|
}));
|
||||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
|
||||||
};
|
};
|
||||||
|
|
||||||
const setProviders = (providers: AIProvider[]) => {
|
const setProviders = (providers: AIProvider[]) => {
|
||||||
@@ -96,6 +99,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
|||||||
providers,
|
providers,
|
||||||
}));
|
}));
|
||||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
|
||||||
};
|
};
|
||||||
|
|
||||||
const addRecentlyUsedModel = (modelId: string) => {
|
const addRecentlyUsedModel = (modelId: string) => {
|
||||||
|
|||||||
@@ -0,0 +1,380 @@
|
|||||||
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -509,17 +509,13 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
|||||||
</div>
|
</div>
|
||||||
<div className="flex-1 min-h-0 overflow-y-auto">
|
<div className="flex-1 min-h-0 overflow-y-auto">
|
||||||
{isLoadingPayments ? (
|
{isLoadingPayments ? (
|
||||||
<div className="space-y-3">
|
<div className="p-3 border rounded-lg space-y-2">
|
||||||
{Array.from({ length: 3 }).map((_, i) => (
|
<div className="flex items-center gap-2">
|
||||||
<div key={i} className="p-3 border rounded-lg space-y-2">
|
<Skeleton className="h-4 w-4 rounded" />
|
||||||
<div className="flex items-center gap-2">
|
<Skeleton className="h-4 w-24" />
|
||||||
<Skeleton className="h-4 w-4 rounded" />
|
<Skeleton className="h-4 w-16 ml-auto" />
|
||||||
<Skeleton className="h-4 w-24" />
|
</div>
|
||||||
<Skeleton className="h-4 w-16 ml-auto" />
|
<Skeleton className="h-3 w-32" />
|
||||||
</div>
|
|
||||||
<Skeleton className="h-3 w-32" />
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
) : !payments || payments.length === 0 ? (
|
) : !payments || payments.length === 0 ? (
|
||||||
<div className="flex-1 flex items-center justify-center">
|
<div className="flex-1 flex items-center justify-center">
|
||||||
|
|||||||
@@ -168,7 +168,9 @@ export function ModelSelector({
|
|||||||
</PopoverTrigger>
|
</PopoverTrigger>
|
||||||
<PopoverContent className="w-96 p-0" align="end">
|
<PopoverContent className="w-96 p-0" align="end">
|
||||||
<Command>
|
<Command>
|
||||||
{isConfigured && <CommandInput placeholder={t('searchModels')} className="h-9" />}
|
{(isConfigured && models.length >= 5) && (
|
||||||
|
<CommandInput placeholder={t('searchModels')} className="h-9" />
|
||||||
|
)}
|
||||||
<CommandList className="max-h-[300px]">
|
<CommandList className="max-h-[300px]">
|
||||||
<CommandEmpty>
|
<CommandEmpty>
|
||||||
<div className="py-6 text-center text-sm text-muted-foreground">
|
<div className="py-6 text-center text-sm text-muted-foreground">
|
||||||
|
|||||||
@@ -208,7 +208,7 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
<DialogContent className="max-w-md">
|
<DialogContent className="max-w-md" onOpenAutoFocus={(e) => e.preventDefault()}>
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle className="flex items-center gap-2">
|
<DialogTitle className="flex items-center gap-2">
|
||||||
<Folder className="h-5 w-5" />
|
<Folder className="h-5 w-5" />
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { useEffect } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import { useTranslation } from 'react-i18next';
|
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 { Button } from '@/components/ui/button';
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Skeleton } from '@/components/ui/skeleton';
|
||||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||||
@@ -9,6 +9,9 @@ import { useProjects } from '@/hooks/useProjects';
|
|||||||
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
|
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
|
||||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
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 type { Project } from '@/lib/ProjectsManager';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { useQueryClient } from '@tanstack/react-query';
|
import { useQueryClient } from '@tanstack/react-query';
|
||||||
@@ -92,6 +95,9 @@ export function ProjectSidebar({
|
|||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const { data: projects = [], isLoading, error } = useProjects();
|
const { data: projects = [], isLoading, error } = useProjects();
|
||||||
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
|
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
|
||||||
|
const projectsManager = useProjectsManager();
|
||||||
|
const { toast } = useToast();
|
||||||
|
const [isZipDialogOpen, setIsZipDialogOpen] = useState(false);
|
||||||
|
|
||||||
const isMobile = useIsMobile();
|
const isMobile = useIsMobile();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
@@ -117,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(() => {
|
useEffect(() => {
|
||||||
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||||
}, [favorites, queryClient]);
|
}, [favorites, queryClient]);
|
||||||
@@ -186,6 +211,13 @@ export function ProjectSidebar({
|
|||||||
<GitBranch className="h-4 w-4" />
|
<GitBranch className="h-4 w-4" />
|
||||||
{t('importRepository')}
|
{t('importRepository')}
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={() => setIsZipDialogOpen(true)}
|
||||||
|
className="flex items-center gap-2 w-full"
|
||||||
|
>
|
||||||
|
<FileArchive className="h-4 w-4" />
|
||||||
|
Import ZIP File
|
||||||
|
</DropdownMenuItem>
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</div>
|
</div>
|
||||||
@@ -248,6 +280,13 @@ export function ProjectSidebar({
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* ZIP Import Dialog */}
|
||||||
|
<ZipImportDialog
|
||||||
|
onImport={handleImportZip}
|
||||||
|
open={isZipDialogOpen}
|
||||||
|
onOpenChange={setIsZipDialogOpen}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -7,6 +7,7 @@ import { useAISettings } from '@/hooks/useAISettings';
|
|||||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||||
import { useAICredits } from '@/hooks/useAICredits';
|
import { useAICredits } from '@/hooks/useAICredits';
|
||||||
import { CreditsDialog } from './CreditsDialog';
|
import { CreditsDialog } from './CreditsDialog';
|
||||||
|
import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
|
|
||||||
export interface QuillyProps {
|
export interface QuillyProps {
|
||||||
@@ -14,6 +15,7 @@ export interface QuillyProps {
|
|||||||
onDismiss: () => void;
|
onDismiss: () => void;
|
||||||
onNewChat: () => void;
|
onNewChat: () => void;
|
||||||
onOpenModelSelector: () => void;
|
onOpenModelSelector: () => void;
|
||||||
|
onRequestConsoleErrorHelp?: (error: ProjectPreviewConsoleError) => void;
|
||||||
providerModel: string;
|
providerModel: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25,14 +27,37 @@ interface ErrorBody {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, providerModel }: QuillyProps) {
|
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { settings } = useAISettings();
|
const { settings } = useAISettings();
|
||||||
const { provider } = parseProviderModel(providerModel, settings.providers);
|
|
||||||
const credits = useAICredits(provider);
|
// 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 [showCreditsDialog, setShowCreditsDialog] = useState(false);
|
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
|
||||||
|
|
||||||
const renderBody = (error: Error): ErrorBody => {
|
const renderBody = (error: Error): ErrorBody => {
|
||||||
|
// Handle Project Preview Console Errors
|
||||||
|
if (error instanceof ProjectPreviewConsoleError) {
|
||||||
|
return {
|
||||||
|
message: 'I noticed some console errors in your project preview. Would you like me to take a look and help fix them?',
|
||||||
|
action: {
|
||||||
|
label: 'Help fix errors',
|
||||||
|
onClick: () => {
|
||||||
|
onRequestConsoleErrorHelp?.(error);
|
||||||
|
onDismiss();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Handle OpenAI API errors with specific error codes
|
// Handle OpenAI API errors with specific error codes
|
||||||
if (error instanceof OpenAI.APIError) {
|
if (error instanceof OpenAI.APIError) {
|
||||||
switch (error.code) {
|
switch (error.code) {
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool';
|
|||||||
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
|
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
|
||||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||||
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
|
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
|
||||||
|
import { ReadConsoleMessagesTool, ProjectPreviewConsoleError, addErrorListener, removeErrorListener } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||||
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
||||||
import { Tool } from '@/lib/tools/Tool';
|
import { Tool } from '@/lib/tools/Tool';
|
||||||
import OpenAI from 'openai';
|
import OpenAI from 'openai';
|
||||||
@@ -65,6 +66,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
isBuildLoading: externalIsBuildLoading,
|
isBuildLoading: externalIsBuildLoading,
|
||||||
}, ref) => {
|
}, ref) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const [searchParams, setSearchParams] = useSearchParams();
|
||||||
|
const { fs } = useFS();
|
||||||
|
const { git } = useGit();
|
||||||
|
const { user } = useCurrentUser();
|
||||||
|
const { models } = useProviderModels();
|
||||||
const [input, setInput] = useState('');
|
const [input, setInput] = useState('');
|
||||||
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
|
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
|
||||||
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
|
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
|
||||||
@@ -74,6 +80,19 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
const [isStuck, setIsStuck] = useState(false);
|
const [isStuck, setIsStuck] = useState(false);
|
||||||
const [aiError, setAIError] = useState<Error | null>(null);
|
const [aiError, setAIError] = useState<Error | null>(null);
|
||||||
|
|
||||||
|
// 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]);
|
||||||
|
|
||||||
// Use external state if provided, otherwise default to false
|
// Use external state if provided, otherwise default to false
|
||||||
const isBuildLoading = externalIsBuildLoading || false;
|
const isBuildLoading = externalIsBuildLoading || false;
|
||||||
const scrollAreaRef = useRef<HTMLDivElement>(null);
|
const scrollAreaRef = useRef<HTMLDivElement>(null);
|
||||||
@@ -84,6 +103,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
});
|
});
|
||||||
// State to control model selector dropdown
|
// State to control model selector dropdown
|
||||||
const [isModelSelectorOpen, setIsModelSelectorOpen] = useState(false);
|
const [isModelSelectorOpen, setIsModelSelectorOpen] = useState(false);
|
||||||
|
const [shouldAutostart, setShouldAutostart] = useState(false);
|
||||||
const autostartedRef = useRef(false);
|
const autostartedRef = useRef(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -92,17 +112,29 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
}
|
}
|
||||||
}, [providerModel, settings.recentlyUsedModels]);
|
}, [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
|
// Reset error state when navigating between projects and switching models
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setAIError(null);
|
setAIError(null);
|
||||||
}, [projectId, providerModel]);
|
}, [projectId, providerModel]);
|
||||||
|
|
||||||
const [searchParams, setSearchParams] = useSearchParams();
|
|
||||||
const { fs } = useFS();
|
|
||||||
const { git } = useGit();
|
|
||||||
const { user } = useCurrentUser();
|
|
||||||
const { models } = useProviderModels();
|
|
||||||
|
|
||||||
// Initialize AI chat with tools
|
// Initialize AI chat with tools
|
||||||
const cwd = `/projects/${projectId}`;
|
const cwd = `/projects/${projectId}`;
|
||||||
const customTools = useMemo(() => {
|
const customTools = useMemo(() => {
|
||||||
@@ -123,6 +155,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
nostr_read_nips_index: new NostrReadNipsIndexTool(),
|
nostr_read_nips_index: new NostrReadNipsIndexTool(),
|
||||||
nostr_generate_kind: new NostrGenerateKindTool(),
|
nostr_generate_kind: new NostrGenerateKindTool(),
|
||||||
shell: new ShellTool(fs, cwd, git),
|
shell: new ShellTool(fs, cwd, git),
|
||||||
|
read_console_messages: new ReadConsoleMessagesTool(),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Add deploy tool only if user is logged in
|
// Add deploy tool only if user is logged in
|
||||||
@@ -187,6 +220,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
onAIError,
|
onAIError,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Handle console error help requests
|
||||||
|
const handleConsoleErrorHelp = useCallback(() => {
|
||||||
|
sendMessage('Read the console messages and fix any errors present.', providerModel);
|
||||||
|
}, [sendMessage, providerModel]);
|
||||||
|
|
||||||
// Use external loading state if provided, otherwise use internal state
|
// Use external loading state if provided, otherwise use internal state
|
||||||
const isLoading = externalIsLoading !== undefined ? externalIsLoading : internalIsLoading;
|
const isLoading = externalIsLoading !== undefined ? externalIsLoading : internalIsLoading;
|
||||||
|
|
||||||
@@ -242,32 +280,13 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (autostartedRef.current) return;
|
if (autostartedRef.current) return;
|
||||||
|
|
||||||
const autostart = searchParams.get('autostart');
|
if (shouldAutostart && providerModel && isConfigured) {
|
||||||
const urlModel = searchParams.get('model');
|
// Start AI generation
|
||||||
|
addRecentlyUsedModel(providerModel);
|
||||||
if (autostart === 'true' && isConfigured) {
|
startGeneration(providerModel);
|
||||||
// Use model from URL if available, otherwise use current selection
|
autostartedRef.current = true;
|
||||||
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, searchParams, setSearchParams, startGeneration]);
|
}, [addRecentlyUsedModel, isConfigured, providerModel, shouldAutostart, startGeneration]);
|
||||||
|
|
||||||
// Simple scroll event listener
|
// Simple scroll event listener
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -596,6 +615,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
onDismiss={() => setAIError(null)}
|
onDismiss={() => setAIError(null)}
|
||||||
onNewChat={onNewChat}
|
onNewChat={onNewChat}
|
||||||
onOpenModelSelector={openModelSelector}
|
onOpenModelSelector={openModelSelector}
|
||||||
|
onRequestConsoleErrorHelp={handleConsoleErrorHelp}
|
||||||
providerModel={providerModel}
|
providerModel={providerModel}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -3,12 +3,12 @@ import { useState, useEffect, useCallback, useRef } from 'react';
|
|||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||||
import { useFS } from '@/hooks/useFS';
|
import { useFS } from '@/hooks/useFS';
|
||||||
import { useConsoleMessages, addConsoleMessage, clearConsoleMessages, type ConsoleMessage } from '@/hooks/useConsoleMessages';
|
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||||
import { Tabs, TabsContent } from '@/components/ui/tabs';
|
import { Tabs, TabsContent } from '@/components/ui/tabs';
|
||||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
|
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { FolderOpen, ArrowLeft, X, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload } from 'lucide-react';
|
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload, X } from 'lucide-react';
|
||||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||||
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
|
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
|
||||||
@@ -18,7 +18,12 @@ import {
|
|||||||
DropdownMenuItem,
|
DropdownMenuItem,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from '@/components/ui/dropdown-menu';
|
} from '@/components/ui/dropdown-menu';
|
||||||
|
import {
|
||||||
|
Popover,
|
||||||
|
PopoverContent,
|
||||||
|
PopoverTrigger,
|
||||||
|
} from '@/components/ui/popover';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
import { FileTree } from './FileTree';
|
import { FileTree } from './FileTree';
|
||||||
import { FileEditor } from './FileEditor';
|
import { FileEditor } from './FileEditor';
|
||||||
import { DeployDialog } from '@/components/DeployDialog';
|
import { DeployDialog } from '@/components/DeployDialog';
|
||||||
@@ -66,7 +71,6 @@ interface JSONRPCResponse {
|
|||||||
id: number;
|
id: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction, isPreviewable = true }: PreviewPaneProps) {
|
export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction, isPreviewable = true }: PreviewPaneProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [selectedFile, setSelectedFile] = useState<string | null>(null);
|
const [selectedFile, setSelectedFile] = useState<string | null>(null);
|
||||||
@@ -78,12 +82,12 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
const [currentPath, setCurrentPath] = useState('/');
|
const [currentPath, setCurrentPath] = useState('/');
|
||||||
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
|
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
|
||||||
const [historyIndex, setHistoryIndex] = useState(0);
|
const [historyIndex, setHistoryIndex] = useState(0);
|
||||||
const [copiedMessageId, setCopiedMessageId] = useState<number | null>(null);
|
|
||||||
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
|
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
|
||||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||||
const { fs } = useFS();
|
const { fs } = useFS();
|
||||||
const projectsManager = useProjectsManager();
|
const projectsManager = useProjectsManager();
|
||||||
const { messages: consoleMessages } = useConsoleMessages();
|
|
||||||
const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId);
|
const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId);
|
||||||
|
|
||||||
const [searchParams, setSearchParams] = useSearchParams();
|
const [searchParams, setSearchParams] = useSearchParams();
|
||||||
@@ -211,7 +215,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
normalizedLevel = params.level as ConsoleMessage['level'];
|
normalizedLevel = params.level as ConsoleMessage['level'];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add to global console messages
|
// Add to console messages
|
||||||
addConsoleMessage(normalizedLevel, params.message);
|
addConsoleMessage(normalizedLevel, params.message);
|
||||||
|
|
||||||
// Log to parent console for debugging with appropriate level
|
// Log to parent console for debugging with appropriate level
|
||||||
@@ -303,8 +307,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
const { params, id } = request;
|
const { params, id } = request;
|
||||||
const { request: fetchRequest } = params;
|
const { request: fetchRequest } = params;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Parse the URL and validate origin
|
// Parse the URL and validate origin
|
||||||
const url = new URL(fetchRequest.url);
|
const url = new URL(fetchRequest.url);
|
||||||
@@ -368,9 +370,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// For non-static assets, try SPA fallback to index.html
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SPA fallback: serve index.html for non-file requests (SPA routing)
|
// SPA fallback: serve index.html for non-file requests (SPA routing)
|
||||||
@@ -393,8 +392,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
// Even index.html doesn't exist
|
// Even index.html doesn't exist
|
||||||
|
|
||||||
|
|
||||||
sendResponse({
|
sendResponse({
|
||||||
jsonrpc: '2.0',
|
jsonrpc: '2.0',
|
||||||
result: {
|
result: {
|
||||||
@@ -503,98 +500,101 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
};
|
};
|
||||||
|
|
||||||
const ConsoleDropdown = () => {
|
const ConsoleDropdown = () => {
|
||||||
const getLevelColor = (level: ConsoleMessage['level']) => {
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
switch (level) {
|
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
|
||||||
case 'error': return 'text-red-500';
|
|
||||||
case 'warn': return 'text-yellow-500';
|
|
||||||
case 'info': return 'text-blue-500';
|
|
||||||
case 'debug': return 'text-gray-500';
|
|
||||||
default: return 'text-gray-400';
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getLevelIcon = (level: ConsoleMessage['level']) => {
|
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
|
||||||
switch (level) {
|
|
||||||
case 'error': return '!';
|
|
||||||
case 'warn': return '⚠';
|
|
||||||
case 'info': return 'ℹ';
|
|
||||||
case 'debug': return '🔍';
|
|
||||||
default: return '•';
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const clearConsole = () => {
|
|
||||||
clearConsoleMessages();
|
|
||||||
};
|
|
||||||
|
|
||||||
const copyMessageToClipboard = async (msg: ConsoleMessage) => {
|
|
||||||
try {
|
try {
|
||||||
// Create a formatted string with all message details
|
await navigator.clipboard.writeText(msg.message);
|
||||||
const formattedMessage = `[${msg.level.toUpperCase()}] ${msg.message}`;
|
setCopiedMessageIndex(index);
|
||||||
|
setTimeout(() => setCopiedMessageIndex(null), 2000);
|
||||||
await navigator.clipboard.writeText(formattedMessage);
|
|
||||||
setCopiedMessageId(msg.id);
|
|
||||||
|
|
||||||
// Reset the copied state after 2 seconds
|
|
||||||
setTimeout(() => {
|
|
||||||
setCopiedMessageId(null);
|
|
||||||
}, 2000);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to copy message to clipboard:', error);
|
console.error('Failed to copy message to clipboard:', error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const consoleMessages = getConsoleMessages();
|
||||||
|
const messageCount = consoleMessages.length;
|
||||||
|
const hasErrors = consoleMessages.some(msg => msg.level === 'error');
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DropdownMenu>
|
<Popover open={isOpen} onOpenChange={setIsOpen}>
|
||||||
<DropdownMenuTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0 relative">
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="h-8 w-8 p-0 relative hover:bg-accent hover:text-accent-foreground transition-colors"
|
||||||
|
>
|
||||||
<Bug className="h-4 w-4" />
|
<Bug className="h-4 w-4" />
|
||||||
{consoleMessages.some(msg => msg.level === 'error') && (
|
{hasErrors && (
|
||||||
<span className="absolute bottom-0 left-0 h-2 w-2 bg-red-500 rounded-full"></span>
|
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</PopoverTrigger>
|
||||||
<DropdownMenuContent align="end" className="w-96 max-w-96 max-h-96 overflow-x-hidden">
|
<PopoverContent
|
||||||
<div className="flex items-center justify-between p-2 border-b">
|
align="end"
|
||||||
<span className="font-medium text-sm">Console Output ({consoleMessages.length})</span>
|
className="w-[calc(100vw-1rem)] max-w-[480px] max-h-[512px] overflow-hidden shadow-lg border rounded-lg bg-background p-0"
|
||||||
<Button variant="ghost" size="sm" onClick={clearConsole}>
|
sideOffset={4}
|
||||||
<X className="h-3 w-3" />
|
>
|
||||||
</Button>
|
|
||||||
</div>
|
{/* Messages */}
|
||||||
<ScrollArea className="h-80 w-full max-w-full overflow-x-hidden">
|
<div className="h-[60vh] max-h-[512px] w-full bg-background text-foreground font-mono text-xs relative overflow-y-auto overflow-x-hidden [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]">
|
||||||
<div className="space-y-1 p-2 w-full max-w-full overflow-x-hidden">
|
<div className="py-2 px-1 space-y-0">
|
||||||
{consoleMessages.length === 0 ? (
|
{messageCount === 0 ? (
|
||||||
<div className="text-center text-muted-foreground text-sm py-4">
|
<div className="flex flex-col items-center justify-center py-12 text-center">
|
||||||
No console messages
|
<p className="text-sm text-muted-foreground font-medium">No console messages</p>
|
||||||
|
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
consoleMessages.map((msg) => (
|
consoleMessages.map((msg, index) => (
|
||||||
<div
|
<div
|
||||||
key={msg.id}
|
key={index}
|
||||||
className={`text-xs font-mono p-2 rounded ${getLevelColor(msg.level)} bg-muted/50 group relative w-full overflow-hidden`}
|
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
copyMessageToClipboard(msg, index);
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<div className="flex items-start justify-between w-full">
|
<div className={cn(
|
||||||
<div className="whitespace-pre-wrap break-all flex-1 pr-2 overflow-x-hidden">{getLevelIcon(msg.level)} {msg.message}</div>
|
"text-xs font-mono leading-tight whitespace-pre-wrap break-words",
|
||||||
<Button
|
msg.level === 'error' ? "text-destructive" :
|
||||||
variant="ghost"
|
msg.level === 'warn' ? "text-warning" :
|
||||||
size="sm"
|
msg.level === 'info' ? "text-primary" :
|
||||||
onClick={() => copyMessageToClipboard(msg)}
|
"text-muted-foreground"
|
||||||
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex-shrink-0"
|
)}>
|
||||||
>
|
{msg.message}
|
||||||
{copiedMessageId === msg.id ? (
|
|
||||||
<Check className="h-3 w-3 text-green-500" />
|
|
||||||
) : (
|
|
||||||
<Copy className="h-3 w-3" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
copyMessageToClipboard(msg, index);
|
||||||
|
}}
|
||||||
|
className="h-3 w-3 p-0 opacity-0 group-hover:opacity-100 transition-all duration-200 absolute right-1 top-1 hover:bg-muted/70 text-muted-foreground hover:text-foreground bg-background/80 rounded border"
|
||||||
|
>
|
||||||
|
{copiedMessageIndex === index ? (
|
||||||
|
<Check className="h-2 w-2 text-success" />
|
||||||
|
) : (
|
||||||
|
<Copy className="h-2 w-2" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
))
|
))
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</ScrollArea>
|
</div>
|
||||||
</DropdownMenuContent>
|
|
||||||
</DropdownMenu>
|
{/* Close button */}
|
||||||
|
<button
|
||||||
|
onClick={() => setIsOpen(false)}
|
||||||
|
className="absolute top-2 right-2 h-8 w-8 p-0 bg-muted/50 hover:bg-muted/70 rounded-md z-10 flex items-center justify-center border"
|
||||||
|
>
|
||||||
|
<X className="h-5 w-5 text-muted-foreground" />
|
||||||
|
</button>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -613,7 +613,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
<span className="sr-only">Open menu</span>
|
<span className="sr-only">Open menu</span>
|
||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end" className="w-48">
|
<DropdownMenuContent align="end" className="w-48 sm:w-48">
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
onClick={handleBuildProject}
|
onClick={handleBuildProject}
|
||||||
disabled={isBuildLoading}
|
disabled={isBuildLoading}
|
||||||
|
|||||||
@@ -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 } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
import { Cloud } from 'lucide-react';
|
import { Cloud, Upload } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||||
@@ -32,6 +32,7 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
|||||||
}) => {
|
}) => {
|
||||||
// Removed step state - we only have one step now
|
// Removed step state - we only have one step now
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [isFileLoading, setIsFileLoading] = useState(false);
|
||||||
const [nsec, setNsec] = useState('');
|
const [nsec, setNsec] = useState('');
|
||||||
const [bunkerUri, setBunkerUri] = useState('');
|
const [bunkerUri, setBunkerUri] = useState('');
|
||||||
const [activeTab, setActiveTab] = useState<'nsec' | 'bunker'>('nsec');
|
const [activeTab, setActiveTab] = useState<'nsec' | 'bunker'>('nsec');
|
||||||
@@ -39,7 +40,9 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
|||||||
nsec?: string;
|
nsec?: string;
|
||||||
bunker?: string;
|
bunker?: string;
|
||||||
extension?: string;
|
extension?: string;
|
||||||
|
file?: string;
|
||||||
}>({});
|
}>({});
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
const login = useLoginActions();
|
const login = useLoginActions();
|
||||||
|
|
||||||
@@ -47,10 +50,15 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isOpen) {
|
if (isOpen) {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
|
setIsFileLoading(false);
|
||||||
setNsec('');
|
setNsec('');
|
||||||
setBunkerUri('');
|
setBunkerUri('');
|
||||||
setActiveTab('nsec');
|
setActiveTab('nsec');
|
||||||
setErrors({});
|
setErrors({});
|
||||||
|
// Reset file input
|
||||||
|
if (fileInputRef.current) {
|
||||||
|
fileInputRef.current.value = '';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}, [isOpen]);
|
}, [isOpen]);
|
||||||
|
|
||||||
@@ -86,20 +94,7 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
|||||||
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
|
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
|
||||||
return;
|
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 () => {
|
const handleBunkerLogin = async () => {
|
||||||
@@ -131,6 +126,52 @@ 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 = () => {
|
const handleSignupClick = () => {
|
||||||
onClose();
|
onClose();
|
||||||
if (onSignup) {
|
if (onSignup) {
|
||||||
@@ -202,14 +243,37 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Button
|
<div className="flex space-x-2">
|
||||||
size="lg"
|
<Button
|
||||||
onClick={handleKeyLogin}
|
size="lg"
|
||||||
disabled={isLoading || !nsec.trim()}
|
onClick={handleKeyLogin}
|
||||||
className="w-full"
|
disabled={isLoading || !nsec.trim()}
|
||||||
>
|
className="flex-1"
|
||||||
{isLoading ? 'Verifying...' : 'Add Key'}
|
>
|
||||||
</Button>
|
{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>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -4,34 +4,18 @@ import { createAIClient } from '@/lib/ai-client';
|
|||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
import { AIProvider } from '@/contexts/AISettingsContext';
|
import { AIProvider } from '@/contexts/AISettingsContext';
|
||||||
|
|
||||||
// Zod schemas for the two possible response formats
|
const creditsResponseSchema = z.object({
|
||||||
const creditsResponseV1Schema = z.object({
|
|
||||||
object: z.literal('credits'),
|
object: z.literal('credits'),
|
||||||
amount: z.number(),
|
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)
|
// Normalized response type (always in V1 format)
|
||||||
export interface CreditsResponse {
|
export interface CreditsResponse {
|
||||||
object: 'credits';
|
object: 'credits';
|
||||||
amount: number;
|
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) {
|
export function useAICredits(provider: AIProvider) {
|
||||||
const { user } = useCurrentUser();
|
const { user } = useCurrentUser();
|
||||||
|
|
||||||
@@ -41,20 +25,7 @@ export function useAICredits(provider: AIProvider) {
|
|||||||
try {
|
try {
|
||||||
const ai = createAIClient(provider, user);
|
const ai = createAIClient(provider, user);
|
||||||
const data = await ai.get('/credits');
|
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) {
|
} catch (error) {
|
||||||
if (error instanceof Error && !error.message.includes('Connection error')) {
|
if (error instanceof Error && !error.message.includes('Connection error')) {
|
||||||
console.error('Error fetching AI credits:', error);
|
console.error('Error fetching AI credits:', error);
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
const errorMessage = error instanceof Error ? error.message : 'Failed to generate project ID';
|
const errorMessage = error instanceof Error ? error.message : 'Failed to generate project ID';
|
||||||
onError?.(errorMessage);
|
onError?.(errorMessage);
|
||||||
throw new Error(errorMessage);
|
throw error;
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,79 +0,0 @@
|
|||||||
import { useState, useCallback, useEffect } from 'react';
|
|
||||||
|
|
||||||
export interface ConsoleMessage {
|
|
||||||
id: number;
|
|
||||||
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
|
|
||||||
message: string;
|
|
||||||
timestamp: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Global state for console messages
|
|
||||||
let globalConsoleMessages: ConsoleMessage[] = [];
|
|
||||||
const listeners: Set<(messages: ConsoleMessage[]) => void> = new Set();
|
|
||||||
|
|
||||||
const notifyListeners = () => {
|
|
||||||
listeners.forEach(listener => listener([...globalConsoleMessages]));
|
|
||||||
};
|
|
||||||
|
|
||||||
export const useConsoleMessages = () => {
|
|
||||||
const [messages, setMessages] = useState<ConsoleMessage[]>(globalConsoleMessages);
|
|
||||||
|
|
||||||
const addMessage = useCallback((level: ConsoleMessage['level'], message: string) => {
|
|
||||||
const newMessage: ConsoleMessage = {
|
|
||||||
id: Date.now() + Math.random(), // Ensure uniqueness
|
|
||||||
level,
|
|
||||||
message,
|
|
||||||
timestamp: Date.now(),
|
|
||||||
};
|
|
||||||
|
|
||||||
globalConsoleMessages = [...globalConsoleMessages, newMessage];
|
|
||||||
notifyListeners();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const clearMessages = useCallback(() => {
|
|
||||||
globalConsoleMessages = [];
|
|
||||||
notifyListeners();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const getErrorsSince = useCallback((timestamp: number) => {
|
|
||||||
return globalConsoleMessages.filter(
|
|
||||||
msg => msg.level === 'error' && msg.timestamp > timestamp
|
|
||||||
);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// Subscribe to global state changes
|
|
||||||
useEffect(() => {
|
|
||||||
const listener = (newMessages: ConsoleMessage[]) => {
|
|
||||||
setMessages(newMessages);
|
|
||||||
};
|
|
||||||
listeners.add(listener);
|
|
||||||
return () => {
|
|
||||||
listeners.delete(listener);
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return {
|
|
||||||
messages,
|
|
||||||
addMessage,
|
|
||||||
clearMessages,
|
|
||||||
getErrorsSince,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
// Export functions for external use (like PreviewPane)
|
|
||||||
export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => {
|
|
||||||
const newMessage: ConsoleMessage = {
|
|
||||||
id: Date.now() + Math.random(),
|
|
||||||
level,
|
|
||||||
message,
|
|
||||||
timestamp: Date.now(),
|
|
||||||
};
|
|
||||||
|
|
||||||
globalConsoleMessages = [...globalConsoleMessages, newMessage];
|
|
||||||
notifyListeners();
|
|
||||||
};
|
|
||||||
|
|
||||||
export const clearConsoleMessages = () => {
|
|
||||||
globalConsoleMessages = [];
|
|
||||||
notifyListeners();
|
|
||||||
};
|
|
||||||
@@ -247,6 +247,31 @@
|
|||||||
max-height: 100dvh;
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 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 {
|
pre.shiki {
|
||||||
background-color: transparent !important;
|
background-color: transparent !important;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -98,8 +98,6 @@ invalid json line
|
|||||||
it('should create history directory if it does not exist', async () => {
|
it('should create history directory if it does not exist', async () => {
|
||||||
// Mock historyDirExists to return false initially
|
// Mock historyDirExists to return false initially
|
||||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false);
|
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false);
|
||||||
// Mock setupAiHistoryDir
|
|
||||||
vi.spyOn(dotAI, 'setupAiHistoryDir').mockResolvedValue();
|
|
||||||
|
|
||||||
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
|
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
|
||||||
{ role: 'user', content: 'Hello' }
|
{ role: 'user', content: 'Hello' }
|
||||||
@@ -107,8 +105,8 @@ invalid json line
|
|||||||
|
|
||||||
await dotAI.setHistory('test-session', messages);
|
await dotAI.setHistory('test-session', messages);
|
||||||
|
|
||||||
// Verify setupAiHistoryDir was called
|
// Verify mkdir was called with recursive option
|
||||||
expect(dotAI.setupAiHistoryDir).toHaveBeenCalled();
|
expect(mockFS.mkdir).toHaveBeenCalledWith('/test-project/.git/ai/history', { recursive: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should write messages as JSONL format', async () => {
|
it('should write messages as JSONL format', async () => {
|
||||||
@@ -124,7 +122,7 @@ invalid json line
|
|||||||
|
|
||||||
// Verify writeFile was called with correct content
|
// Verify writeFile was called with correct content
|
||||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||||
'/test-project/.ai/history/test-session.jsonl',
|
'/test-project/.git/ai/history/test-session.jsonl',
|
||||||
'{"role":"user","content":"Hello"}\n{"role":"assistant","content":"Hi there!"}\n'
|
'{"role":"user","content":"Hello"}\n{"role":"assistant","content":"Hi there!"}\n'
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -137,7 +135,7 @@ invalid json line
|
|||||||
|
|
||||||
// Verify writeFile was called with empty content
|
// Verify writeFile was called with empty content
|
||||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||||
'/test-project/.ai/history/test-session.jsonl',
|
'/test-project/.git/ai/history/test-session.jsonl',
|
||||||
''
|
''
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
+16
-86
@@ -2,7 +2,7 @@ import { join } from "path-browserify";
|
|||||||
import type OpenAI from "openai";
|
import type OpenAI from "openai";
|
||||||
import type { JSRuntimeFS } from "./JSRuntime";
|
import type { JSRuntimeFS } from "./JSRuntime";
|
||||||
|
|
||||||
/** AI message history manager and .ai directory utilities */
|
/** AI message history manager and .git/ai directory utilities */
|
||||||
export class DotAI {
|
export class DotAI {
|
||||||
readonly fs: JSRuntimeFS;
|
readonly fs: JSRuntimeFS;
|
||||||
readonly historyDir: string;
|
readonly historyDir: string;
|
||||||
@@ -11,7 +11,7 @@ export class DotAI {
|
|||||||
constructor(fs: JSRuntimeFS, workingDir: string = "/") {
|
constructor(fs: JSRuntimeFS, workingDir: string = "/") {
|
||||||
this.fs = fs;
|
this.fs = fs;
|
||||||
this.workingDir = workingDir;
|
this.workingDir = workingDir;
|
||||||
this.historyDir = join(workingDir, ".ai", "history");
|
this.historyDir = join(workingDir, ".git", "ai", "history");
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Generate a unique session name based on the current date and time */
|
/** Generate a unique session name based on the current date and time */
|
||||||
@@ -31,8 +31,6 @@ export class DotAI {
|
|||||||
return filename;
|
return filename;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/** Check if the history directory exists */
|
/** Check if the history directory exists */
|
||||||
async historyDirExists(): Promise<boolean> {
|
async historyDirExists(): Promise<boolean> {
|
||||||
try {
|
try {
|
||||||
@@ -51,10 +49,9 @@ export class DotAI {
|
|||||||
// Validate messages before saving
|
// Validate messages before saving
|
||||||
this.validateMessages(messages);
|
this.validateMessages(messages);
|
||||||
|
|
||||||
// Always create the .ai directory and write session history
|
|
||||||
// Create the history directory if it doesn't exist
|
// Create the history directory if it doesn't exist
|
||||||
if (!(await this.historyDirExists())) {
|
if (!(await this.historyDirExists())) {
|
||||||
await this.setupAiHistoryDir();
|
await this.fs.mkdir(this.historyDir, { recursive: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
const sessionFile = join(this.historyDir, sessionName + ".jsonl");
|
const sessionFile = join(this.historyDir, sessionName + ".jsonl");
|
||||||
@@ -122,29 +119,11 @@ export class DotAI {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates .ai/history directory and ensures .ai/ is gitignored at the project root.
|
* Read the model from .git/ai/MODEL file
|
||||||
*/
|
|
||||||
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> {
|
async readAiModel(): Promise<string | undefined> {
|
||||||
try {
|
try {
|
||||||
const modelPath = join(this.workingDir, ".ai", "MODEL");
|
const modelPath = join(this.workingDir, ".git", "ai", "MODEL");
|
||||||
const content = await this.fs.readFile(modelPath, "utf8");
|
const content = await this.fs.readFile(modelPath, "utf8");
|
||||||
return content.trim();
|
return content.trim();
|
||||||
} catch {
|
} catch {
|
||||||
@@ -153,32 +132,29 @@ export class DotAI {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Write the model to .ai/MODEL file
|
* Write the model to .git/ai/MODEL file
|
||||||
*/
|
*/
|
||||||
async writeAiModel(model: string): Promise<void> {
|
async writeAiModel(model: string): Promise<void> {
|
||||||
const aiDir = join(this.workingDir, ".ai");
|
const aiDir = join(this.workingDir, ".git", "ai");
|
||||||
const modelPath = join(aiDir, "MODEL");
|
const modelPath = join(aiDir, "MODEL");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Ensure .ai directory exists
|
// Ensure .git/ai directory exists
|
||||||
await this.fs.mkdir(aiDir, { recursive: true });
|
await this.fs.mkdir(aiDir, { recursive: true });
|
||||||
|
|
||||||
// Ensure .ai/ is gitignored
|
|
||||||
await this.ensureAiGitignored();
|
|
||||||
|
|
||||||
// Write the model
|
// Write the model
|
||||||
await this.fs.writeFile(modelPath, model.trim() + "\n");
|
await this.fs.writeFile(modelPath, model.trim() + "\n");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn(`Failed to write .ai/MODEL file: ${error}`);
|
console.warn(`Failed to write .git/ai/MODEL file: ${error}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Read parameters from .ai/PARAMETERS file
|
* Read parameters from .git/ai/PARAMETERS file
|
||||||
*/
|
*/
|
||||||
async readAiParameters(): Promise<Record<string, string>> {
|
async readAiParameters(): Promise<Record<string, string>> {
|
||||||
try {
|
try {
|
||||||
const parametersPath = join(this.workingDir, ".ai", "PARAMETERS");
|
const parametersPath = join(this.workingDir, ".git", "ai", "PARAMETERS");
|
||||||
const content = await this.fs.readFile(parametersPath, "utf8");
|
const content = await this.fs.readFile(parametersPath, "utf8");
|
||||||
|
|
||||||
const parameters: Record<string, string> = {};
|
const parameters: Record<string, string> = {};
|
||||||
@@ -203,19 +179,16 @@ export class DotAI {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Write parameters to .ai/PARAMETERS file
|
* Write parameters to .git/ai/PARAMETERS file
|
||||||
*/
|
*/
|
||||||
async writeAiParameters(parameters: Record<string, string>): Promise<void> {
|
async writeAiParameters(parameters: Record<string, string>): Promise<void> {
|
||||||
const aiDir = join(this.workingDir, ".ai");
|
const aiDir = join(this.workingDir, ".git", "ai");
|
||||||
const parametersPath = join(aiDir, "PARAMETERS");
|
const parametersPath = join(aiDir, "PARAMETERS");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Ensure .ai directory exists
|
// Ensure .git/ai directory exists
|
||||||
await this.fs.mkdir(aiDir, { recursive: true });
|
await this.fs.mkdir(aiDir, { recursive: true });
|
||||||
|
|
||||||
// Ensure .ai/ is gitignored
|
|
||||||
await this.ensureAiGitignored();
|
|
||||||
|
|
||||||
// Format parameters as key=value pairs
|
// Format parameters as key=value pairs
|
||||||
const lines = Object.entries(parameters).map(([key, value]) =>
|
const lines = Object.entries(parameters).map(([key, value]) =>
|
||||||
`${key}=${value}`
|
`${key}=${value}`
|
||||||
@@ -225,12 +198,12 @@ export class DotAI {
|
|||||||
// Write the parameters
|
// Write the parameters
|
||||||
await this.fs.writeFile(parametersPath, content);
|
await this.fs.writeFile(parametersPath, content);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn(`Failed to write .ai/PARAMETERS file: ${error}`);
|
console.warn(`Failed to write .git/ai/PARAMETERS file: ${error}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update a single parameter in .ai/PARAMETERS file
|
* Update a single parameter in .git/ai/PARAMETERS file
|
||||||
*/
|
*/
|
||||||
async updateAiParameter(key: string, value: string): Promise<void> {
|
async updateAiParameter(key: string, value: string): Promise<void> {
|
||||||
const currentParameters = await this.readAiParameters();
|
const currentParameters = await this.readAiParameters();
|
||||||
@@ -301,47 +274,4 @@ export class DotAI {
|
|||||||
return null;
|
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}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -14,6 +14,27 @@ const createMockNostr = (): NPool => ({
|
|||||||
close: vi.fn(),
|
close: vi.fn(),
|
||||||
}) as unknown as NPool;
|
}) as unknown as NPool;
|
||||||
|
|
||||||
|
// Mock JSZip
|
||||||
|
vi.mock('jszip', () => ({
|
||||||
|
default: class MockJSZip {
|
||||||
|
files: Record<string, { dir: boolean; async: () => Uint8Array }> = {};
|
||||||
|
|
||||||
|
static async loadAsync(buffer: ArrayBuffer) {
|
||||||
|
const instance = new MockJSZip();
|
||||||
|
// Add a mock file entry
|
||||||
|
instance.files['package.json'] = {
|
||||||
|
dir: false,
|
||||||
|
async: () => new Uint8Array(buffer)
|
||||||
|
};
|
||||||
|
return instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
async file(name: string) {
|
||||||
|
return this.files[name];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
// Mock filesystem for testing
|
// Mock filesystem for testing
|
||||||
class MockFS implements JSRuntimeFS {
|
class MockFS implements JSRuntimeFS {
|
||||||
private files: Map<string, string | Uint8Array> = new Map();
|
private files: Map<string, string | Uint8Array> = new Map();
|
||||||
@@ -269,6 +290,156 @@ describe('ProjectsManager', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('importProjectFromZip', () => {
|
||||||
|
it('should preserve original project name when overwriting', async () => {
|
||||||
|
await projectsManager.init();
|
||||||
|
|
||||||
|
// Create an existing project with a specific name
|
||||||
|
await fs.mkdir('/projects/my-project');
|
||||||
|
await fs.mkdir('/projects/my-project/.git');
|
||||||
|
await fs.writeFile('/projects/my-project/package.json', '{"name": "original-name"}');
|
||||||
|
|
||||||
|
// Mock the git methods to simulate existing project
|
||||||
|
const mockGit = {
|
||||||
|
init: vi.fn(),
|
||||||
|
clone: vi.fn(),
|
||||||
|
add: vi.fn(),
|
||||||
|
commit: vi.fn(),
|
||||||
|
getConfig: vi.fn(),
|
||||||
|
getAllFiles: vi.fn().mockResolvedValue(['package.json']),
|
||||||
|
} as Partial<import('./git').Git>;
|
||||||
|
|
||||||
|
// Replace git instance
|
||||||
|
Object.assign(projectsManager, { git: mockGit });
|
||||||
|
|
||||||
|
// Create a mock ZIP file with different name
|
||||||
|
const zipFile = new File(['test content'], 'different-name.zip', { type: 'application/zip' });
|
||||||
|
|
||||||
|
// Mock arrayBuffer method
|
||||||
|
Object.defineProperty(zipFile, 'arrayBuffer', {
|
||||||
|
value: () => Promise.resolve(new TextEncoder().encode('test content').buffer),
|
||||||
|
writable: false
|
||||||
|
});
|
||||||
|
|
||||||
|
// Import with overwrite
|
||||||
|
const project = await projectsManager.importProjectFromZip(zipFile, 'my-project', true);
|
||||||
|
|
||||||
|
// Should preserve original project name
|
||||||
|
expect(project.name).toBe('my-project');
|
||||||
|
expect(project.id).toBe('my-project');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should use new project name when not overwriting', async () => {
|
||||||
|
await projectsManager.init();
|
||||||
|
|
||||||
|
// Mock the git methods
|
||||||
|
const mockGit = {
|
||||||
|
init: vi.fn(),
|
||||||
|
clone: vi.fn(),
|
||||||
|
add: vi.fn(),
|
||||||
|
commit: vi.fn(),
|
||||||
|
getConfig: vi.fn(),
|
||||||
|
getAllFiles: vi.fn().mockResolvedValue(['package.json']),
|
||||||
|
} as Partial<import('./git').Git>;
|
||||||
|
|
||||||
|
// Replace git instance
|
||||||
|
Object.assign(projectsManager, { git: mockGit });
|
||||||
|
|
||||||
|
// Create a mock ZIP file
|
||||||
|
const zipFile = new File(['test content'], 'new-project.zip', { type: 'application/zip' });
|
||||||
|
|
||||||
|
// Mock arrayBuffer method
|
||||||
|
Object.defineProperty(zipFile, 'arrayBuffer', {
|
||||||
|
value: () => Promise.resolve(new TextEncoder().encode('test content').buffer),
|
||||||
|
writable: false
|
||||||
|
});
|
||||||
|
|
||||||
|
// Import without overwrite
|
||||||
|
const project = await projectsManager.importProjectFromZip(zipFile, undefined, false);
|
||||||
|
|
||||||
|
// Should use formatted name from ID
|
||||||
|
expect(project.name).toBe('new-project');
|
||||||
|
expect(project.id).toBe('new-project');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should prevent zip slip attacks during import', async () => {
|
||||||
|
await projectsManager.init();
|
||||||
|
|
||||||
|
// Mock the git methods
|
||||||
|
const mockGit = {
|
||||||
|
init: vi.fn(),
|
||||||
|
clone: vi.fn(),
|
||||||
|
add: vi.fn(),
|
||||||
|
commit: vi.fn(),
|
||||||
|
getConfig: vi.fn(),
|
||||||
|
getAllFiles: vi.fn().mockResolvedValue([]),
|
||||||
|
} as Partial<import('./git').Git>;
|
||||||
|
|
||||||
|
// Replace git instance
|
||||||
|
Object.assign(projectsManager, { git: mockGit });
|
||||||
|
|
||||||
|
// Create a mock ZIP file that would try to escape the project directory
|
||||||
|
const zipFile = new File(['malicious content'], 'malicious.zip', { type: 'application/zip' });
|
||||||
|
|
||||||
|
// Mock JSZip to simulate a malicious ZIP with path traversal
|
||||||
|
const JSZip = await import('jszip');
|
||||||
|
|
||||||
|
const mockLoadAsync = vi.fn().mockResolvedValue({
|
||||||
|
files: {
|
||||||
|
'../../../etc/passwd': {
|
||||||
|
dir: false,
|
||||||
|
async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3]))
|
||||||
|
},
|
||||||
|
'../../outside.txt': {
|
||||||
|
dir: false,
|
||||||
|
async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6]))
|
||||||
|
},
|
||||||
|
'safe-file.txt': {
|
||||||
|
dir: false,
|
||||||
|
async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.spyOn(JSZip.default, 'loadAsync').mockImplementation(mockLoadAsync);
|
||||||
|
|
||||||
|
// Mock arrayBuffer method
|
||||||
|
Object.defineProperty(zipFile, 'arrayBuffer', {
|
||||||
|
value: () => Promise.resolve(new ArrayBuffer(0)),
|
||||||
|
writable: false
|
||||||
|
});
|
||||||
|
|
||||||
|
// Spy on console.warn to check for security warnings
|
||||||
|
const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Import the malicious ZIP
|
||||||
|
const project = await projectsManager.importProjectFromZip(zipFile, undefined, false);
|
||||||
|
|
||||||
|
// Should have completed successfully (safe files extracted)
|
||||||
|
expect(project).toBeDefined();
|
||||||
|
|
||||||
|
// Should have logged a security warning about skipped files
|
||||||
|
expect(consoleSpy).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('Skipped 2 files due to resolving to paths outside the project direcotry:'),
|
||||||
|
['../../../etc/passwd', '../../outside.txt']
|
||||||
|
);
|
||||||
|
|
||||||
|
// Verify that only safe files would be written (check writeFile calls)
|
||||||
|
const writeFileCalls = (fs.writeFile as unknown as { mock?: { calls: [string, unknown][] } }).mock?.calls || [];
|
||||||
|
const maliciousPaths = writeFileCalls.filter((call: [string, unknown]) =>
|
||||||
|
call[0].includes('../') || call[0].includes('etc/passwd') || call[0].includes('outside.txt')
|
||||||
|
);
|
||||||
|
expect(maliciousPaths).toHaveLength(0);
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
// Restore mocks
|
||||||
|
consoleSpy.mockRestore();
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('renameProject', () => {
|
describe('renameProject', () => {
|
||||||
it('should rename a project directory', async () => {
|
it('should rename a project directory', async () => {
|
||||||
await projectsManager.init();
|
await projectsManager.init();
|
||||||
|
|||||||
+253
-9
@@ -1,6 +1,8 @@
|
|||||||
import { Buffer } from 'buffer';
|
import { Buffer } from 'buffer';
|
||||||
import type { Git } from '@/lib/git';
|
import JSZip from 'jszip';
|
||||||
|
import { Git } from '@/lib/git';
|
||||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||||
|
import { ensurePersistentStorage } from '@/lib/persistentStorage';
|
||||||
|
|
||||||
// Polyfill Buffer for browser
|
// Polyfill Buffer for browser
|
||||||
if (typeof window !== 'undefined') {
|
if (typeof window !== 'undefined') {
|
||||||
@@ -44,12 +46,6 @@ export class ProjectsManager {
|
|||||||
async createProject(name: string, customId?: string): Promise<Project> {
|
async createProject(name: string, customId?: string): Promise<Project> {
|
||||||
const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId, { depth: 1 });
|
const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId, { depth: 1 });
|
||||||
|
|
||||||
try {
|
|
||||||
await this.fs.mkdir(this.dir + `/${project.id}/.ai/history`, { recursive: true });
|
|
||||||
} catch {
|
|
||||||
// Directory might already exist
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete README.md if it exists
|
// Delete README.md if it exists
|
||||||
try {
|
try {
|
||||||
await this.fs.unlink(`${project.path}/README.md`);
|
await this.fs.unlink(`${project.path}/README.md`);
|
||||||
@@ -73,8 +69,8 @@ export class ProjectsManager {
|
|||||||
// Add all files to git
|
// Add all files to git
|
||||||
const files = await this.getAllFiles(project.path);
|
const files = await this.getAllFiles(project.path);
|
||||||
for (const file of files) {
|
for (const file of files) {
|
||||||
// Skip .git directory and other hidden files we don't want to track
|
// Skip .git directory
|
||||||
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
|
if (!file.startsWith('.git/')) {
|
||||||
await this.git.add({
|
await this.git.add({
|
||||||
dir: project.path,
|
dir: project.path,
|
||||||
filepath: file,
|
filepath: file,
|
||||||
@@ -92,9 +88,196 @@ export class ProjectsManager {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 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;
|
return project;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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, '');
|
||||||
|
const generatedId = baseName
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9]+/g, '-')
|
||||||
|
.replace(/^-+|-+$/g, '');
|
||||||
|
|
||||||
|
// Determine the project ID to use
|
||||||
|
let id: string;
|
||||||
|
if (customId) {
|
||||||
|
// Use the provided custom ID (for overwrite scenarios)
|
||||||
|
id = customId;
|
||||||
|
} else {
|
||||||
|
// If no custom ID, generate a unique ID (for new projects)
|
||||||
|
id = await this.generateUniqueProjectId(generatedId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const projectPath = `${this.dir}/${id}`;
|
||||||
|
const projectExists = await this.projectExists(id);
|
||||||
|
|
||||||
|
// Check if project with this ID already exists when not overwriting
|
||||||
|
if (projectExists && !overwrite) {
|
||||||
|
throw new Error(`Project with ID "${id}" already exists`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get original project name if overwriting, otherwise use formatted name
|
||||||
|
let projectName: string;
|
||||||
|
if (overwrite && projectExists) {
|
||||||
|
const existingProject = await this.getProject(id);
|
||||||
|
projectName = existingProject?.name || this.formatProjectName(id);
|
||||||
|
} else {
|
||||||
|
projectName = this.formatProjectName(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 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 (projectExists && overwrite) {
|
||||||
|
const existingFiles = await this.getAllFiles(projectPath);
|
||||||
|
for (const file of existingFiles) {
|
||||||
|
// Preserve .git directory
|
||||||
|
if (!file.startsWith('.git/')) {
|
||||||
|
try {
|
||||||
|
await this.fs.unlink(`${projectPath}/${file}`);
|
||||||
|
} catch {
|
||||||
|
// Ignore deletion errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read the zip file
|
||||||
|
const arrayBuffer = await zipFile.arrayBuffer();
|
||||||
|
const zip = await JSZip.loadAsync(arrayBuffer);
|
||||||
|
|
||||||
|
// Extract all files from the zip with security validation
|
||||||
|
const extractedFiles: string[] = [];
|
||||||
|
const skippedFiles: string[] = [];
|
||||||
|
|
||||||
|
for (const [relativePath, zipEntry] of Object.entries(zip.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;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (zipEntry.dir) {
|
||||||
|
// Create the directory structure
|
||||||
|
await this.fs.mkdir(extractPath, { recursive: true });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract file content
|
||||||
|
const content = await zipEntry.async('uint8array');
|
||||||
|
|
||||||
|
// 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 direcotry:`, skippedFiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get filesystem stats for timestamps
|
||||||
|
const stats = await this.fs.stat(projectPath);
|
||||||
|
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||||
|
|
||||||
|
// 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
|
||||||
|
if (!file.startsWith('.git/')) {
|
||||||
|
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
|
||||||
|
const projectFiles = await this.getAllFiles(projectPath);
|
||||||
|
for (const file of projectFiles) {
|
||||||
|
// Skip .git directory
|
||||||
|
if (!file.startsWith('.git/')) {
|
||||||
|
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]',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
name: projectName,
|
||||||
|
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> {
|
async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise<Project> {
|
||||||
const id = customId || await this.generateUniqueProjectId(name);
|
const id = customId || await this.generateUniqueProjectId(name);
|
||||||
|
|
||||||
@@ -119,6 +302,14 @@ export class ProjectsManager {
|
|||||||
const stats = await this.fs.stat(projectPath);
|
const stats = await this.fs.stat(projectPath);
|
||||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||||
|
|
||||||
|
// Automatically request persistent storage after project cloning
|
||||||
|
try {
|
||||||
|
await ensurePersistentStorage();
|
||||||
|
} catch (error) {
|
||||||
|
// Don't fail project cloning if persistent storage request fails
|
||||||
|
console.warn('Failed to request persistent storage after project cloning:', error);
|
||||||
|
}
|
||||||
|
|
||||||
// Return the full project object with dynamically generated properties
|
// Return the full project object with dynamically generated properties
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
@@ -402,4 +593,57 @@ export class ProjectsManager {
|
|||||||
|
|
||||||
return files;
|
return files;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Safe path join that normalizes the result to prevent directory traversal
|
||||||
|
*/
|
||||||
|
private join(...paths: string[]): string {
|
||||||
|
// Simple path joining with normalization
|
||||||
|
const joined = paths.join('/').replace(/\/+/g, '/');
|
||||||
|
|
||||||
|
// Normalize path separators and resolve .. and . components
|
||||||
|
const parts = joined.split('/').filter(part => part !== '');
|
||||||
|
const normalized: string[] = [];
|
||||||
|
|
||||||
|
for (const part of parts) {
|
||||||
|
if (part === '..') {
|
||||||
|
normalized.pop();
|
||||||
|
} else if (part !== '.') {
|
||||||
|
normalized.push(part);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return '/' + normalized.join('/');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a path is within the project directory
|
||||||
|
*/
|
||||||
|
private isPathWithinProject(extractPath: string, projectPath: string): boolean {
|
||||||
|
// Normalize both paths
|
||||||
|
const normalizedExtractPath = this.normalize(extractPath);
|
||||||
|
const normalizedProjectPath = this.normalize(projectPath);
|
||||||
|
|
||||||
|
// Check if the extract path starts with the project path
|
||||||
|
return normalizedExtractPath.startsWith(normalizedProjectPath + '/') ||
|
||||||
|
normalizedExtractPath === normalizedProjectPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Normalize a path by resolving . and .. components
|
||||||
|
*/
|
||||||
|
private normalize(path: string): string {
|
||||||
|
const parts = path.split('/').filter(part => part !== '');
|
||||||
|
const normalized: string[] = [];
|
||||||
|
|
||||||
|
for (const part of parts) {
|
||||||
|
if (part === '..') {
|
||||||
|
normalized.pop();
|
||||||
|
} else if (part !== '.') {
|
||||||
|
normalized.push(part);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return '/' + normalized.join('/');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -250,7 +250,6 @@ export class SessionManager {
|
|||||||
model,
|
model,
|
||||||
messages,
|
messages,
|
||||||
tools: session.tools && Object.keys(session.tools).length > 0 ? Object.values(session.tools) : undefined,
|
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: true,
|
||||||
stream_options: {
|
stream_options: {
|
||||||
include_usage: true,
|
include_usage: true,
|
||||||
@@ -301,9 +300,9 @@ export class SessionManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (delta?.tool_calls) {
|
if (delta?.tool_calls) {
|
||||||
for (const toolCallDelta of delta.tool_calls) {
|
for (let i = 0; i < delta.tool_calls.length; i++) {
|
||||||
const index = toolCallDelta.index;
|
const toolCallDelta = delta.tool_calls[i];
|
||||||
if (index === undefined) continue;
|
const index = toolCallDelta.index ?? i; // Fix for Gemini models
|
||||||
|
|
||||||
accumulatedToolCalls[index] ??= {
|
accumulatedToolCalls[index] ??= {
|
||||||
id: '',
|
id: '',
|
||||||
|
|||||||
@@ -13,11 +13,11 @@ export function createAIClient(provider: AIProvider, user?: NUser): OpenAI {
|
|||||||
baseURL: provider.baseURL,
|
baseURL: provider.baseURL,
|
||||||
apiKey: provider.apiKey ?? '',
|
apiKey: provider.apiKey ?? '',
|
||||||
dangerouslyAllowBrowser: true,
|
dangerouslyAllowBrowser: true,
|
||||||
defaultHeaders: {
|
defaultHeaders: provider.id === 'openrouter' ? {
|
||||||
// https://openrouter.ai/docs/app-attribution
|
// https://openrouter.ai/docs/app-attribution
|
||||||
'HTTP-Referer': 'https://shakespeare.diy',
|
'HTTP-Referer': 'https://shakespeare.diy',
|
||||||
'X-Title': 'Shakespeare',
|
'X-Title': 'Shakespeare',
|
||||||
},
|
} : {},
|
||||||
};
|
};
|
||||||
|
|
||||||
let openai: OpenAI;
|
let openai: OpenAI;
|
||||||
|
|||||||
+139
-8
@@ -96,7 +96,15 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
|||||||
const name = packageInfo.name ?? packageName;
|
const name = packageInfo.name ?? packageName;
|
||||||
const specifier = `${name}@${version}${packagePath}`;
|
const specifier = `${name}@${version}${packagePath}`;
|
||||||
|
|
||||||
const url = new URL(`https://esm.sh/*${specifier}`);
|
// Handle JSR packages with correct ESM.sh JSR format
|
||||||
|
let url: URL;
|
||||||
|
if (packageName.startsWith("@jsr/")) {
|
||||||
|
// Convert @jsr/scope__package to jsr/@scope/package format for ESM.sh
|
||||||
|
const jsrName = packageName.slice(5).replace("__", "/");
|
||||||
|
url = new URL(`https://esm.sh/jsr/@${jsrName}@${version}${packagePath}`);
|
||||||
|
} else {
|
||||||
|
url = new URL(`https://esm.sh/*${specifier}`);
|
||||||
|
}
|
||||||
|
|
||||||
if (target) {
|
if (target) {
|
||||||
url.searchParams.set("target", target);
|
url.searchParams.set("target", target);
|
||||||
@@ -110,20 +118,109 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
|||||||
|
|
||||||
// Handle relative or absolute imports inside esm.sh modules
|
// Handle relative or absolute imports inside esm.sh modules
|
||||||
build.onResolve({ filter: /.*/, namespace: "esm" }, async (args) => {
|
build.onResolve({ filter: /.*/, namespace: "esm" }, async (args) => {
|
||||||
|
// Check if this is a bare package import (not a relative path)
|
||||||
|
// Note: CSS assets and some other relative imports don't use ./ prefix
|
||||||
|
const isLikelyAsset = /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot|ico|webp|avif)$/i.test(args.path);
|
||||||
|
const isRelativePath = args.path.startsWith("./") || args.path.startsWith("../") || args.path.startsWith("/") || isLikelyAsset;
|
||||||
|
|
||||||
|
if (!isRelativePath) {
|
||||||
|
try {
|
||||||
|
// This is a bare import like "@emotion/is-prop-valid" - treat it as a new package
|
||||||
|
const packageName = args.path.startsWith("@")
|
||||||
|
? args.path.split("/").slice(0, 2).join("/")
|
||||||
|
: args.path.split("/")[0];
|
||||||
|
|
||||||
|
// Handle transitive dependency versions
|
||||||
|
const keys: string[] = [];
|
||||||
|
try {
|
||||||
|
const importerPackage = extractPackageName(args.importer);
|
||||||
|
keys.push(
|
||||||
|
`node_modules/${importerPackage}/node_modules/${packageName}`,
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
// fallthrough
|
||||||
|
}
|
||||||
|
|
||||||
|
if (packageName.startsWith("@jsr/")) {
|
||||||
|
keys.push(`node_modules/@${packageName.slice(5).replace("__", "/")}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
keys.push(`node_modules/${packageName}`);
|
||||||
|
|
||||||
|
const packageInfo = keys
|
||||||
|
.map((key) => packageLock.packages[key])
|
||||||
|
.find((info) => info);
|
||||||
|
|
||||||
|
const packagePath = args.path.slice(packageName.length);
|
||||||
|
const version = packageInfo?.version;
|
||||||
|
|
||||||
|
if (version) {
|
||||||
|
const name = packageInfo.name ?? packageName;
|
||||||
|
const specifier = `${name}@${version}${packagePath}`;
|
||||||
|
|
||||||
|
// Handle JSR packages with correct ESM.sh JSR format
|
||||||
|
let url: URL;
|
||||||
|
if (packageName.startsWith("@jsr/")) {
|
||||||
|
// Convert @jsr/scope__package to jsr/@scope/package format for ESM.sh
|
||||||
|
const jsrName = packageName.slice(5).replace("__", "/");
|
||||||
|
url = new URL(`https://esm.sh/jsr/@${jsrName}@${version}${packagePath}`);
|
||||||
|
} else {
|
||||||
|
url = new URL(`https://esm.sh/*${specifier}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (target) {
|
||||||
|
url.searchParams.set("target", target);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
path: url.toString(),
|
||||||
|
namespace: "esm",
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
// If we can't find the version in package lock, let ESM.sh resolve it
|
||||||
|
// This handles transitive dependencies that might not be in our package-lock
|
||||||
|
let url: URL;
|
||||||
|
if (packageName.startsWith("@jsr/")) {
|
||||||
|
// Convert @jsr/scope__package to jsr/@scope/package format for ESM.sh
|
||||||
|
const jsrName = packageName.slice(5).replace("__", "/");
|
||||||
|
url = new URL(`https://esm.sh/jsr/@${jsrName}${packagePath}`);
|
||||||
|
} else {
|
||||||
|
url = new URL(`https://esm.sh/${args.path}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (target) {
|
||||||
|
url.searchParams.set("target", target);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
path: url.toString(),
|
||||||
|
namespace: "esm",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// If package resolution fails, fall through to URL resolution
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let fullURL: URL;
|
let fullURL: URL;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
fullURL = new URL(args.path);
|
fullURL = new URL(args.path);
|
||||||
} catch {
|
} catch {
|
||||||
try {
|
try {
|
||||||
// When resolving relative paths, it's important the baseURL is *after* any redirects.
|
// Handle ESM.sh internal paths like /@jsr/package__name@version/...
|
||||||
// For example, `https://esm.sh/@fontsource/[email protected]` redirects to `https://esm.sh/@fontsource/[email protected]/index.css`
|
if (args.path.startsWith("/")) {
|
||||||
// and this changes the outcome of resolving paths like `./font.woff2` and `../font.woff2`
|
fullURL = new URL(`https://esm.sh${args.path}`);
|
||||||
const baseURL = args.path.startsWith("./")
|
} else {
|
||||||
? await getRedirectedURL(args.importer)
|
// When resolving relative paths, it's important the baseURL is *after* any redirects.
|
||||||
: args.importer;
|
// For example, `https://esm.sh/@fontsource/[email protected]` redirects to `https://esm.sh/@fontsource/[email protected]/index.css`
|
||||||
|
// and this changes the outcome of resolving paths like `./font.woff2` and `../font.woff2`
|
||||||
|
const baseURL = args.path.startsWith("./")
|
||||||
|
? await getRedirectedURL(args.importer)
|
||||||
|
: args.importer;
|
||||||
|
|
||||||
fullURL = new URL(args.path, baseURL);
|
fullURL = new URL(args.path, baseURL);
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
return {
|
return {
|
||||||
errors: [{ text: `Could not resolve ${args.path}` }],
|
errors: [{ text: `Could not resolve ${args.path}` }],
|
||||||
@@ -146,6 +243,40 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
|
// Special handling for JSR packages when specific version isn't available
|
||||||
|
if (args.path.includes('esm.sh/jsr/') && res.status === 404) {
|
||||||
|
// Try without version (let ESM.sh pick the latest available version)
|
||||||
|
const urlWithoutVersion = args.path.replace(/@[\d.]+(\?|$)/, '$1');
|
||||||
|
|
||||||
|
const fallbackRes = await fetch(urlWithoutVersion);
|
||||||
|
|
||||||
|
if (fallbackRes.ok) {
|
||||||
|
if (fallbackRes.redirected) {
|
||||||
|
redirectedURLs.set(args.path, fallbackRes.url);
|
||||||
|
}
|
||||||
|
|
||||||
|
let loader: Loader | undefined;
|
||||||
|
const contentType = fallbackRes.headers.get("Content-Type")?.split(";")[0];
|
||||||
|
|
||||||
|
if (contentType) {
|
||||||
|
if (contentType === "application/javascript") {
|
||||||
|
loader = "js";
|
||||||
|
} else if (contentType === "text/css") {
|
||||||
|
loader = "css";
|
||||||
|
} else {
|
||||||
|
loader = "text";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const contents = await fallbackRes.text();
|
||||||
|
|
||||||
|
return {
|
||||||
|
contents,
|
||||||
|
loader,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
throw new Error(`Failed to fetch ${args.path}`);
|
throw new Error(`Failed to fetch ${args.path}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin {
|
|||||||
async (args) => {
|
async (args) => {
|
||||||
const ext = path.extname(args.path).slice(1);
|
const ext = path.extname(args.path).slice(1);
|
||||||
|
|
||||||
if (!["ts", "tsx", "js", "jsx", "css"].includes(ext)) {
|
if (!["ts", "tsx", "js", "jsx", "css", "json"].includes(ext)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,7 +56,7 @@ async function tryFileVariants(
|
|||||||
fs: JSRuntimeFS,
|
fs: JSRuntimeFS,
|
||||||
basePath: string,
|
basePath: string,
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
const extensions = [".ts", ".tsx", ".js", ".jsx", ".css"];
|
const extensions = [".ts", ".tsx", ".js", ".jsx", ".css", ".json"];
|
||||||
const stat = await statSafe(fs, basePath);
|
const stat = await statSafe(fs, basePath);
|
||||||
|
|
||||||
// If it's a file, check if it exists
|
// If it's a file, check if it exists
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||||
import { buildProject } from './index';
|
import { buildProject } from './index';
|
||||||
import { copyFiles } from '../copyFiles';
|
import { copyFiles } from '../copyFiles';
|
||||||
|
import { esmPlugin } from './esmPlugin';
|
||||||
import type { JSRuntimeFS } from '../JSRuntime';
|
import type { JSRuntimeFS } from '../JSRuntime';
|
||||||
|
|
||||||
// Mock esbuild
|
// Mock esbuild
|
||||||
@@ -258,3 +259,31 @@ describe('buildProject', () => {
|
|||||||
expect(copyFiles).toHaveBeenCalledWith(mockFS, mockFS, '/test/project/public', '/test/project/dist');
|
expect(copyFiles).toHaveBeenCalledWith(mockFS, mockFS, '/test/project/public', '/test/project/dist');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('esmPlugin JSR package handling', () => {
|
||||||
|
it('should generate correct URLs for JSR packages', () => {
|
||||||
|
const packageLock = {
|
||||||
|
packages: {
|
||||||
|
'node_modules/@jsr/nostrify__nostrify': {
|
||||||
|
version: '0.46.11',
|
||||||
|
name: '@jsr/nostrify__nostrify'
|
||||||
|
},
|
||||||
|
'node_modules/@nostrify/nostrify': {
|
||||||
|
version: '0.46.11',
|
||||||
|
name: '@jsr/nostrify__nostrify'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const plugin = esmPlugin(packageLock, 'esnext');
|
||||||
|
|
||||||
|
// Test the plugin setup to ensure it handles JSR packages correctly
|
||||||
|
expect(plugin.name).toBe('esm');
|
||||||
|
expect(plugin.setup).toBeDefined();
|
||||||
|
|
||||||
|
// The actual URL generation is tested through the resolve handlers
|
||||||
|
// which are difficult to test directly, but the fix ensures:
|
||||||
|
// - @jsr/[email protected] -> https://esm.sh/jsr/nostrify/[email protected]
|
||||||
|
// - Regular packages still use -> https://esm.sh/*package@version
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -61,7 +61,7 @@ describe('configUtils', () => {
|
|||||||
apiKey: 'sk-test123',
|
apiKey: 'sk-test123',
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
recentlyUsedModels: ['gpt-4', 'gpt-3.5-turbo'],
|
recentlyUsedModels: ['openai/gpt-4', 'openai/gpt-3.5-turbo'],
|
||||||
};
|
};
|
||||||
|
|
||||||
describe('readAISettings', () => {
|
describe('readAISettings', () => {
|
||||||
@@ -97,26 +97,6 @@ describe('configUtils', () => {
|
|||||||
recentlyUsedModels: [],
|
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', () => {
|
describe('writeAISettings', () => {
|
||||||
@@ -188,26 +168,6 @@ describe('configUtils', () => {
|
|||||||
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
|
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', () => {
|
describe('writeGitSettings', () => {
|
||||||
|
|||||||
+39
-130
@@ -1,11 +1,40 @@
|
|||||||
|
import z from 'zod';
|
||||||
|
import { filteredArray } from '@/lib/schema';
|
||||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||||
import type { AISettings, AIProvider } from '@/contexts/AISettingsContext';
|
import type { AIProvider, AISettings } from '@/contexts/AISettingsContext';
|
||||||
import type { GitSettings } from '@/contexts/GitSettingsContext';
|
import type { GitSettings } from '@/contexts/GitSettingsContext';
|
||||||
|
|
||||||
const CONFIG_DIR = '/config';
|
const CONFIG_DIR = '/config';
|
||||||
const AI_CONFIG_PATH = `${CONFIG_DIR}/ai.json`;
|
const AI_CONFIG_PATH = `${CONFIG_DIR}/ai.json`;
|
||||||
const GIT_CONFIG_PATH = `${CONFIG_DIR}/git.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
|
* Ensures the config directory exists
|
||||||
*/
|
*/
|
||||||
@@ -17,49 +46,6 @@ 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)
|
* Read AI settings from VFS (with automatic migration from localStorage)
|
||||||
*/
|
*/
|
||||||
@@ -69,50 +55,16 @@ export async function readAISettings(fs: JSRuntimeFS): Promise<AISettings> {
|
|||||||
recentlyUsedModels: [],
|
recentlyUsedModels: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
// Try to read from VFS first
|
|
||||||
try {
|
try {
|
||||||
const content = await fs.readFile(AI_CONFIG_PATH, 'utf8');
|
const content = await fs.readFile(AI_CONFIG_PATH, 'utf8');
|
||||||
const parsed = JSON.parse(content);
|
const data = JSON.parse(content);
|
||||||
|
return aiSettingsSchema.parse(data);
|
||||||
if (parsed && typeof parsed === 'object' && 'providers' in parsed) {
|
} catch (error) {
|
||||||
// Handle migration from old map format to new array format
|
if (error instanceof z.ZodError) {
|
||||||
let providers;
|
console.error('AI settings parsing error:', error.errors);
|
||||||
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 || [],
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
} catch {
|
return defaultSettings;
|
||||||
// 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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -123,35 +75,6 @@ export async function writeAISettings(fs: JSRuntimeFS, settings: AISettings): Pr
|
|||||||
await fs.writeFile(AI_CONFIG_PATH, JSON.stringify(settings, null, 2), 'utf8');
|
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)
|
* Read Git settings from VFS (with automatic migration from localStorage)
|
||||||
*/
|
*/
|
||||||
@@ -164,25 +87,11 @@ export async function readGitSettings(fs: JSRuntimeFS): Promise<GitSettings> {
|
|||||||
// Try to read from VFS first
|
// Try to read from VFS first
|
||||||
try {
|
try {
|
||||||
const content = await fs.readFile(GIT_CONFIG_PATH, 'utf8');
|
const content = await fs.readFile(GIT_CONFIG_PATH, 'utf8');
|
||||||
const parsed = JSON.parse(content);
|
const data = JSON.parse(content);
|
||||||
|
return gitSettingsSchema.parse(data);
|
||||||
if (parsed && typeof parsed === 'object' && 'credentials' in parsed) {
|
|
||||||
return {
|
|
||||||
credentials: parsed.credentials || {},
|
|
||||||
corsProxy: parsed.corsProxy || 'https://proxy.shakespeare.diy/?url={href}',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
} catch {
|
} catch {
|
||||||
// File doesn't exist or is invalid, try migration
|
return defaultSettings;
|
||||||
}
|
}
|
||||||
|
|
||||||
// If not in VFS, try to migrate from localStorage
|
|
||||||
const migratedSettings = await migrateGitSettingsFromLocalStorage(fs);
|
|
||||||
if (migratedSettings) {
|
|
||||||
return migratedSettings;
|
|
||||||
}
|
|
||||||
|
|
||||||
return defaultSettings;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -242,6 +242,17 @@ const resources = {
|
|||||||
dataClearedSuccessfully: 'Data cleared successfully',
|
dataClearedSuccessfully: 'Data cleared successfully',
|
||||||
dataClearedDescription: 'All local data has been removed. Redirecting to homepage...',
|
dataClearedDescription: 'All local data has been removed. Redirecting to homepage...',
|
||||||
failedToClearData: 'Failed to clear data',
|
failedToClearData: 'Failed to clear data',
|
||||||
|
persistData: 'Persist Data',
|
||||||
|
persistDataDescription: 'Request persistent storage to prevent data loss when browser storage is low. This helps protect your projects and settings.',
|
||||||
|
persistentStorageGranted: 'Persistent storage granted',
|
||||||
|
persistentStorageGrantedDescription: 'Your browser will now protect your data from automatic cleanup.',
|
||||||
|
persistentStorageAlreadyGranted: 'Persistent storage already granted',
|
||||||
|
persistentStorageAlreadyGrantedDescription: 'Your data is already protected from automatic cleanup.',
|
||||||
|
persistentStorageDenied: 'Persistent storage request denied',
|
||||||
|
persistentStorageDeniedDescription: 'Your browser declined the request. Data may still be cleared automatically when storage is low.',
|
||||||
|
persistentStorageNotSupported: 'Persistent storage not supported',
|
||||||
|
persistentStorageNotSupportedDescription: 'Your browser does not support persistent storage requests.',
|
||||||
|
failedToRequestPersistentStorage: 'Failed to request persistent storage',
|
||||||
|
|
||||||
// 404 Page
|
// 404 Page
|
||||||
pageNotFound: 'Oops! Page not found',
|
pageNotFound: 'Oops! Page not found',
|
||||||
@@ -534,6 +545,17 @@ const resources = {
|
|||||||
dataClearedSuccessfully: 'Dados limpos com sucesso',
|
dataClearedSuccessfully: 'Dados limpos com sucesso',
|
||||||
dataClearedDescription: 'Todos os dados locais foram removidos. Redirecionando para a página inicial...',
|
dataClearedDescription: 'Todos os dados locais foram removidos. Redirecionando para a página inicial...',
|
||||||
failedToClearData: 'Falha ao limpar dados',
|
failedToClearData: 'Falha ao limpar dados',
|
||||||
|
persistData: 'Persistir Dados',
|
||||||
|
persistDataDescription: 'Solicitar armazenamento persistente para evitar perda de dados quando o armazenamento do navegador estiver baixo. Isso ajuda a proteger seus projetos e configurações.',
|
||||||
|
persistentStorageGranted: 'Armazenamento persistente concedido',
|
||||||
|
persistentStorageGrantedDescription: 'Seu navegador agora protegerá seus dados da limpeza automática.',
|
||||||
|
persistentStorageAlreadyGranted: 'Armazenamento persistente já concedido',
|
||||||
|
persistentStorageAlreadyGrantedDescription: 'Seus dados já estão protegidos da limpeza automática.',
|
||||||
|
persistentStorageDenied: 'Solicitação de armazenamento persistente negada',
|
||||||
|
persistentStorageDeniedDescription: 'Seu navegador recusou a solicitação. Os dados ainda podem ser limpos automaticamente quando o armazenamento estiver baixo.',
|
||||||
|
persistentStorageNotSupported: 'Armazenamento persistente não suportado',
|
||||||
|
persistentStorageNotSupportedDescription: 'Seu navegador não suporta solicitações de armazenamento persistente.',
|
||||||
|
failedToRequestPersistentStorage: 'Falha ao solicitar armazenamento persistente',
|
||||||
|
|
||||||
// About Settings
|
// About Settings
|
||||||
aboutShakespeare: 'Sobre o Shakespeare',
|
aboutShakespeare: 'Sobre o Shakespeare',
|
||||||
@@ -836,6 +858,17 @@ const resources = {
|
|||||||
dataClearedSuccessfully: '数据清除成功',
|
dataClearedSuccessfully: '数据清除成功',
|
||||||
dataClearedDescription: '所有本地数据已删除。正在重定向到主页...',
|
dataClearedDescription: '所有本地数据已删除。正在重定向到主页...',
|
||||||
failedToClearData: '清除数据失败',
|
failedToClearData: '清除数据失败',
|
||||||
|
persistData: '持久化数据',
|
||||||
|
persistDataDescription: '请求持久存储以防止浏览器存储不足时数据丢失。这有助于保护您的项目和设置。',
|
||||||
|
persistentStorageGranted: '已授予持久存储',
|
||||||
|
persistentStorageGrantedDescription: '您的浏览器现在将保护您的数据免受自动清理。',
|
||||||
|
persistentStorageAlreadyGranted: '已授予持久存储',
|
||||||
|
persistentStorageAlreadyGrantedDescription: '您的数据已受到保护,不会被自动清理。',
|
||||||
|
persistentStorageDenied: '持久存储请求被拒绝',
|
||||||
|
persistentStorageDeniedDescription: '您的浏览器拒绝了请求。当存储不足时,数据仍可能被自动清理。',
|
||||||
|
persistentStorageNotSupported: '不支持持久存储',
|
||||||
|
persistentStorageNotSupportedDescription: '您的浏览器不支持持久存储请求。',
|
||||||
|
failedToRequestPersistentStorage: '请求持久存储失败',
|
||||||
|
|
||||||
// About Settings
|
// About Settings
|
||||||
aboutShakespeare: '关于Shakespeare',
|
aboutShakespeare: '关于Shakespeare',
|
||||||
@@ -1138,6 +1171,17 @@ const resources = {
|
|||||||
dataClearedSuccessfully: 'An share bayanai cikin nasara',
|
dataClearedSuccessfully: 'An share bayanai cikin nasara',
|
||||||
dataClearedDescription: 'An cire duk bayanan gida. Ana turawa zuwa shafin gida...',
|
dataClearedDescription: 'An cire duk bayanan gida. Ana turawa zuwa shafin gida...',
|
||||||
failedToClearData: 'Ya gaza share bayanai',
|
failedToClearData: 'Ya gaza share bayanai',
|
||||||
|
persistData: 'Kiyaye Bayanai',
|
||||||
|
persistDataDescription: 'Nemi ajiyar bayanai ta dindindin don hana asarar bayanai lokacin da ajiyar burauzar ta ragu. Wannan yana taimakawa wajen kare ayyukan ku da saitunan.',
|
||||||
|
persistentStorageGranted: 'An ba da ajiyar ta dindindin',
|
||||||
|
persistentStorageGrantedDescription: 'Burauzar ku yanzu za ta kare bayananku daga share mai sarrafa kansa.',
|
||||||
|
persistentStorageAlreadyGranted: 'An riga an ba da ajiyar ta dindindin',
|
||||||
|
persistentStorageAlreadyGrantedDescription: 'An riga an kare bayananku daga share mai sarrafa kansa.',
|
||||||
|
persistentStorageDenied: 'An ki neman ajiyar ta dindindin',
|
||||||
|
persistentStorageDeniedDescription: 'Burauzar ku ta ki bukatar. Ana iya share bayanai ta atomatik lokacin da ajiya ta ragu.',
|
||||||
|
persistentStorageNotSupported: 'Ba a goyan bayan ajiyar ta dindindin ba',
|
||||||
|
persistentStorageNotSupportedDescription: 'Burauzar ku ba ta goyan bayan bukatun ajiyar ta dindindin ba.',
|
||||||
|
failedToRequestPersistentStorage: 'Ya gaza neman ajiyar ta dindindin',
|
||||||
|
|
||||||
// About Settings
|
// About Settings
|
||||||
aboutShakespeare: 'Game da Shakespeare',
|
aboutShakespeare: 'Game da Shakespeare',
|
||||||
@@ -1440,6 +1484,17 @@ const resources = {
|
|||||||
dataClearedSuccessfully: 'Data ti nu ni aṣeyọri',
|
dataClearedSuccessfully: 'Data ti nu ni aṣeyọri',
|
||||||
dataClearedDescription: 'Gbogbo data agbegbe ti yọ kuro. N ṣe atunṣe si oju-iwe ile...',
|
dataClearedDescription: 'Gbogbo data agbegbe ti yọ kuro. N ṣe atunṣe si oju-iwe ile...',
|
||||||
failedToClearData: 'O kuna lati nu data',
|
failedToClearData: 'O kuna lati nu data',
|
||||||
|
persistData: 'Fi Data Pamọ',
|
||||||
|
persistDataDescription: 'Beere ibi ipamọ ti o wa nigbagbogbo lati yago fun isonu data nigbati ibi ipamọ aṣawakiri ba kere. Eyi ṣe iranlọwọ lati daabobo awọn iṣẹ akanṣe ati awọn eto rẹ.',
|
||||||
|
persistentStorageGranted: 'Ibi ipamọ ti o wa nigbagbogbo ti funni',
|
||||||
|
persistentStorageGrantedDescription: 'Aṣawakiri rẹ yoo daabobo data rẹ lati imukuro adaṣe.',
|
||||||
|
persistentStorageAlreadyGranted: 'Ibi ipamọ ti o wa nigbagbogbo ti funni tẹlẹ',
|
||||||
|
persistentStorageAlreadyGrantedDescription: 'Data rẹ ti wa ni aabo lati imukuro adaṣe.',
|
||||||
|
persistentStorageDenied: 'Ibeere ibi ipamọ ti o wa nigbagbogbo ti kọ',
|
||||||
|
persistentStorageDeniedDescription: 'Aṣawakiri rẹ ti kọ ibeere naa. Data le tun jẹ imukuro adaṣe nigbati ibi ipamọ ba kere.',
|
||||||
|
persistentStorageNotSupported: 'Ibi ipamọ ti o wa nigbagbogbo ko ni atilẹyin',
|
||||||
|
persistentStorageNotSupportedDescription: 'Aṣawakiri rẹ ko ni atilẹyin awọn ibeere ibi ipamọ ti o wa nigbagbogbo.',
|
||||||
|
failedToRequestPersistentStorage: 'O kuna lati beere ibi ipamọ ti o wa nigbagbogbo',
|
||||||
|
|
||||||
// About Settings
|
// About Settings
|
||||||
aboutShakespeare: 'Nipa Shakespeare',
|
aboutShakespeare: 'Nipa Shakespeare',
|
||||||
@@ -1737,6 +1792,17 @@ const resources = {
|
|||||||
dataClearedSuccessfully: 'Ehichapụrụ data nke ọma',
|
dataClearedSuccessfully: 'Ehichapụrụ data nke ọma',
|
||||||
dataClearedDescription: 'Ewepụrụ data mpaghara niile. Na-atụgharị gaa na ibe ụlọ...',
|
dataClearedDescription: 'Ewepụrụ data mpaghara niile. Na-atụgharị gaa na ibe ụlọ...',
|
||||||
failedToClearData: 'O dara ihichapụ data',
|
failedToClearData: 'O dara ihichapụ data',
|
||||||
|
persistData: 'Chekwaa Data Ogologo Oge',
|
||||||
|
persistDataDescription: 'Rịọ nchekwa na-adịgide adịgide iji gbochie mfu data mgbe nchekwa browser dị ala. Nke a na-enyere aka ichebe ọrụ gị na ntọala.',
|
||||||
|
persistentStorageGranted: 'Enyere nchekwa na-adịgide adịgide',
|
||||||
|
persistentStorageGrantedDescription: 'Browser gị ga-echebe data gị ugbu a site na nhicha akpaaka.',
|
||||||
|
persistentStorageAlreadyGranted: 'Enyerela nchekwa na-adịgide adịgide',
|
||||||
|
persistentStorageAlreadyGrantedDescription: 'Echebeela data gị site na nhicha akpaaka.',
|
||||||
|
persistentStorageDenied: 'Ajụrụ arịrịọ nchekwa na-adịgide adịgide',
|
||||||
|
persistentStorageDeniedDescription: 'Browser gị jụrụ arịrịọ ahụ. Enwere ike ihichapụ data akpaaka mgbe nchekwa dị ala.',
|
||||||
|
persistentStorageNotSupported: 'Akwadoghị nchekwa na-adịgide adịgide',
|
||||||
|
persistentStorageNotSupportedDescription: 'Browser gị akwadoghị arịrịọ nchekwa na-adịgide adịgide.',
|
||||||
|
failedToRequestPersistentStorage: 'O dara ịrịọ nchekwa na-adịgide adịgide',
|
||||||
|
|
||||||
// About Settings
|
// About Settings
|
||||||
aboutShakespeare: 'Gbasara Shakespeare',
|
aboutShakespeare: 'Gbasara Shakespeare',
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
/**
|
||||||
|
* Utility functions for managing persistent storage in the browser
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if persistent storage is supported by the browser
|
||||||
|
*/
|
||||||
|
export function isPersistentStorageSupported(): boolean {
|
||||||
|
return 'storage' in navigator && 'persist' in navigator.storage;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if persistent storage is already granted
|
||||||
|
*/
|
||||||
|
export async function isPersistentStorageGranted(): Promise<boolean> {
|
||||||
|
if (!isPersistentStorageSupported()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
return await navigator.storage.persisted();
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('Failed to check persistent storage status:', error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Requests persistent storage from the browser
|
||||||
|
* Returns true if granted, false if denied or not supported
|
||||||
|
*/
|
||||||
|
export async function requestPersistentStorage(): Promise<boolean> {
|
||||||
|
if (!isPersistentStorageSupported()) {
|
||||||
|
console.warn('Persistent storage is not supported in this browser');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Check if already granted
|
||||||
|
const alreadyGranted = await isPersistentStorageGranted();
|
||||||
|
if (alreadyGranted) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request persistent storage
|
||||||
|
const granted = await navigator.storage.persist();
|
||||||
|
return granted;
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('Failed to request persistent storage:', error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Automatically requests persistent storage if not already granted
|
||||||
|
* This is intended to be called silently after project creation/cloning
|
||||||
|
* Returns true if persistent storage is available (either already granted or newly granted)
|
||||||
|
*/
|
||||||
|
export async function ensurePersistentStorage(): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
// Check if already granted
|
||||||
|
const alreadyGranted = await isPersistentStorageGranted();
|
||||||
|
if (alreadyGranted) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only request if supported
|
||||||
|
if (!isPersistentStorageSupported()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Silently request persistent storage
|
||||||
|
const granted = await requestPersistentStorage();
|
||||||
|
|
||||||
|
if (granted) {
|
||||||
|
console.log('Persistent storage granted automatically');
|
||||||
|
} else {
|
||||||
|
console.log('Persistent storage request denied or failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
return granted;
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('Failed to ensure persistent storage:', error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets current storage usage information
|
||||||
|
*/
|
||||||
|
export async function getStorageInfo(): Promise<{
|
||||||
|
quota: number;
|
||||||
|
usage: number;
|
||||||
|
usageDetails?: Record<string, number>;
|
||||||
|
} | null> {
|
||||||
|
if (!('storage' in navigator)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const estimate = await navigator.storage.estimate();
|
||||||
|
return {
|
||||||
|
quota: estimate.quota || 0,
|
||||||
|
usage: estimate.usage || 0,
|
||||||
|
usageDetails: (estimate as StorageEstimate & { usageDetails?: Record<string, number> }).usageDetails,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('Failed to get storage information:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
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: [] },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
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))
|
||||||
|
));
|
||||||
|
}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||||
|
import {
|
||||||
|
ReadConsoleMessagesTool,
|
||||||
|
addConsoleMessage,
|
||||||
|
clearConsoleMessages,
|
||||||
|
ProjectPreviewConsoleError,
|
||||||
|
addErrorListener,
|
||||||
|
removeErrorListener
|
||||||
|
} from './ReadConsoleMessagesTool';
|
||||||
|
|
||||||
|
describe('ReadConsoleMessagesTool', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
clearConsoleMessages();
|
||||||
|
// Add test messages
|
||||||
|
addConsoleMessage('log', 'App started');
|
||||||
|
addConsoleMessage('warn', 'Deprecated API used');
|
||||||
|
addConsoleMessage('error', 'Network request failed');
|
||||||
|
addConsoleMessage('info', 'User logged in');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return all messages by default', async () => {
|
||||||
|
const tool = new ReadConsoleMessagesTool();
|
||||||
|
const result = await tool.execute({});
|
||||||
|
|
||||||
|
expect(result).toContain('Found 4 console messages');
|
||||||
|
expect(result).toContain('[LOG] App started');
|
||||||
|
expect(result).toContain('[WARN] Deprecated API used');
|
||||||
|
expect(result).toContain('[ERROR] Network request failed');
|
||||||
|
expect(result).toContain('[INFO] User logged in');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should filter messages by level', async () => {
|
||||||
|
const tool = new ReadConsoleMessagesTool();
|
||||||
|
const result = await tool.execute({ filter: 'error' });
|
||||||
|
|
||||||
|
expect(result).toContain('Found 1 console message (level: error)');
|
||||||
|
expect(result).toContain('[ERROR] Network request failed');
|
||||||
|
expect(result).not.toContain('[LOG] App started');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should limit number of messages', async () => {
|
||||||
|
const tool = new ReadConsoleMessagesTool();
|
||||||
|
const result = await tool.execute({ limit: 2 });
|
||||||
|
|
||||||
|
expect(result).toContain('Found 2 console messages');
|
||||||
|
// Should get the last 2 messages
|
||||||
|
expect(result).toContain('[ERROR] Network request failed');
|
||||||
|
expect(result).toContain('[INFO] User logged in');
|
||||||
|
expect(result).not.toContain('[LOG] App started');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle no messages found', async () => {
|
||||||
|
clearConsoleMessages();
|
||||||
|
const tool = new ReadConsoleMessagesTool();
|
||||||
|
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 result = await tool.execute({ filter: 'debug' });
|
||||||
|
|
||||||
|
expect(result).toBe('No console messages found for level: debug.');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
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> {
|
||||||
|
async execute(params: ReadConsoleMessagesParams): Promise<string> {
|
||||||
|
const { filter = 'all', limit } = params;
|
||||||
|
|
||||||
|
// Filter and limit messages in one chain
|
||||||
|
const filteredMessages = getConsoleMessages()
|
||||||
|
.filter(msg => filter === 'all' || msg.level === filter)
|
||||||
|
.slice(limit && limit > 0 ? -limit : 0);
|
||||||
|
|
||||||
|
if (filteredMessages.length === 0) {
|
||||||
|
return `No console messages found${filter !== 'all' ? ` for level: ${filter}` : ''}.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const formattedMessages = filteredMessages
|
||||||
|
.map(msg => `[${msg.level.toUpperCase()}] ${msg.message}`)
|
||||||
|
.join('\n');
|
||||||
|
|
||||||
|
const plural = filteredMessages.length !== 1 ? 's' : '';
|
||||||
|
const levelInfo = filter !== 'all' ? ` (level: ${filter})` : '';
|
||||||
|
|
||||||
|
return `Found ${filteredMessages.length} console message${plural}${levelInfo}:\n\n${formattedMessages}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
description = 'Read console messages from the project preview. Can filter by level and limit results.';
|
||||||
|
}
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
+28
-30
@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next';
|
|||||||
import { Info, ExternalLink, Loader2, AlertTriangle, ArrowLeft } from 'lucide-react';
|
import { Info, ExternalLink, Loader2, AlertTriangle, ArrowLeft } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||||
|
|
||||||
@@ -22,7 +22,7 @@ export function AboutSettings() {
|
|||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
const response = await fetch('/LICENSE.txt');
|
const response = await fetch('/LICENSE.html');
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(`Failed to fetch license: ${response.status} ${response.statusText}`);
|
throw new Error(`Failed to fetch license: ${response.status} ${response.statusText}`);
|
||||||
@@ -109,35 +109,33 @@ export function AboutSettings() {
|
|||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
{/* License */}
|
{/* License */}
|
||||||
<Card>
|
<Accordion type="single" collapsible className="w-full">
|
||||||
<CardHeader>
|
<AccordionItem value="license-text" className="border rounded-lg">
|
||||||
<CardTitle className="flex items-center gap-2">
|
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||||
<Info className="h-5 w-5" />
|
<div className="flex items-center gap-2">
|
||||||
{t('license')}
|
<Info className="h-5 w-5" />
|
||||||
</CardTitle>
|
{t('license')}
|
||||||
</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>
|
</div>
|
||||||
) : error ? (
|
</AccordionTrigger>
|
||||||
<Alert variant="destructive">
|
<AccordionContent className="px-4 pb-4">
|
||||||
<AlertTriangle className="h-4 w-4" />
|
{isLoading ? (
|
||||||
<AlertDescription>
|
<div className="flex items-center gap-2 text-muted-foreground py-4">
|
||||||
{t('failedToLoadLicense')}: {error}
|
<Loader2 className="h-4 w-4 animate-spin" />
|
||||||
</AlertDescription>
|
<span className="text-sm">{t('loadingLicense')}</span>
|
||||||
</Alert>
|
</div>
|
||||||
) : license ? (
|
) : error ? (
|
||||||
<ScrollArea className="h-96 w-full rounded-md border p-4">
|
<Alert variant="destructive">
|
||||||
<pre className="text-xs font-mono whitespace-pre-wrap break-words">
|
<AlertTriangle className="h-4 w-4" />
|
||||||
{license}
|
<AlertDescription>
|
||||||
</pre>
|
{t('failedToLoadLicense')}: {error}
|
||||||
</ScrollArea>
|
</AlertDescription>
|
||||||
) : null}
|
</Alert>
|
||||||
</CardContent>
|
) : license ? (
|
||||||
</Card>
|
<div className="prose text-sm" dangerouslySetInnerHTML={{ __html: license }} />
|
||||||
|
) : null}
|
||||||
|
</AccordionContent>
|
||||||
|
</AccordionItem>
|
||||||
|
</Accordion>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -17,6 +17,9 @@ describe('DataSettings', () => {
|
|||||||
// Check for description
|
// Check for description
|
||||||
expect(screen.getByText('Export files and manage local data.')).toBeInTheDocument();
|
expect(screen.getByText('Export files and manage local data.')).toBeInTheDocument();
|
||||||
|
|
||||||
|
// Check for Persist Data section
|
||||||
|
expect(screen.getByText('Persist Data')).toBeInTheDocument();
|
||||||
|
|
||||||
// Check for Export Files section
|
// Check for Export Files section
|
||||||
expect(screen.getByText('Export Files')).toBeInTheDocument();
|
expect(screen.getByText('Export Files')).toBeInTheDocument();
|
||||||
expect(screen.getByText('Export All Files')).toBeInTheDocument();
|
expect(screen.getByText('Export All Files')).toBeInTheDocument();
|
||||||
@@ -26,13 +29,17 @@ describe('DataSettings', () => {
|
|||||||
expect(screen.getByRole('button', { name: /clear all data/i })).toBeInTheDocument();
|
expect(screen.getByRole('button', { name: /clear all data/i })).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows export and clear buttons', () => {
|
it('shows persist data toggle, export and clear buttons', () => {
|
||||||
render(
|
render(
|
||||||
<TestApp>
|
<TestApp>
|
||||||
<DataSettings />
|
<DataSettings />
|
||||||
</TestApp>
|
</TestApp>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Persist storage toggle should be visible
|
||||||
|
const persistToggle = screen.getByRole('switch');
|
||||||
|
expect(persistToggle).toBeInTheDocument();
|
||||||
|
|
||||||
// Export button should be visible
|
// Export button should be visible
|
||||||
const exportButton = screen.getByRole('button', { name: /export all files/i });
|
const exportButton = screen.getByRole('button', { name: /export all files/i });
|
||||||
expect(exportButton).toBeInTheDocument();
|
expect(exportButton).toBeInTheDocument();
|
||||||
|
|||||||
+103
-12
@@ -1,14 +1,21 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft } from 'lucide-react';
|
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Shield } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
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';
|
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||||
import { Progress } from '@/components/ui/progress';
|
import { Progress } from '@/components/ui/progress';
|
||||||
|
import { Switch } from '@/components/ui/switch';
|
||||||
import { useToast } from '@/hooks/useToast';
|
import { useToast } from '@/hooks/useToast';
|
||||||
import { useFS } from '@/hooks/useFS';
|
import { useFS } from '@/hooks/useFS';
|
||||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||||
|
import {
|
||||||
|
isPersistentStorageSupported,
|
||||||
|
isPersistentStorageGranted,
|
||||||
|
requestPersistentStorage,
|
||||||
|
getStorageInfo
|
||||||
|
} from '@/lib/persistentStorage';
|
||||||
import JSZip from 'jszip';
|
import JSZip from 'jszip';
|
||||||
|
|
||||||
interface StorageUsageDetails {
|
interface StorageUsageDetails {
|
||||||
@@ -28,8 +35,10 @@ export function DataSettings() {
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [isExporting, setIsExporting] = useState(false);
|
const [isExporting, setIsExporting] = useState(false);
|
||||||
const [isClearing, setIsClearing] = useState(false);
|
const [isClearing, setIsClearing] = useState(false);
|
||||||
|
const [isRequestingPersistent, setIsRequestingPersistent] = useState(false);
|
||||||
const [storageInfo, setStorageInfo] = useState<StorageInfo | null>(null);
|
const [storageInfo, setStorageInfo] = useState<StorageInfo | null>(null);
|
||||||
const [storageError, setStorageError] = useState<string | null>(null);
|
const [storageError, setStorageError] = useState<string | null>(null);
|
||||||
|
const [isPersistent, setIsPersistent] = useState<boolean | null>(null);
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
const { fs } = useFS();
|
const { fs } = useFS();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
@@ -44,27 +53,29 @@ export function DataSettings() {
|
|||||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||||
};
|
};
|
||||||
|
|
||||||
// Load storage information
|
// Load storage information and persistent status
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const loadStorageInfo = async () => {
|
const loadStorageInfo = async () => {
|
||||||
try {
|
try {
|
||||||
// Check if StorageManager API is available
|
// Check if StorageManager API is available
|
||||||
if (!('storage' in navigator)) {
|
if (!isPersistentStorageSupported()) {
|
||||||
setStorageError('StorageManager API is not available in this browser');
|
setStorageError('StorageManager API is not available in this browser');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get storage estimate
|
// Get storage estimate
|
||||||
const estimate = await navigator.storage.estimate();
|
const info = await getStorageInfo();
|
||||||
|
if (info) {
|
||||||
|
setStorageInfo({
|
||||||
|
quota: info.quota,
|
||||||
|
usage: info.usage,
|
||||||
|
usageDetails: info.usageDetails as StorageUsageDetails,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Extract usage details safely
|
// Check if storage is persistent
|
||||||
const usageDetails: StorageUsageDetails | undefined = (estimate as StorageEstimate & { usageDetails?: StorageUsageDetails }).usageDetails;
|
const persistent = await isPersistentStorageGranted();
|
||||||
|
setIsPersistent(persistent);
|
||||||
setStorageInfo({
|
|
||||||
quota: estimate.quota || 0,
|
|
||||||
usage: estimate.usage || 0,
|
|
||||||
usageDetails,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to get storage information:', error);
|
console.error('Failed to get storage information:', error);
|
||||||
setStorageError(error instanceof Error ? error.message : 'Failed to get storage information');
|
setStorageError(error instanceof Error ? error.message : 'Failed to get storage information');
|
||||||
@@ -149,6 +160,63 @@ export function DataSettings() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handlePersistentStorageToggle = async (checked: boolean) => {
|
||||||
|
// If trying to turn off, we can't actually do that - just ignore
|
||||||
|
if (!checked) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsRequestingPersistent(true);
|
||||||
|
try {
|
||||||
|
// Check if persist method is available
|
||||||
|
if (!isPersistentStorageSupported()) {
|
||||||
|
toast({
|
||||||
|
title: t('persistentStorageNotSupported'),
|
||||||
|
description: t('persistentStorageNotSupportedDescription'),
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if already persistent
|
||||||
|
const alreadyPersistent = await isPersistentStorageGranted();
|
||||||
|
if (alreadyPersistent) {
|
||||||
|
setIsPersistent(true);
|
||||||
|
toast({
|
||||||
|
title: t('persistentStorageAlreadyGranted'),
|
||||||
|
description: t('persistentStorageAlreadyGrantedDescription'),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request persistent storage
|
||||||
|
const granted = await requestPersistentStorage();
|
||||||
|
|
||||||
|
if (granted) {
|
||||||
|
setIsPersistent(true);
|
||||||
|
toast({
|
||||||
|
title: t('persistentStorageGranted'),
|
||||||
|
description: t('persistentStorageGrantedDescription'),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
toast({
|
||||||
|
title: t('persistentStorageDenied'),
|
||||||
|
description: t('persistentStorageDeniedDescription'),
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to request persistent storage:', error);
|
||||||
|
toast({
|
||||||
|
title: t('failedToRequestPersistentStorage'),
|
||||||
|
description: error instanceof Error ? error.message : t('error'),
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setIsRequestingPersistent(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const handleClearAllData = async () => {
|
const handleClearAllData = async () => {
|
||||||
setIsClearing(true);
|
setIsClearing(true);
|
||||||
try {
|
try {
|
||||||
@@ -268,6 +336,29 @@ export function DataSettings() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Persist Data */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center gap-2">
|
||||||
|
<Shield className="h-5 w-5" />
|
||||||
|
{t('persistData')}
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
{t('persistDataDescription')}
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="flex items-center justify-start">
|
||||||
|
<Switch
|
||||||
|
id="persistent-storage"
|
||||||
|
checked={isPersistent === true}
|
||||||
|
onCheckedChange={handlePersistentStorageToggle}
|
||||||
|
disabled={isRequestingPersistent || isPersistent === null}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
{/* Export Files */}
|
{/* Export Files */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
|
|||||||
@@ -22,6 +22,10 @@ export function EmailSettings() {
|
|||||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||||
const [isSubmitted, setIsSubmitted] = 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
|
// Check localStorage on component mount
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const hasSubscribed = localStorage.getItem('shakespeare-email-subscribed');
|
const hasSubscribed = localStorage.getItem('shakespeare-email-subscribed');
|
||||||
@@ -56,21 +60,10 @@ export function EmailSettings() {
|
|||||||
setIsSubmitting(true);
|
setIsSubmitting(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Prepare form data
|
// Submit to Mailchimp
|
||||||
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');
|
const form = document.createElement('form');
|
||||||
form.method = 'POST';
|
form.method = 'POST';
|
||||||
form.action = 'https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&id=f7271442a0&f_id=00ffa3e4f0';
|
form.action = url.href;
|
||||||
form.target = '_blank'; // Open in new tab
|
form.target = '_blank'; // Open in new tab
|
||||||
form.style.display = 'none';
|
form.style.display = 'none';
|
||||||
|
|
||||||
@@ -85,7 +78,7 @@ export function EmailSettings() {
|
|||||||
const tagInput = document.createElement('input');
|
const tagInput = document.createElement('input');
|
||||||
tagInput.type = 'hidden';
|
tagInput.type = 'hidden';
|
||||||
tagInput.name = 'tags';
|
tagInput.name = 'tags';
|
||||||
tagInput.value = '8982396';
|
tagInput.value = tag;
|
||||||
form.appendChild(tagInput);
|
form.appendChild(tagInput);
|
||||||
|
|
||||||
// Add npub if available
|
// Add npub if available
|
||||||
@@ -101,7 +94,7 @@ export function EmailSettings() {
|
|||||||
// Add honeypot field
|
// Add honeypot field
|
||||||
const honeypotInput = document.createElement('input');
|
const honeypotInput = document.createElement('input');
|
||||||
honeypotInput.type = 'text';
|
honeypotInput.type = 'text';
|
||||||
honeypotInput.name = 'b_f1f718a93795f42a604d558d8_f7271442a0';
|
honeypotInput.name = honeypot;
|
||||||
honeypotInput.tabIndex = -1;
|
honeypotInput.tabIndex = -1;
|
||||||
honeypotInput.style.position = 'absolute';
|
honeypotInput.style.position = 'absolute';
|
||||||
honeypotInput.style.left = '-5000px';
|
honeypotInput.style.left = '-5000px';
|
||||||
@@ -275,8 +268,6 @@ export function EmailSettings() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
<Button
|
<Button
|
||||||
type="submit"
|
type="submit"
|
||||||
|
|||||||
+52
-41
@@ -7,20 +7,18 @@ import { useFS } from '@/hooks/useFS';
|
|||||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||||
import { useAISettings } from '@/hooks/useAISettings';
|
import { useAISettings } from '@/hooks/useAISettings';
|
||||||
import { useToast } from '@/hooks/useToast';
|
|
||||||
import { AppLayout } from '@/components/AppLayout';
|
import { AppLayout } from '@/components/AppLayout';
|
||||||
import { OnboardingDialog } from '@/components/OnboardingDialog';
|
import { OnboardingDialog } from '@/components/OnboardingDialog';
|
||||||
|
import { Act1Dialog } from '@/components/Act1Dialog';
|
||||||
|
import { Quilly } from '@/components/Quilly';
|
||||||
import { DotAI } from '@/lib/DotAI';
|
import { DotAI } from '@/lib/DotAI';
|
||||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
|
||||||
import type { AIMessage } from '@/lib/SessionManager';
|
import type { AIMessage } from '@/lib/SessionManager';
|
||||||
import { saveFileToTmp } from '@/lib/fileUtils';
|
import { saveFileToTmp } from '@/lib/fileUtils';
|
||||||
import type OpenAI from 'openai';
|
import type OpenAI from 'openai';
|
||||||
|
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Textarea } from '@/components/ui/textarea';
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
import { ModelSelector } from '@/components/ModelSelector';
|
import { ModelSelector } from '@/components/ModelSelector';
|
||||||
import { FileAttachment } from '@/components/ui/file-attachment';
|
import { FileAttachment } from '@/components/ui/file-attachment';
|
||||||
import { ToastAction } from '@/components/ui/toast';
|
|
||||||
import { Plus } from 'lucide-react';
|
import { Plus } from 'lucide-react';
|
||||||
import { useSeoMeta } from '@unhead/react';
|
import { useSeoMeta } from '@unhead/react';
|
||||||
|
|
||||||
@@ -30,12 +28,12 @@ export default function Index() {
|
|||||||
const [isCreating, setIsCreating] = useState(false);
|
const [isCreating, setIsCreating] = useState(false);
|
||||||
const [storedPrompt, setStoredPrompt] = useLocalStorage('shakespeare-draft-prompt', '');
|
const [storedPrompt, setStoredPrompt] = useLocalStorage('shakespeare-draft-prompt', '');
|
||||||
const [showOnboarding, setShowOnboarding] = useState(false);
|
const [showOnboarding, setShowOnboarding] = useState(false);
|
||||||
|
const [showAct1Dialog, setShowAct1Dialog] = useState(false);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const projectsManager = useProjectsManager();
|
const projectsManager = useProjectsManager();
|
||||||
const { fs } = useFS();
|
const { fs } = useFS();
|
||||||
const { generateProjectId, isLoading: isGeneratingId } = useAIProjectId();
|
const { generateProjectId, isLoading: isGeneratingId } = useAIProjectId();
|
||||||
const { settings, addRecentlyUsedModel } = useAISettings();
|
const { settings, addRecentlyUsedModel } = useAISettings();
|
||||||
const { toast } = useToast();
|
|
||||||
const [providerModel, setProviderModel] = useState(() => {
|
const [providerModel, setProviderModel] = useState(() => {
|
||||||
// Initialize with first recently used model if available, otherwise empty
|
// Initialize with first recently used model if available, otherwise empty
|
||||||
return settings.recentlyUsedModels?.[0] || '';
|
return settings.recentlyUsedModels?.[0] || '';
|
||||||
@@ -43,45 +41,11 @@ export default function Index() {
|
|||||||
const isMobile = useIsMobile();
|
const isMobile = useIsMobile();
|
||||||
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
|
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
|
||||||
const [isDragOver, setIsDragOver] = useState(false);
|
const [isDragOver, setIsDragOver] = useState(false);
|
||||||
|
const [quillyError, setQuillyError] = useState<Error | null>(null);
|
||||||
|
|
||||||
// Check if any providers are configured
|
// Check if any providers are configured
|
||||||
const hasProvidersConfigured = settings.providers.length > 0;
|
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(() => {
|
useEffect(() => {
|
||||||
if (!providerModel && settings.recentlyUsedModels?.length) {
|
if (!providerModel && settings.recentlyUsedModels?.length) {
|
||||||
setProviderModel(settings.recentlyUsedModels[0]);
|
setProviderModel(settings.recentlyUsedModels[0]);
|
||||||
@@ -100,6 +64,13 @@ export default function Index() {
|
|||||||
}
|
}
|
||||||
}, [storedPrompt]);
|
}, [storedPrompt]);
|
||||||
|
|
||||||
|
// Check for Act 1 users and show welcome dialog
|
||||||
|
useEffect(() => {
|
||||||
|
if (localStorage.getItem('selectedNSPAddr')) {
|
||||||
|
setShowAct1Dialog(true);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
// Sync prompt with local storage
|
// Sync prompt with local storage
|
||||||
const handlePromptChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
const handlePromptChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||||
const newPrompt = e.target.value;
|
const newPrompt = e.target.value;
|
||||||
@@ -188,6 +159,27 @@ 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 () => {
|
const handleCreateProject = async () => {
|
||||||
if (!prompt.trim() || !providerModel.trim()) return;
|
if (!prompt.trim() || !providerModel.trim()) return;
|
||||||
|
|
||||||
@@ -262,7 +254,7 @@ export default function Index() {
|
|||||||
navigate(`/project/${project.id}?${searchParams.toString()}`);
|
navigate(`/project/${project.id}?${searchParams.toString()}`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create project:', error);
|
console.error('Failed to create project:', error);
|
||||||
checkForKeyFailure(error);
|
setQuillyError(error instanceof Error ? error : new Error("An unexpected error occurred"));
|
||||||
} finally {
|
} finally {
|
||||||
setIsCreating(false);
|
setIsCreating(false);
|
||||||
}
|
}
|
||||||
@@ -285,6 +277,19 @@ export default function Index() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mb-8 md:mb-12">
|
<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 */}
|
{/* Chat Input Container - matching the ChatPane style */}
|
||||||
<div
|
<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' : ''
|
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' : ''
|
||||||
@@ -378,6 +383,12 @@ export default function Index() {
|
|||||||
open={showOnboarding}
|
open={showOnboarding}
|
||||||
onOpenChange={setShowOnboarding}
|
onOpenChange={setShowOnboarding}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* Act 1 Welcome Dialog */}
|
||||||
|
<Act1Dialog
|
||||||
|
open={showAct1Dialog}
|
||||||
|
onOpenChange={setShowAct1Dialog}
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -16,9 +16,9 @@ import { ActionsMenu } from '@/components/ActionsMenu';
|
|||||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||||
import { StarButton } from '@/components/StarButton';
|
import { StarButton } from '@/components/StarButton';
|
||||||
|
|
||||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||||
import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable';
|
import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable';
|
||||||
|
import { clearConsoleMessages } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||||
|
|
||||||
export function ProjectView() {
|
export function ProjectView() {
|
||||||
const { projectId } = useParams<{ projectId: string }>();
|
const { projectId } = useParams<{ projectId: string }>();
|
||||||
@@ -29,6 +29,7 @@ export function ProjectView() {
|
|||||||
const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat');
|
const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat');
|
||||||
const [isAILoading, setIsAILoading] = useState(false);
|
const [isAILoading, setIsAILoading] = useState(false);
|
||||||
const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false);
|
const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false);
|
||||||
|
|
||||||
const projectsManager = useProjectsManager();
|
const projectsManager = useProjectsManager();
|
||||||
const chatPaneRef = useRef<ChatPaneRef>(null);
|
const chatPaneRef = useRef<ChatPaneRef>(null);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
@@ -45,6 +46,8 @@ export function ProjectView() {
|
|||||||
try {
|
try {
|
||||||
const projectData = await projectsManager.getProject(projectId);
|
const projectData = await projectsManager.getProject(projectId);
|
||||||
setProject(projectData);
|
setProject(projectData);
|
||||||
|
// Clear console messages when switching projects
|
||||||
|
clearConsoleMessages();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to load project:', error);
|
console.error('Failed to load project:', error);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -118,7 +121,7 @@ export function ProjectView() {
|
|||||||
|
|
||||||
if (isMobile) {
|
if (isMobile) {
|
||||||
return (
|
return (
|
||||||
<div className="h-dvh flex flex-col bg-background">
|
<div className="h-dvh flex flex-col bg-background safe-area-inset-top">
|
||||||
<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">
|
<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">
|
<div className="flex items-center space-x-2 overflow-hidden">
|
||||||
<Button
|
<Button
|
||||||
@@ -236,13 +239,13 @@ export function ProjectView() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="border-t bg-gradient-to-r from-primary/5 via-background to-accent/5 backdrop-blur">
|
<div className="border-t bg-gradient-to-r from-primary/5 via-background to-accent/5 backdrop-blur safe-area-inset-bottom">
|
||||||
<div className="flex">
|
<div className="flex">
|
||||||
<Button
|
<Button
|
||||||
variant={mobileView === 'chat' ? 'default' : 'ghost'}
|
variant="ghost"
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => setMobileView('chat')}
|
onClick={() => setMobileView('chat')}
|
||||||
className="flex-1 rounded-none"
|
className={`flex-1 rounded-none mobile-nav-button ${mobileView === 'chat' ? 'mobile-nav-button-active' : ''}`}
|
||||||
disabled={!project}
|
disabled={!project}
|
||||||
>
|
>
|
||||||
<MessageSquare className="h-4 w-4 mr-1" />
|
<MessageSquare className="h-4 w-4 mr-1" />
|
||||||
@@ -250,10 +253,10 @@ export function ProjectView() {
|
|||||||
</Button>
|
</Button>
|
||||||
{isPreviewable && (
|
{isPreviewable && (
|
||||||
<Button
|
<Button
|
||||||
variant={mobileView === 'preview' ? 'default' : 'ghost'}
|
variant="ghost"
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => setMobileView('preview')}
|
onClick={() => setMobileView('preview')}
|
||||||
className="flex-1 rounded-none"
|
className={`flex-1 rounded-none mobile-nav-button ${mobileView === 'preview' ? 'mobile-nav-button-active' : ''}`}
|
||||||
disabled={!project}
|
disabled={!project}
|
||||||
>
|
>
|
||||||
<Eye className="h-4 w-4 mr-1" />
|
<Eye className="h-4 w-4 mr-1" />
|
||||||
@@ -261,10 +264,10 @@ export function ProjectView() {
|
|||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<Button
|
<Button
|
||||||
variant={mobileView === 'code' ? 'default' : 'ghost'}
|
variant="ghost"
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => setMobileView('code')}
|
onClick={() => setMobileView('code')}
|
||||||
className="flex-1 rounded-none"
|
className={`flex-1 rounded-none mobile-nav-button ${mobileView === 'code' ? 'mobile-nav-button-active' : ''}`}
|
||||||
disabled={!project}
|
disabled={!project}
|
||||||
>
|
>
|
||||||
<Code className="h-4 w-4 mr-1" />
|
<Code className="h-4 w-4 mr-1" />
|
||||||
|
|||||||
Reference in new issue
Block a user