Compare commits

...
Author SHA1 Message Date
Chad Curtis c6617beb6d Gracefully handle total response failure from site - no response at all. 2025-09-20 18:36:52 +00:00
Chad Curtis 718b2f369b Remove code example from a file path already linked. 2025-09-20 18:24:18 +00:00
Chad Curtis a823f81b50 Function definition consistency + slight deduplication 2025-09-20 18:21:55 +00:00
Chad Curtis 4cd8683e73 Re-add purged, but informative documentation/comment items. 2025-09-20 18:09:03 +00:00
Chad Curtis 53ac813eb5 Further simplify main.js, update documentation. 2025-09-20 17:59:04 +00:00
Chad Curtis f4f455606f Simplify console overrides list within iframe client as well. 2025-09-20 17:15:17 +00:00
Chad Curtis 1a424c0762 Refactor and simplify console methods. 2025-09-20 17:10:47 +00:00
Chad Curtis f299c73c4d final consolidation 2025-09-20 03:53:46 +00:00
Chad Curtis 1d05aa10eb further cleanup 2025-09-20 03:38:19 +00:00
Chad Curtis ca2426a800 Further cleanup + make errors copiable 2025-09-20 03:37:20 +00:00
Chad Curtis fbea142bbb Address review items 2025-09-20 02:16:40 +00:00
Chad Curtis 0027752654 consolidation and visual cleanup 2025-09-20 02:16:40 +00:00
Chad Curtis d64fa0e0ec Deduplicate console interception code
- Extract shared console utilities to console-utils.js
- Remove duplicated console methods array
- Consolidate original console storage logic
- Extract console override and error handler patterns
- Reduced code duplication by ~90 lines
2025-09-20 02:16:40 +00:00
Chad Curtis 696cbca55a remove debug file 2025-09-20 02:16:40 +00:00
Chad Curtis 92f3c06f51 cleanup 2025-09-20 02:16:40 +00:00
Chad Curtis 3898681d97 CF worker setup + iframe domain to env 2025-09-20 02:16:40 +00:00
Chad Curtis ba251d57eb baseline 2025-09-20 02:16:40 +00:00
Alex Gleason efd7c3901b Display loading state for reasoning 2025-09-19 20:36:40 -05:00
Alex Gleason e6c9c213b5 Support reasoning_content 2025-09-19 20:23:55 -05:00
Alex Gleason bd5373f57b Simplify Preferences page 2025-09-19 19:54:23 -05:00
Alex Gleason f67d6dbfc5 Add About Shakespeare page 2025-09-19 19:49:29 -05:00
Alex Gleason efbec14d24 Add AGPL license 2025-09-19 19:31:17 -05:00
Alex Gleason 1c8095d40e Enforce max height on transactions list 2025-09-19 19:26:46 -05:00
Alex Gleason 7807f875f2 Add Back button to Lightning view 2025-09-19 19:10:26 -05:00
Alex Gleason fdd3fd2b52 Add refresh button to transactions 2025-09-19 18:47:32 -05:00
Alex Gleason 77863f97be Copy tooltip 2025-09-19 18:32:38 -05:00
Alex Gleason 1d88ca84f2 Improve Lightning payment UX 2025-09-19 18:26:24 -05:00
Alex Gleason 62cd515a9e Improve credits dialog 2025-09-19 18:09:22 -05:00
Alex Gleason a1e18ec335 Render dialog outside of accordion 2025-09-19 17:59:34 -05:00
Alex Gleason dca1573293 Add initial AI credits dialog 2025-09-19 17:49:15 -05:00
Alex Gleason 04d28cbe01 Delete CreditsBadge test 2025-09-19 17:19:12 -05:00
Alex Gleason 234418babd Display provider credits in the UI 2025-09-19 17:12:57 -05:00
Alex Gleason e570ee0236 Add special treatment for Nostr providers in the UI 2025-09-19 16:31:59 -05:00
Alex Gleason 45745dc368 Add Shakespeare AI provider 2025-09-19 16:22:28 -05:00
Alex Gleason 15ec573ed1 Merge branch 'fix-spacing-ui' into 'main'
Fix spacing ui

See merge request soapbox-pub/act2!18
2025-09-19 21:16:18 +00:00
Alex Gleason 23075932b8 Fix title overflow issue 2025-09-19 16:08:51 -05:00
Alex Gleason 94755d4cc0 Improve useProjectId logic 2025-09-19 16:06:10 -05:00
P. Reis 2c2d76137b make password input use all available space 2025-09-19 17:44:32 -03:00
P. Reis b8fd6421fa adjust 'Add' button size and position it in the correct location 2025-09-19 17:44:05 -03:00
Alex Gleason 8dfe186e8a Translate more pages 2025-09-19 15:19:23 -05:00
Alex Gleason 4ad3c7367d Default to browser language 2025-09-19 14:47:14 -05:00
Alex Gleason 350f3b3c5e Add Chinese translation 2025-09-19 14:24:10 -05:00
Alex Gleason bb830fbae5 Add translations info to AGENTS.md 2025-09-19 14:20:04 -05:00
Alex Gleason 03b712a917 Translate all the strings 2025-09-19 14:15:30 -05:00
Alex Gleason ced204bfde Add translations support 2025-09-19 13:40:11 -05:00
Alex Gleason dd970c2ca7 Darken settings hover state on light theme 2025-09-19 12:26:48 -05:00
Alex Gleason 1cccd8c254 Add loading skeleton to NostrSettings page 2025-09-19 12:22:10 -05:00
Alex Gleason 6f399af544 Merge branch 'dark-mode' into 'main'
Dark Mode

See merge request soapbox-pub/act2!17
2025-09-19 17:18:07 +00:00
Alex Gleason 7437118051 Remove ThemeToggle 2025-09-19 12:16:11 -05:00
Alex Gleason 656cce0159 Add Preferences page to settings 2025-09-19 12:15:15 -05:00
Alex Gleason 20778f5045 Add dark support to code blocks in AI messages 2025-09-19 12:03:38 -05:00
Alex Gleason 579dd93d6d Sidebar dark theme improvements 2025-09-19 11:44:07 -05:00
Alex Gleason af86b50141 Fix sidebar tests 2025-09-19 11:38:18 -05:00
lemonknowsall 395111ac07 added dark mode 2025-09-18 20:59:38 -07:00
Alex Gleason 9c358bb230 Simplify sidebar navigation 2025-09-18 21:39:49 -05:00
Alex Gleason 5cdb62ca1c Improve "Add Account" button in Nostr Settings UI 2025-09-18 17:55:34 -05:00
Alex Gleason 6204164408 Simplify Nostr Settings accounts 2025-09-18 17:46:11 -05:00
Alex Gleason 6c5ee84fe4 Click account to switch 2025-09-18 17:34:31 -05:00
Alex Gleason 1653e5d018 Add accounts to Nostr Settings 2025-09-18 17:32:42 -05:00
Alex Gleason edb0cd580f Remove relay picker from Anonymous 2025-09-18 17:28:06 -05:00
Alex Gleason 94f28d2ee8 Simplify Clone page 2025-09-18 17:17:23 -05:00
Alex Gleason 3064866e2b Add Nostr Settings page, move relay picker there 2025-09-18 17:07:10 -05:00
Alex Gleason 000c3d62ab Merge branch 'fix-tests' into 'main'
Revert "fix test CI"

See merge request soapbox-pub/act2!16
2025-09-18 21:56:55 +00:00
Alex Gleason 83af1d7d2d Merge branch 'main' of gitlab.com:soapbox-pub/act2 2025-09-18 16:56:07 -05:00
P. Reis 176b156151 fix tests 2025-09-18 18:55:20 -03:00
Alex Gleason 783e7c38ce Close the mobile sidebar when navigating to self page 2025-09-18 16:55:13 -05:00
Alex Gleason 16b36dab8e Add "x" button to sidebar on mobile 2025-09-18 16:48:21 -05:00
P. Reis ebaaf51c22 Revert "fix test CI"
This reverts commit aac0d5d320.
2025-09-18 18:37:47 -03:00
Alex Gleason 1947402d9a Merge branch 'add-eye-password' into 'main'
feat: add eye to toggle visibility of passwords

See merge request soapbox-pub/act2!15
2025-09-18 20:46:38 +00:00
Alex Gleason 61fcbc7003 Downgrade streamdown again 2025-09-18 15:44:13 -05:00
Alex Gleason 562d2c3085 Upgrade streamdown 2025-09-18 15:39:22 -05:00
Alex Gleason 7b4a5ee22e Remove unused streamdown dep 2025-09-18 15:35:01 -05:00
Alex Gleason 9ac157e802 Remove unused dep, fix esbuild plugins 2025-09-18 15:31:36 -05:00
P. Reis aac0d5d320 fix test CI 2025-09-18 17:28:51 -03:00
Alex Gleason 4b42f4cedb Improve resolution of imports in esmPlugin in some cases 2025-09-18 15:20:56 -05:00
P. Reis ceb716d2ab Merge branch 'main' into add-eye-password 2025-09-18 17:09:03 -03:00
Alex Gleason f43e582a78 Make react-hooks/exhaustive-deps required 2025-09-18 15:08:24 -05:00
P. Reis 1aafb67cbd fix CI eslint complain 2025-09-18 17:06:40 -03:00
P. Reis 81af9852a8 feat: add eye to toggle visibility of passwords 2025-09-18 17:02:32 -03:00
Alex Gleason c278618afd Always show sidebar in Settings on desktop 2025-09-18 13:30:52 -05:00
Alex Gleason 94a14c5f7e Fix sidebar menu button on ProjectView 2025-09-18 13:27:12 -05:00
Alex Gleason 47b2f2bb12 Merge branch 'menu-update' into 'main'
Menu update

Closes #25

See merge request soapbox-pub/act2!12
2025-09-18 18:06:25 +00:00
Alex Gleason 8d00ac57c7 Merge branch 'main' of gitlab.com:soapbox-pub/act2 2025-09-18 12:35:48 -05:00
Mary Kate Fain 85f1f4597e fix sidebar collapse button location when settings is open 2025-09-18 12:21:36 -05:00
Alex Gleason 3989a8a217 Implement GitHub PKCE 2025-09-18 12:15:04 -05:00
Alex Gleason 72f8a9def9 Fix Connect to GitHub styling 2025-09-18 12:02:06 -05:00
Alex Gleason 945bc002f2 Fix OAuth useEffect getting called twice 2025-09-18 11:54:58 -05:00
Mary Kate Fain 80e9a8decb add help center link to user menu 2025-09-18 11:48:02 -05:00
Alex Gleason 9ee120f765 Switch GitHub auth page to /oauth/github 2025-09-18 11:44:08 -05:00
Mary Kate Fain b73bb3971e move sidebar collapse button into the sidebar 2025-09-18 11:41:58 -05:00
Mary Kate Fain 69c38b489a Change logged out view to still have bottom user menu, and move settings into it 2025-09-18 11:35:50 -05:00
73 changed files with 6742 additions and 1696 deletions

No files matched your search

+41
View File
@@ -279,6 +279,47 @@ The AI assistant's behavior and knowledge is defined by the AGENTS.md file, whic
1. Edit AGENTS.md directly
2. The changes take effect in the next session
## Translations
Shakespeare includes internationalization (i18n) support using react-i18next. The translation system allows the interface to be displayed in multiple languages.
### Key Files
- **`src/lib/i18n.ts`**: Main translation configuration file containing all translation resources for supported languages
- **`src/components/LanguagePicker.tsx`**: Language selection component used in preferences, must be updated when adding new languages
### Usage in Components
Use the `useTranslation` hook to access translations in React components:
```tsx
import { useTranslation } from 'react-i18next';
function MyComponent() {
const { t } = useTranslation();
return <h1>{t('settings')}</h1>; // Returns "Settings", "Configurações", etc.
}
```
### Translation Key Organization
Translation keys are organized by functionality:
- **Navigation and Layout**: `preferences`, `settings`, `help`, etc.
- **Authentication**: `logIn`, `signUp`
- **UI Elements**: `save`, `cancel`, `loading`, etc.
- **Feature-specific sections**: AI Settings, Git Settings, Nostr Settings, etc.
### Adding New Languages
1. Add the new language code and translation object to the `resources` object in `src/lib/i18n.ts`
2. Add all required key-value pairs for the new language, following existing patterns
3. Update `src/components/LanguagePicker.tsx` to include the new language option in the dropdown
4. Add the language name translations (e.g., `spanish: 'Spanish'`) to all existing language objects
5. Use descriptive, hierarchical key names (avoid duplicates)
6. Keep translations concise and consistent with existing patterns
7. Test the new language thoroughly to ensure proper display across all components
## "Vibed with MKStack"
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+1
View File
@@ -27,6 +27,7 @@ export default tseslint.config(
},
rules: {
...reactHooks.configs.recommended.rules,
"react-hooks/exhaustive-deps": "error",
"react-refresh/only-export-components": [
"warn",
{ allowConstantExport: true },
+72 -30
View File
@@ -65,7 +65,7 @@ All messages follow JSON-RPC 2.0 specification:
"headers": {
"Content-Type": "application/json"
},
"body": "eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9" // base64 of: {"name":"John","age":30}
"body": "eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9" // base64 encoded: {"name":"John","age":30}
}
},
"id": 124
@@ -81,7 +81,7 @@ All messages follow JSON-RPC 2.0 specification:
"Content-Type": "application/javascript",
"Cache-Control": "no-cache"
},
"body": "Y29uc29sZS5sb2coJ2hlbGxvJyk7"
"body": "Y29uc29sZS5sb2coJ2hlbGxvJyk7" // base64 encoded: console.log('hello');
},
"id": 123
}
@@ -137,16 +137,28 @@ full request body support
Request bodies must be base64-encoded strings when not null. This ensures
consistent handling of both text and binary data across the messaging protocol.
### `console`
**Purpose:** Forward console messages from iframe to parent for display
**Parameters:**
- `level` (string): Log level - "log", "warn", "error", "info", "debug"
- `message` (string): The log message
**Result:** None (notification only, no response expected)
## Implementation
### Parent Page
In this example, the parent page acts as a static file server.
The parent page acts as a static file server and console log collector:
```javascript
class FetchClientParent {
constructor(files) {
this.files = files; // Map of path -> {content, contentType}
this.consoleLogs = []; // Store console messages
this.setupMessageListener();
}
@@ -156,12 +168,43 @@ class FetchClientParent {
if (event.origin !== "https://app123.example.com") return;
const message = event.data;
// Handle fetch requests
if (message.jsonrpc === "2.0" && message.method === "fetch") {
this.handleFetch(message);
}
// Handle console messages
if (message.jsonrpc === "2.0" && message.method === "console") {
this.handleConsoleMessage(message);
}
});
}
handleConsoleMessage(message) {
const { params } = message;
const { level, message: logMessage } = params;
// Store the log message
this.consoleLogs.push({
level,
message: logMessage,
timestamp: Date.now(),
id: Date.now()
});
// Update UI to show new logs
this.updateConsoleUI();
// Also log to parent's console for debugging
console[level](`[IFRAME] ${logMessage}`);
}
updateConsoleUI() {
// Implementation depends on your UI framework
console.log(`Total console logs: ${this.consoleLogs.length}`);
}
handleFetch(request) {
const { params, id } = request;
const { request: fetchRequest } = params;
@@ -170,9 +213,6 @@ class FetchClientParent {
const url = new URL(fetchRequest.url);
const path = url.pathname;
// Decode request body if present
const requestBody = fetchRequest.body ? atob(fetchRequest.body) : null;
const file = this.files.get(path);
if (file) {
@@ -186,11 +226,10 @@ class FetchClientParent {
"Content-Type": file.contentType,
"Cache-Control": "no-cache",
},
body: btoa(file.content), // base64 encode the response body
body: btoa(file.content),
},
});
} else {
// Return 404 response (not a JSON-RPC error)
this.sendResponse({
id,
jsonrpc: "2.0",
@@ -200,7 +239,7 @@ class FetchClientParent {
headers: {
"Content-Type": "text/plain",
},
body: btoa(`File not found: ${path}`), // base64 encode the error message
body: btoa(`File not found: ${path}`),
},
});
}
@@ -210,22 +249,15 @@ class FetchClientParent {
const iframe = document.getElementById("preview-iframe");
iframe.contentWindow.postMessage(message, "https://app123.example.com");
}
sendError(message) {
const iframe = document.getElementById("preview-iframe");
iframe.contentWindow.postMessage(message, "https://app123.example.com");
}
}
```
### Preview Page
### iframe Client Communication
Below is a simplified RPC client that could be used inside the iframe's main
thread to test functionality of the parent. In practice, requests originate from
the ServiceWorker and the main thread acts as a relay, so multiple steps of
communication are involved.
The iframe client uses a simplified JSON-RPC client for communication. In the actual implementation, the ServiceWorker makes requests and the main thread acts as a relay:
```javascript
// Simplified JSON-RPC client (actual implementation in _iframe-client/main.js)
class JSONRPCClient {
constructor() {
this.requestId = 0;
@@ -236,7 +268,7 @@ class JSONRPCClient {
setupMessageListener() {
window.addEventListener("message", (event) => {
const message = event.data;
if (message.jsonrpc === "2.0" && message.id) {
if (message.jsonrpc === "2.0" && message.id !== undefined) {
this.handleResponse(message);
}
});
@@ -248,7 +280,6 @@ class JSONRPCClient {
return new Promise((resolve, reject) => {
this.pendingRequests.set(id, { resolve, reject });
// Send request to parent
window.parent.postMessage({
jsonrpc: "2.0",
method: "fetch",
@@ -256,7 +287,6 @@ class JSONRPCClient {
id,
}, "*");
// Timeout after 10 seconds
setTimeout(() => {
if (this.pendingRequests.has(id)) {
this.pendingRequests.delete(id);
@@ -275,9 +305,8 @@ class JSONRPCClient {
this.pendingRequests.delete(id);
if (error) {
pending.reject(new Error(error.message));
pending.reject(new Error(`${error.message} (code: ${error.code})`));
} else {
// Result is a serialized response
pending.resolve(result);
}
}
@@ -286,7 +315,7 @@ class JSONRPCClient {
## Base64 Encoding
All request and response bodies must be base64 encoded when not null. This ensures:
All request and response bodies are base64 encoded when not null to ensure proper transmission through JSON-RPC:
- **Consistent Data Handling:** Both text and binary data are handled uniformly
- **JSON Compatibility:** Avoids issues with special characters in JSON messages
@@ -294,11 +323,16 @@ All request and response bodies must be base64 encoded when not null. This ensur
**Encoding/Decoding:**
```javascript
// Encoding (before sending)
const encodedBody = btoa(originalBody);
// Encoding text content (parent side)
const encodedBody = btoa(textContent);
// Decoding (after receiving)
const decodedBody = atob(encodedBody);
// Encoding binary content (ServiceWorker side)
const bytes = new Uint8Array(arrayBuffer);
const encodedBody = btoa(String.fromCharCode(...bytes));
// Decoding (receiver side)
const decodedText = atob(encodedBody);
const decodedBytes = new Uint8Array(atob(encodedBody).split('').map(c => c.charCodeAt(0)));
```
## Security
@@ -324,9 +358,17 @@ const decodedBody = atob(encodedBody);
content: "<!DOCTYPE html><html><body>Hello world!</body></html>",
contentType: "text/html",
}],
["/app.js", {
content: "console.log('App loaded');",
contentType: "application/javascript",
}],
]);
// Example static file server
// Initialize the fetch client parent
new FetchClientParent(files);
</script>
```
## Console Logging Implementation
The iframe client automatically intercepts console messages and forwards them to the parent. The implementation (in `_iframe-client/main.js`) overrides console methods.
+35 -21
View File
@@ -54,30 +54,31 @@ blocked.
```
/
├── index.html # Main iframe client page
├── _iframe-client.js # Main coordination script
├── _iframe-client.css # Styles for the iframe client
├── sw.js # ServiceWorker
├── MESSAGING_PROTOCOL.md # Communication protocol docs
├── example-parent.html # Example parent implementation
└── README.md # This file
├── index.html # Main iframe client page
├── _iframe-client/
│ ├── main.js # Main coordination script
│ └── client.css # Styles for the iframe client
├── sw.js # ServiceWorker
├── MESSAGING_PROTOCOL.md # Communication protocol docs
└── README.md # This file
```
## Simplified JSON-RPC Protocol
The system now uses a drastically simplified JSON-RPC 2.0 protocol with only one
method:
The system now uses a simplified JSON-RPC 2.0 protocol with two methods:
- **`fetch(request)`** - Handle HTTP requests with serialized fetch
request/response
- **`console(level, message)`** - Forward console messages from
iframe to parent for display
**Request:**
```javascript
{
"jsonrpc": "2.0",
"method": "fetch",
"params": {
"method": "fetch",
"params": {
"request": {
"url": "https://app123.example.com/assets/main.js",
"method": "GET",
@@ -106,6 +107,19 @@ method:
}
```
**Console Message:**
```javascript
{
"jsonrpc": "2.0",
"method": "console",
"params": {
"level": "error",
"message": "Failed to load module"
}
}
```
## How It Works
1. **Initialization:**
@@ -136,8 +150,9 @@ Deploy these files to your iframe client subdomain:
```
https://*.example.com/
├── index.html
├── _iframe-client.js
├── _iframe-client.css
├── _iframe-client/
│ ├── main.js
│ └── client.css
└── sw.js
```
@@ -158,8 +173,7 @@ Include the iframe client in your parent page:
</iframe>
```
Implement the JSON-RPC protocol (see `example-parent.html` for a complete
example):
Implement the JSON-RPC protocol:
```javascript
class FetchClientParent {
@@ -270,9 +284,9 @@ function handleRequest(fetchRequest) {
## Testing
1. Open `example-parent.html` in a browser
2. Click "Load Sample Site"
3. The iframe client should load and display the sample app
1. Create a parent page implementing the JSON-RPC protocol (see example in MESSAGING_PROTOCOL.md)
2. Load the iframe client in an iframe pointing to your deployed client domain
3. The iframe client should load and display the served content
4. Test navigation and functionality within the iframe client
## Browser Support
@@ -312,10 +326,10 @@ function handleRequest(fetchRequest) {
To modify the system:
1. **iframe Client:** Edit `index.html`, `_iframe-client.js`,
`_iframe-client.css`, `sw.js`
1. **iframe Client:** Edit `index.html`, `_iframe-client/main.js`,
`_iframe-client/client.css`, `sw.js`
2. **Protocol:** Update `MESSAGING_PROTOCOL.md` for any changes
3. **Testing:** Use `example-parent.html` for testing changes
3. **Testing:** Create a parent page implementing the JSON-RPC protocol for testing changes
## License
-270
View File
@@ -1,270 +0,0 @@
/**
* iframe Fetch Client Main Script
* JSON-RPC based communication with parent page
*/
class JSONRPCClient {
constructor() {
this.requestId = 0;
this.pendingRequests = new Map();
this.setupMessageListener();
}
setupMessageListener() {
window.addEventListener("message", (event) => {
const message = event.data;
if (message.jsonrpc === "2.0" && message.id !== undefined) {
// Check if this is a response to our own request or a ServiceWorker request
if (this.pendingRequests.has(message.id)) {
this.handleResponse(message);
} else {
// This is a response to a ServiceWorker request, relay it back
this.relayJSONRPCToServiceWorker(message);
}
}
});
}
relayJSONRPCToServiceWorker(response) {
// Forward the JSON-RPC response to ServiceWorker
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage(response);
}
}
async fetch(request) {
const id = ++this.requestId;
return new Promise((resolve, reject) => {
this.pendingRequests.set(id, { resolve, reject });
// Send JSON-RPC request to parent
window.parent.postMessage({
jsonrpc: "2.0",
method: "fetch",
params: { request },
id,
}, "*");
// Timeout after 10 seconds
setTimeout(() => {
if (this.pendingRequests.has(id)) {
this.pendingRequests.delete(id);
reject(new Error(`Timeout fetching: ${request.url}`));
}
}, 10000);
});
}
handleResponse(message) {
const { id, result, error } = message;
const pending = this.pendingRequests.get(id);
if (!pending) return;
this.pendingRequests.delete(id);
if (error) {
pending.reject(new Error(`${error.message} (code: ${error.code})`));
} else {
pending.resolve(result);
}
}
}
class FetchClient {
constructor() {
this.rpcClient = new JSONRPCClient();
this.swReady = false;
this.init();
}
async init() {
try {
await this.registerServiceWorker();
this.setupServiceWorkerCommunication();
await this.waitForServiceWorker();
await this.fetchSiteIndex();
} catch (error) {
this.showError("Failed to initialize fetch client", error);
}
}
async registerServiceWorker() {
if (!("serviceWorker" in navigator)) {
throw new Error("ServiceWorker not supported");
}
// Check if SW is already registered
const existingRegistration = await navigator.serviceWorker
.getRegistration();
if (existingRegistration) {
console.log("ServiceWorker already registered");
this.swReady = true;
return;
}
try {
const registration = await navigator.serviceWorker.register("/sw.js", {
scope: "/",
});
console.log("ServiceWorker registered:", registration);
// Wait for SW to be ready
await navigator.serviceWorker.ready;
this.swReady = true;
// Block future registrations to prevent site from registering its own SW
this.blockFutureRegistrations();
} catch (error) {
throw new Error(`ServiceWorker registration failed: ${error.message}`);
}
}
blockFutureRegistrations() {
navigator.serviceWorker.register = function () {
console.log("Blocked ServiceWorker registration attempt");
return Promise.resolve({
scope: "/",
active: navigator.serviceWorker.controller,
installing: null,
waiting: null,
addEventListener: () => {},
removeEventListener: () => {},
});
};
}
setupServiceWorkerCommunication() {
// Listen for JSON-RPC requests from ServiceWorker and relay them to parent
navigator.serviceWorker.addEventListener("message", async (event) => {
const { data } = event;
// Check if this is a JSON-RPC request from ServiceWorker
if (data.jsonrpc === "2.0" && data.method && data.id !== undefined) {
this.relayJSONRPCToParent(data);
}
});
}
relayJSONRPCToParent(request) {
// Forward the JSON-RPC request directly to parent
window.parent.postMessage(request, "*");
}
async waitForServiceWorker() {
const timeout = 10000; // 10 seconds
const start = Date.now();
while (!this.swReady) {
if (Date.now() - start > timeout) {
throw new Error("Timeout waiting for ServiceWorker readiness");
}
await new Promise((resolve) => setTimeout(resolve, 100));
}
console.log("ServiceWorker is ready");
}
async fetchSiteIndex() {
try {
// Request site index from parent via JSON-RPC fetch
const serializedRequest = {
url: `${location.origin}/`,
method: "GET",
body: null,
headers: {},
};
const response = await this.rpcClient.fetch(serializedRequest);
if (response.status !== 200) {
throw new Error(`Failed to fetch site index: ${response.status} ${response.statusText}`);
}
if (response.headers["Content-Type"] !== "text/html") {
throw new Error(`Unexpected Content-Type: ${response.headers["Content-Type"]}`);
}
const bytes = new Uint8Array(atob(response.body).split('').map(c => c.charCodeAt(0)));
const text = new TextDecoder().decode(bytes);
// Replace current document with the site index content
this.replaceDocument(text);
} catch (error) {
this.showError("Failed to load site index", error);
}
}
replaceDocument(htmlContent) {
// Create a new document from the HTML content
const parser = new DOMParser();
const newDoc = parser.parseFromString(htmlContent, "text/html");
const scripts = [];
newDoc.querySelectorAll("script").forEach((script) => {
scripts.push({
src: script.src,
type: script.type,
async: script.hasAttribute("async"),
defer: script.hasAttribute("defer"),
});
script.parentNode.removeChild(script);
});
// Replace the entire document
document.head.innerHTML = newDoc.head.innerHTML;
document.body.innerHTML = newDoc.body.innerHTML;
// Re-add scripts (this is necessary to execute them)
scripts.forEach((script) => {
const newScript = document.createElement("script");
newScript.src = script.src;
newScript.type = script.type;
if (script.async) newScript.async = true;
if (script.defer) newScript.defer = true;
document.body.appendChild(newScript);
});
console.log("Document replaced with site content");
}
showError(message, error) {
console.error(message, error);
document.body.innerHTML = `
<div style="
font-family: system-ui, -apple-system, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
border-left: 4px solid #dc3545;
">
<h2 style="color: #dc3545; margin-top: 0;">Fetch Client Error</h2>
<p><strong>${message}</strong></p>
<p style="color: #6c757d;">${error.message || error}</p>
<details style="margin-top: 20px;">
<summary style="cursor: pointer; color: #007bff;">Technical Details</summary>
<pre style="
background: #f1f3f4;
padding: 10px;
border-radius: 4px;
overflow-x: auto;
font-size: 12px;
margin-top: 10px;
">${error.stack || JSON.stringify(error, null, 2)}</pre>
</details>
</div>
`;
}
}
// Initialize when DOM is ready
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => new FetchClient());
} else {
new FetchClient();
}
+350
View File
@@ -0,0 +1,350 @@
/**
* iframe Fetch Client - Simplified Implementation
* Implements JSON-RPC 2.0 messaging protocol per MESSAGING_PROTOCOL.md
*/
// JSON-RPC Client for communication with parent
class JSONRPCClient {
constructor() {
this.requestId = 0;
this.pendingRequests = new Map();
this.setupMessageListener();
}
setupMessageListener() {
window.addEventListener("message", (event) => {
const message = event.data;
// Check if this is a response to our own request or a ServiceWorker request
if (message.jsonrpc === "2.0" && message.id !== undefined) {
if (this.pendingRequests.has(message.id)) {
this.handleResponse(message);
} else {
// This is a response to a ServiceWorker request, relay it back
this.relayToServiceWorker(message);
}
}
});
}
relayToServiceWorker(response) {
// Forward the JSON-RPC response to ServiceWorker
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage(response);
}
}
async fetch(request) {
const id = ++this.requestId;
return new Promise((resolve, reject) => {
this.pendingRequests.set(id, { resolve, reject });
// Send JSON-RPC request to parent
window.parent.postMessage({
jsonrpc: "2.0",
method: "fetch",
params: { request },
id,
}, "*");
// Timeout after 10 seconds
setTimeout(() => {
if (this.pendingRequests.has(id)) {
this.pendingRequests.delete(id);
reject(new Error(`Timeout fetching: ${request.url}`));
}
}, 10000);
});
}
handleResponse(message) {
const { id, result, error } = message;
const pending = this.pendingRequests.get(id);
if (!pending) return;
this.pendingRequests.delete(id);
if (error) {
pending.reject(new Error(`${error.message} (code: ${error.code})`));
} else {
pending.resolve(result);
}
}
}
// Console Interceptor - forwards console messages to parent
class ConsoleInterceptor {
constructor() {
this.originalConsole = {};
this.methods = ['log', 'warn', 'error', 'info', 'debug'];
this.init();
}
init() {
// Store original methods and override in single pass
this.methods.forEach((method) => {
if (typeof console[method] === 'function') {
this.originalConsole[method] = console[method];
console[method] = (...args) => {
// Call original method
try {
this.originalConsole[method](...args);
} catch (e) {
// Continue if original fails
}
// Send to parent
this.sendConsoleMessage(method, ...args);
};
}
});
}
sendConsoleMessage(level, ...args) {
const message = args.map((arg) => {
if (arg === undefined) return 'undefined';
if (arg === null) return 'null';
if (typeof arg === 'object') {
try {
return JSON.stringify(arg, (key, value) => {
if (value instanceof Error) {
return {
name: value.name,
message: value.message,
stack: value.stack
};
}
return value;
});
} catch {
return String(arg);
}
}
return String(arg);
}).join(' ');
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: { level, message }
}, "*");
} catch (error) {
// Retry once after delay if postMessage fails
setTimeout(() => {
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: { level: "error", message: `[DELAYED] ${message}` }
}, "*");
} catch {
// Give up if retry fails
}
}, 100);
}
}
}
// Main Fetch Client
class FetchClient {
constructor() {
this.rpcClient = new JSONRPCClient();
this.consoleInterceptor = new ConsoleInterceptor();
this.init();
}
async init() {
try {
await this.setupServiceWorker();
await this.loadSiteIndex();
} catch (error) {
this.showError("Failed to initialize fetch client", error);
}
}
async setupServiceWorker() {
if (!("serviceWorker" in navigator)) {
throw new Error("ServiceWorker not supported");
}
// Check if already registered
const existing = await navigator.serviceWorker.getRegistration();
if (existing) {
console.log("ServiceWorker already registered");
this.setupServiceWorkerCommunication();
return;
}
// Register new ServiceWorker
const registration = await navigator.serviceWorker.register("/sw.js", { scope: "/" });
console.log("ServiceWorker registered:", registration);
await navigator.serviceWorker.ready;
this.setupServiceWorkerCommunication();
this.blockFutureRegistrations(); // Block future registrations to prevent site from registering its own SW
}
setupServiceWorkerCommunication() {
// Relay JSON-RPC requests from ServiceWorker to parent
navigator.serviceWorker.addEventListener("message", (event) => {
const { data } = event;
if (data.jsonrpc === "2.0" && data.method && data.id !== undefined) {
window.parent.postMessage(data, "*");
}
});
}
blockFutureRegistrations() {
navigator.serviceWorker.register = () => {
console.log("Blocked ServiceWorker registration attempt");
return Promise.resolve({
scope: "/",
active: navigator.serviceWorker.controller,
installing: null,
waiting: null,
addEventListener: () => {},
removeEventListener: () => {},
});
};
}
async loadSiteIndex() {
const serializedRequest = {
url: `${location.origin}/`,
method: "GET",
body: null,
headers: {},
};
const response = await this.rpcClient.fetch(serializedRequest);
if (response?.status !== 200) {
throw new Error(`Failed to fetch site index: ${response?.status || 'Invalid response from site: ' + response} ${response?.statusText || ''}`);
}
if (response.headers["Content-Type"] !== "text/html") {
throw new Error(`Unexpected Content-Type: ${response.headers["Content-Type"]}`);
}
const bytes = new Uint8Array(atob(response.body).split('').map(c => c.charCodeAt(0)));
const text = new TextDecoder().decode(bytes);
this.replaceDocument(text);
}
replaceDocument(htmlContent) {
// Create a new document from the HTML content
const parser = new DOMParser();
const newDoc = parser.parseFromString(htmlContent, "text/html");
// Extract scripts for re-execution
const scripts = [];
newDoc.querySelectorAll("script").forEach((script) => {
scripts.push({
src: script.src,
type: script.type,
async: script.hasAttribute("async"),
defer: script.hasAttribute("defer"),
});
script.remove();
});
// Replace document content
document.head.innerHTML = newDoc.head.innerHTML;
document.body.innerHTML = newDoc.body.innerHTML;
// Re-add scripts to execute them
scripts.forEach((script) => {
const newScript = document.createElement("script");
newScript.src = script.src;
newScript.type = script.type;
if (script.async) newScript.async = true;
if (script.defer) newScript.defer = true;
document.body.appendChild(newScript);
});
console.log("Document replaced with site content");
}
showError(message, error) {
console.error(message, error);
document.body.innerHTML = `
<div style="
font-family: system-ui, -apple-system, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
border-left: 4px solid #dc3545;
">
<h2 style="color: #dc3545; margin-top: 0;">Fetch Client Error</h2>
<p><strong>${message}</strong></p>
<p style="color: #6c757d;">${error.message || error}</p>
<details style="margin-top: 20px;">
<summary style="cursor: pointer; color: #007bff;">Technical Details</summary>
<pre style="
background: #f1f3f4;
padding: 10px;
border-radius: 4px;
overflow-x: auto;
font-size: 12px;
margin-top: 10px;
">${error.stack || JSON.stringify(error, null, 2)}</pre>
</details>
</div>
`;
}
}
// Global error handlers
const setupGlobalErrorHandlers = () => {
window.addEventListener('error', (event) => {
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: {
level: "error",
message: `Uncaught Error: ${event.message}`,
source: event.filename,
lineno: event.lineno,
colno: event.colno,
stack: event.error?.stack
}
}, "*");
} catch {
// Ignore postMessage errors
}
});
window.addEventListener('unhandledrejection', (event) => {
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: {
level: "error",
message: "Unhandled Promise Rejection",
reason: event.reason,
promise: event.promise ? 'Promise object' : 'No promise object'
}
}, "*");
} catch {
// Ignore postMessage errors
}
});
};
// Initialize
setupGlobalErrorHandlers();
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => new FetchClient());
} else {
new FetchClient();
}
+2 -2
View File
@@ -4,7 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Site Preview</title>
<link rel="stylesheet" href="/_iframe-client.css">
<link rel="stylesheet" href="/_iframe-client/client.css">
</head>
<body>
<div class="loading">
@@ -12,6 +12,6 @@
<p>Loading preview...</p>
<p><small>Waiting for ServiceWorker and parent communication</small></p>
</div>
<script src="/_iframe-client.js"></script>
<script type="module" src="/_iframe-client/main.js"></script>
</body>
</html>
+163 -798
View File
File diff suppressed because it is too large. Load diff
+4 -4
View File
@@ -44,7 +44,6 @@
"@radix-ui/react-toggle": "^1.1.0",
"@radix-ui/react-toggle-group": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.4",
"@soapbox.pub/streamdown": "^1.0.11",
"@std/encoding": "npm:@jsr/std__encoding@^1.0.10",
"@std/path": "npm:@jsr/std__path@^1.1.1",
"@tanstack/react-query": "^5.56.2",
@@ -57,6 +56,7 @@
"decimal.js": "^10.6.0",
"embla-carousel-react": "^8.3.0",
"esbuild-wasm": "^0.25.8",
"i18next": "^25.5.2",
"ignore": "^7.0.5",
"input-otp": "^1.2.4",
"isomorphic-git": "^1.32.1",
@@ -70,13 +70,13 @@
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.53.0",
"react-i18next": "^15.7.3",
"react-markdown": "^10.1.0",
"react-resizable-panels": "^3.0.3",
"react-router-dom": "^6.26.2",
"react-syntax-highlighter": "^15.6.1",
"recharts": "^2.12.7",
"remark-gfm": "^4.0.1",
"streamdown": "^1.0.12",
"streamdown": "~1.0.0",
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"turndown": "^7.2.1",
@@ -96,9 +96,9 @@
"@types/jszip": "^3.4.0",
"@types/node": "^22.5.5",
"@types/path-browserify": "^1.0.3",
"@types/qrcode": "^1.5.5",
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@types/react-syntax-highlighter": "^15.5.13",
"@types/turndown": "^5.0.5",
"@vitejs/plugin-react-swc": "^3.5.0",
"autoprefixer": "^10.4.20",
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+8
View File
@@ -5,9 +5,13 @@ import { SessionMonitor } from "./components/SessionMonitor";
import Index from "./pages/Index";
import Clone from "./pages/Clone";
import Settings from "./pages/Settings";
import Preferences from "./pages/Preferences";
import NostrSettings from "./pages/NostrSettings";
import AISettings from "./pages/AISettings";
import GitSettings from "./pages/GitSettings";
import DataSettings from "./pages/DataSettings";
import AboutSettings from "./pages/AboutSettings";
import GitHubOAuth from "./pages/GitHubOAuth";
import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound";
import { ProjectView } from "./pages/ProjectView";
@@ -21,11 +25,15 @@ export function AppRouter() {
<Routes>
<Route path="/" element={<Index />} />
<Route path="/clone" element={<Clone />} />
<Route path="/oauth/github" element={<GitHubOAuth />} />
<Route path="/settings" element={<SettingsLayout />}>
<Route index element={<Settings />} />
<Route path="preferences" element={<Preferences />} />
<Route path="nostr" element={<NostrSettings />} />
<Route path="ai" element={<AISettings />} />
<Route path="git" element={<GitSettings />} />
<Route path="data" element={<DataSettings />} />
<Route path="about" element={<AboutSettings />} />
</Route>
<Route path="/project/:projectId" element={<ProjectView />} />
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
+51 -2
View File
@@ -1,23 +1,33 @@
import { memo, useState } from 'react';
import { Streamdown } from 'streamdown';
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle } from 'lucide-react';
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2 } from 'lucide-react';
import type { AIMessage } from '@/lib/SessionManager';
import { cn } from '@/lib/utils';
import { UserMessage } from '@/components/UserMessage';
import OpenAI from 'openai';
import { useTheme } from '@/hooks/useTheme';
// Type guard to check if message has reasoning content
function hasReasoningContent(message: AIMessage): message is AIMessage & { reasoning_content: string } {
return message.role === 'assistant' && 'reasoning_content' in message && typeof (message as { reasoning_content?: unknown }).reasoning_content === 'string';
}
interface AIMessageItemProps {
message: AIMessage;
isCurrentlyLoading?: boolean;
toolCall?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined; // Tool call data passed from the assistant message
reasoningContent?: string; // Reasoning content for streaming messages
}
export const AIMessageItem = memo(({
message,
isCurrentlyLoading = false,
toolCall
toolCall,
reasoningContent
}: AIMessageItemProps) => {
const [isToolExpanded, setIsToolExpanded] = useState(false);
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
const { displayTheme } = useTheme();
// Get content to display
const getContent = () => {
@@ -228,10 +238,49 @@ export const AIMessageItem = memo(({
<div className="flex">
<div className="flex-1 min-w-0">
<div className="text-sm">
{/* Reasoning content display */}
{((reasoningContent && reasoningContent.trim()) ||
(hasReasoningContent(message) && message.reasoning_content.trim()) ||
(reasoningContent !== undefined && !getContent().trim() && isCurrentlyLoading)) && (
<div className="mb-3">
<button
onClick={() => setIsReasoningExpanded(!isReasoningExpanded)}
className={cn(
"w-full flex items-center gap-2 px-2 py-1 text-xs",
"hover:bg-muted/30 rounded transition-colors duration-200"
)}
>
{reasoningContent !== undefined && !getContent().trim() && isCurrentlyLoading ? (
<Loader2 className="h-3 w-3 text-muted-foreground flex-shrink-0 animate-spin" />
) : (
<Lightbulb className="h-3 w-3 text-muted-foreground flex-shrink-0" />
)}
<span className="text-muted-foreground font-medium flex-1 text-left">
Thinking
</span>
</button>
{isReasoningExpanded && (reasoningContent?.trim() || (hasReasoningContent(message) && message.reasoning_content.trim())) && (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
<div className="whitespace-pre-wrap break-words">
<Streamdown
className='size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0'
parseIncompleteMarkdown={isCurrentlyLoading}
shikiTheme={displayTheme === 'dark' ? 'github-dark' : 'github-light'}
>
{reasoningContent || (hasReasoningContent(message) ? message.reasoning_content : '') || ''}
</Streamdown>
</div>
</div>
)}
</div>
)}
<div className="break-words">
<Streamdown
className='size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0'
parseIncompleteMarkdown={isCurrentlyLoading}
shikiTheme={displayTheme === 'dark' ? 'github-dark' : 'github-light'}
>
{getContent()}
</Streamdown>
+8 -6
View File
@@ -4,7 +4,7 @@ import { type Project } from '@/lib/ProjectsManager';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { ProjectSidebar } from '@/components/ProjectSidebar';
import { Button } from '@/components/ui/button';
import { Menu, Columns2 } from 'lucide-react';
import { Menu } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
interface AppLayoutProps {
@@ -108,6 +108,7 @@ export function AppLayout({
setIsSidebarVisible(false); // Always collapse sidebar on mobile navigation
handleProjectSelect(project);
}}
onClose={() => setIsSidebarVisible(false)}
/>
</div>
</div>
@@ -129,6 +130,7 @@ export function AppLayout({
selectedProject={selectedProject}
onSelectProject={handleProjectSelect}
className="h-screen sticky top-0"
onToggleSidebar={() => setIsSidebarVisible(false)}
/>
</div>
)}
@@ -136,16 +138,16 @@ export function AppLayout({
{/* Main Content Area */}
<div className="flex-1 flex flex-col bg-background">
<div className="min-h-screen bg-gradient-to-br from-primary/5 to-accent/5 relative">
{/* Toggle Button - positioned absolutely in top-left corner */}
{showSidebar && (
{/* Show open button when sidebar is collapsed */}
{showSidebar && !isSidebarVisible && (
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
onClick={() => setIsSidebarVisible(true)}
className="absolute top-2 left-4 h-8 w-8 p-0 z-10 bg-transparent backdrop-blur-sm hover:bg-transparent text-foreground/70 hover:text-foreground"
aria-label="Toggle sidebar"
aria-label="Open sidebar"
>
{isSidebarVisible ? <Columns2 className="h-4 w-4" /> : <Menu className="h-4 w-4" />}
<Menu className="h-4 w-4" />
</Button>
)}
+14
View File
@@ -2,6 +2,7 @@ import { ReactNode, useEffect } from 'react';
import { z } from 'zod';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext';
import i18n from '@/lib/i18n';
interface AppProviderProps {
children: ReactNode;
@@ -18,6 +19,7 @@ const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
theme: z.enum(['dark', 'light', 'system']),
relayUrl: z.string().url(),
deployServer: z.string().min(1),
language: z.string().optional(),
});
export function AppProvider(props: AppProviderProps) {
@@ -55,6 +57,9 @@ export function AppProvider(props: AppProviderProps) {
// Apply theme effects to document
useApplyTheme(config.theme);
// Apply language effects to i18n
useApplyLanguage(config.language);
return (
<AppContext.Provider value={appContextValue}>
{children}
@@ -101,4 +106,13 @@ function useApplyTheme(theme: Theme) {
mediaQuery.addEventListener('change', handleChange);
return () => mediaQuery.removeEventListener('change', handleChange);
}, [theme]);
}
/**
* Hook to apply language changes to i18n
*/
function useApplyLanguage(language?: string): void {
useEffect(() => {
i18n.changeLanguage(language ?? navigator.language);
}, [language]);
}
+85
View File
@@ -0,0 +1,85 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { CreditsBadge } from './CreditsBadge';
import type { AIConnection } from '@/contexts/AISettingsContext';
// Mock the useAICredits hook
vi.mock('@/hooks/useAICredits', () => ({
useAICredits: () => ({
data: { amount: 10.50 },
isLoading: false,
error: null,
}),
}));
// Mock the fetch function
global.fetch = vi.fn();
const mockConnection: AIConnection = {
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
};
describe('CreditsBadge', () => {
it('renders the credits amount', () => {
render(
<TestApp>
<CreditsBadge
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
expect(screen.getByText('$10.50')).toBeInTheDocument();
});
it('calls onOpenDialog when badge is clicked', () => {
const mockCallback = vi.fn();
render(
<TestApp>
<CreditsBadge
providerId="test-provider"
connection={mockConnection}
onOpenDialog={mockCallback}
/>
</TestApp>
);
const badge = screen.getByText('$10.50');
fireEvent.click(badge);
expect(mockCallback).toHaveBeenCalled();
});
it('has proper styling for clickable badge', () => {
render(
<TestApp>
<CreditsBadge
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
const badge = screen.getByText('$10.50');
expect(badge).toHaveClass('cursor-pointer');
expect(badge).toHaveClass('hover:bg-secondary/80');
});
it('does not render dialog directly', () => {
render(
<TestApp>
<CreditsBadge
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
// Dialog should not be rendered by CreditsBadge itself
expect(screen.queryByText('Credits - test-provider')).not.toBeInTheDocument();
});
});
+48
View File
@@ -0,0 +1,48 @@
import { Badge } from '@/components/ui/badge';
import { useAICredits } from '@/hooks/useAICredits';
import type { AIConnection } from '@/contexts/AISettingsContext';
interface CreditsBadgeProps {
providerId: string;
connection: AIConnection;
className?: string;
onOpenDialog?: () => void;
}
/**
* Displays a clickable credits badge showing the remaining credits for an AI provider
*/
export function CreditsBadge({ providerId, connection, className, onOpenDialog }: CreditsBadgeProps) {
const { data: credits, isLoading, error } = useAICredits(providerId, connection);
// Don't render anything if there's an error (provider doesn't support credits endpoint)
if (error || isLoading) {
return null;
}
// Don't render if no credits data is available
if (!credits) {
return null;
}
// Format the amount as currency
const formattedAmount = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(credits.amount);
return (
<Badge
variant="secondary"
className={`cursor-pointer hover:bg-secondary/80 transition-colors ${className}`}
onClick={(e) => {
e.stopPropagation();
onOpenDialog?.();
}}
>
{formattedAmount}
</Badge>
);
}
+125
View File
@@ -0,0 +1,125 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { CreditsDialog } from './CreditsDialog';
import type { AIConnection } from '@/contexts/AISettingsContext';
// Mock the fetch function
global.fetch = vi.fn();
const mockConnection: AIConnection = {
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
};
describe('CreditsDialog', () => {
it('renders dialog when open', () => {
render(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
expect(screen.getByText('Credits')).toBeInTheDocument();
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
expect(screen.getByText('Recent Transactions')).toBeInTheDocument();
});
it('does not render when closed', () => {
render(
<TestApp>
<CreditsDialog
open={false}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
expect(screen.queryByText('Credits')).not.toBeInTheDocument();
});
it('shows payment method options', () => {
render(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
expect(screen.getByText('Payment Method')).toBeInTheDocument();
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
});
it('shows preset amount buttons', () => {
render(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
expect(screen.getByText('$5')).toBeInTheDocument();
expect(screen.getByText('$10')).toBeInTheDocument();
expect(screen.getByText('$25')).toBeInTheDocument();
expect(screen.getByText('$50')).toBeInTheDocument();
expect(screen.getByText('$100')).toBeInTheDocument();
});
it('shows login requirement when user is not logged in', () => {
render(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
expect(screen.getByText('Please log in to purchase credits')).toBeInTheDocument();
});
it('calls onDialogStateChange callback when dialog state changes', () => {
const mockCallback = vi.fn();
const { rerender } = render(
<TestApp>
<CreditsDialog
open={false}
onOpenChange={mockCallback}
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
// Simulate opening the dialog
rerender(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={mockCallback}
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
expect(screen.getByText('Credits')).toBeInTheDocument();
});
});
+620
View File
@@ -0,0 +1,620 @@
import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import QRCode from 'qrcode';
import { CreditCard, Zap, ExternalLink, RefreshCw, Check, X, Clock, AlertCircle, Copy, RotateCcw, ArrowLeft } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Skeleton } from '@/components/ui/skeleton';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useToast } from '@/hooks/useToast';
import { createAIClient } from '@/lib/ai-client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import type { AIConnection } from '@/contexts/AISettingsContext';
interface CreditsDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
providerId: string;
connection: AIConnection;
}
interface Payment {
object: 'payment';
id: string;
status: 'pending' | 'completed' | 'failed' | 'expired';
amount: number;
fee: number;
total: number;
method: 'stripe' | 'lightning';
description: string;
url: string;
created_at: number;
completed_at?: number;
expires_at: number;
}
interface PaymentsResponse {
object: 'list';
data: Payment[];
has_more: boolean;
url: string;
}
interface AddCreditsRequest {
amount: number;
method: 'stripe' | 'lightning';
redirect_url?: string;
}
const PRESET_AMOUNTS = [5, 10, 25, 50, 100];
interface LightningPaymentProps {
invoice: string;
amount: number;
onClose: () => void;
}
function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) {
const [qrDataUrl, setQrDataUrl] = useState<string>('');
const [isWebLNAvailable, setIsWebLNAvailable] = useState(false);
const [isPayingWithWebLN, setIsPayingWithWebLN] = useState(false);
const [showCopiedTooltip, setShowCopiedTooltip] = useState(false);
const { toast } = useToast();
useEffect(() => {
// Generate QR code
QRCode.toDataURL(invoice, {
width: 256,
margin: 2,
color: {
dark: '#000000',
light: '#ffffff',
},
})
.then(setQrDataUrl)
.catch(console.error);
// Check for WebLN availability
setIsWebLNAvailable(typeof window !== 'undefined' && 'webln' in window);
}, [invoice]);
const handleWebLNPay = async () => {
if (!window.webln) return;
try {
setIsPayingWithWebLN(true);
await window.webln.enable();
await window.webln.sendPayment(invoice);
toast({
title: 'Payment sent!',
description: 'Your Lightning payment has been sent successfully.',
});
onClose();
} catch (error) {
console.error('WebLN payment failed:', error);
toast({
title: 'Payment failed',
description: error instanceof Error ? error.message : 'Failed to send Lightning payment',
variant: 'destructive',
});
} finally {
setIsPayingWithWebLN(false);
}
};
const handleCopyInvoice = () => {
navigator.clipboard.writeText(invoice);
setShowCopiedTooltip(true);
setTimeout(() => setShowCopiedTooltip(false), 2000);
};
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(amount);
};
return (
<div className="space-y-4">
<div className="text-center">
<h3 className="text-lg font-semibold mb-2">Lightning Payment</h3>
<p className="text-sm text-muted-foreground">
Pay {formatCurrency(amount)} with Lightning Network
</p>
</div>
{/* QR Code */}
<div className="flex justify-center">
{qrDataUrl ? (
<div className="p-4 bg-white rounded-lg border">
<img src={qrDataUrl} alt="Lightning Invoice QR Code" className="w-48 h-48" />
</div>
) : (
<div className="w-48 h-48 bg-muted rounded-lg flex items-center justify-center">
<RefreshCw className="h-6 w-6 animate-spin" />
</div>
)}
</div>
{/* Payment Buttons */}
<div className="space-y-2">
{isWebLNAvailable && (
<Button
onClick={handleWebLNPay}
disabled={isPayingWithWebLN}
className="w-full"
size="lg"
>
{isPayingWithWebLN && <RefreshCw className="h-4 w-4 mr-2 animate-spin" />}
<Zap className="h-4 w-4 mr-2" />
Pay with WebLN
</Button>
)}
<div className="relative">
<Button
variant="outline"
onClick={handleCopyInvoice}
className="w-full"
size="lg"
>
<Copy className="h-4 w-4 mr-2" />
Copy Invoice
</Button>
{showCopiedTooltip && (
<div className="absolute -top-10 left-1/2 transform -translate-x-1/2 bg-foreground text-background text-xs px-2 py-1 rounded shadow-lg z-10 animate-in fade-in-0 duration-200">
Copied!
<div className="absolute top-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent border-t-foreground"></div>
</div>
)}
</div>
</div>
</div>
);
}
export function CreditsDialog({ open, onOpenChange, providerId, connection }: CreditsDialogProps) {
const { user } = useCurrentUser();
const { toast } = useToast();
const queryClient = useQueryClient();
const [amount, setAmount] = useState<number>(10);
const [paymentMethod, setPaymentMethod] = useState<'stripe' | 'lightning'>('stripe');
const [lightningInvoice, setLightningInvoice] = useState<string | null>(null);
const [refreshingPayments, setRefreshingPayments] = useState<Set<string>>(new Set());
// Query for payment history
const { data: payments, isLoading: isLoadingPayments } = useQuery({
queryKey: ['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId],
queryFn: async (): Promise<Payment[]> => {
const ai = createAIClient(connection, user);
const data = await ai.get('/credits/payments?limit=50') as PaymentsResponse;
return data.data;
},
enabled: open && !!user,
retry: false,
refetchOnWindowFocus: false,
});
// Mutation for adding credits
const addCreditsMutation = useMutation({
mutationFn: async (request: AddCreditsRequest): Promise<Payment> => {
const ai = createAIClient(connection, user);
return await ai.post('/credits/add', {
body: request,
}) as Payment;
},
onSuccess: (payment) => {
if (payment.method === 'stripe') {
// Open Stripe checkout in new window
window.open(payment.url, '_blank');
toast({
title: 'Payment initiated',
description: 'Stripe checkout opened in a new window.',
});
} else if (payment.method === 'lightning') {
// Show Lightning payment interface
setLightningInvoice(payment.url);
}
// Refresh payments list
queryClient.invalidateQueries({
queryKey: ['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId],
});
// Refresh credits balance
queryClient.invalidateQueries({
queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId],
});
},
onError: (error: Error) => {
const errorMessage = error?.message || 'Failed to initiate payment';
toast({
title: 'Payment failed',
description: errorMessage,
variant: 'destructive',
});
},
});
// Mutation for checking payment status
const checkPaymentMutation = useMutation({
mutationFn: async (paymentId: string): Promise<Payment> => {
const ai = createAIClient(connection, user);
return await ai.get(`/credits/payments/${paymentId}`) as Payment;
},
onMutate: async (paymentId: string) => {
// Add this payment to the refreshing set
setRefreshingPayments(prev => new Set(prev).add(paymentId));
},
onSuccess: (updatedPayment) => {
// Remove from refreshing set
setRefreshingPayments(prev => {
const newSet = new Set(prev);
newSet.delete(updatedPayment.id);
return newSet;
});
// Update the specific payment in the cache instead of refetching
queryClient.setQueryData<Payment[]>(
['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId],
(oldPayments) => {
if (!oldPayments) return oldPayments;
return oldPayments.map(payment =>
payment.id === updatedPayment.id ? updatedPayment : payment
);
}
);
// If payment completed, refresh credits balance
if (updatedPayment.status === 'completed') {
queryClient.invalidateQueries({
queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId],
});
toast({
title: 'Payment completed!',
description: `${formatCurrency(updatedPayment.amount)} has been added to your account.`,
});
} else if (updatedPayment.status === 'failed') {
toast({
title: 'Payment failed',
description: 'The payment has failed. Please try again.',
variant: 'destructive',
});
} else if (updatedPayment.status === 'expired') {
toast({
title: 'Payment expired',
description: 'The payment has expired. Please create a new payment.',
variant: 'destructive',
});
}
},
onError: (error: Error, paymentId: string) => {
// Remove from refreshing set on error
setRefreshingPayments(prev => {
const newSet = new Set(prev);
newSet.delete(paymentId);
return newSet;
});
const errorMessage = error?.message || 'Failed to check payment status';
toast({
title: 'Refresh failed',
description: errorMessage,
variant: 'destructive',
});
},
});
const handleAddCredits = () => {
if (!user) {
toast({
title: 'Authentication required',
description: 'Please log in to purchase credits.',
variant: 'destructive',
});
return;
}
if (amount <= 0) {
toast({
title: 'Invalid amount',
description: 'Please enter a valid amount.',
variant: 'destructive',
});
return;
}
const request: AddCreditsRequest = {
amount,
method: paymentMethod,
};
if (paymentMethod === 'stripe') {
request.redirect_url = window.location.origin + '/settings/ai';
}
addCreditsMutation.mutate(request);
};
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(amount);
};
const formatDate = (timestamp: number) => {
const date = new Date(timestamp * 1000);
const now = new Date();
const diffDays = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60 * 24));
if (diffDays === 0) {
return new Intl.DateTimeFormat('en-US', {
hour: '2-digit',
minute: '2-digit',
}).format(date);
} else if (diffDays === 1) {
return 'Yesterday';
} else if (diffDays < 7) {
return new Intl.DateTimeFormat('en-US', {
weekday: 'short',
}).format(date);
} else {
return new Intl.DateTimeFormat('en-US', {
month: 'short',
day: 'numeric',
}).format(date);
}
};
const getStatusIcon = (status: Payment['status']) => {
switch (status) {
case 'completed':
return <Check className="h-4 w-4 text-green-600" />;
case 'failed':
return <X className="h-4 w-4 text-red-600" />;
case 'expired':
return <AlertCircle className="h-4 w-4 text-orange-600" />;
case 'pending':
default:
return <Clock className="h-4 w-4 text-yellow-600" />;
}
};
const getStatusVariant = (status: Payment['status']): "default" | "secondary" | "destructive" | "outline" => {
switch (status) {
case 'completed':
return 'default';
case 'failed':
return 'destructive';
case 'expired':
return 'secondary';
case 'pending':
default:
return 'outline';
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-full max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none">
<DialogHeader className="flex-shrink-0">
<DialogTitle className="flex items-center gap-2 text-lg">
{lightningInvoice ? (
<>
<button
onClick={() => setLightningInvoice(null)}
className="flex items-center gap-2 hover:opacity-70 transition-opacity"
>
<ArrowLeft className="h-5 w-5" />
Back
</button>
</>
) : (
<>
<CreditCard className="h-5 w-5" />
Credits
</>
)}
</DialogTitle>
</DialogHeader>
{/* Lightning Payment Interface */}
{lightningInvoice ? (
<div className="flex-1 overflow-y-auto px-1 -mx-1">
<LightningPayment
invoice={lightningInvoice}
amount={amount}
onClose={() => setLightningInvoice(null)}
/>
</div>
) : (
<div className="flex-1 flex flex-col min-h-0">
{/* Add Credits Form - Fixed size section */}
<div className="flex-shrink-0 space-y-4 px-1 -mx-1">
<div className="space-y-3">
<Label htmlFor="amount" className="text-sm font-medium">Amount (USD)</Label>
<div className="space-y-3">
<Input
id="amount"
type="number"
step="0.01"
value={amount}
onChange={(e) => setAmount(Number(e.target.value))}
placeholder="Enter amount"
className="text-center text-lg font-medium"
/>
<div className="grid grid-cols-5 gap-2">
{PRESET_AMOUNTS.map((preset) => (
<Button
key={preset}
variant={amount === preset ? "default" : "outline"}
size="sm"
onClick={() => setAmount(preset)}
className="text-xs"
>
${preset}
</Button>
))}
</div>
</div>
</div>
<div className="space-y-3">
<Label htmlFor="payment-method" className="text-sm font-medium">Payment Method</Label>
<Select value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="stripe">
<div className="flex items-center gap-2">
<CreditCard className="h-4 w-4" />
Credit Card
</div>
</SelectItem>
<SelectItem value="lightning">
<div className="flex items-center gap-2">
<Zap className="h-4 w-4" />
Lightning
</div>
</SelectItem>
</SelectContent>
</Select>
</div>
<Button
onClick={handleAddCredits}
disabled={!user || amount <= 0 || addCreditsMutation.isPending}
className="w-full h-12 text-base font-medium"
size="lg"
>
{addCreditsMutation.isPending && <RefreshCw className="h-4 w-4 mr-2 animate-spin" />}
{paymentMethod === 'stripe' ? 'Pay with Card' : 'Generate Invoice'}
{amount > 0 && ` - ${formatCurrency(amount)}`}
</Button>
{!user && (
<p className="text-sm text-muted-foreground text-center px-4">
Please log in to purchase credits
</p>
)}
</div>
<div className="flex-shrink-0 px-1 -mx-1 py-4">
<Separator />
</div>
{/* Transaction History - Flexible section */}
<div className="flex-1 min-h-0 flex flex-col px-1 -mx-1">
<div className="flex-shrink-0 mb-4">
<h3 className="text-base font-semibold">Recent Transactions</h3>
</div>
<div className="flex-1 min-h-0 overflow-y-auto">
{isLoadingPayments ? (
<div className="space-y-3">
{Array.from({ length: 3 }).map((_, i) => (
<div key={i} className="p-3 border rounded-lg space-y-2">
<div className="flex items-center gap-2">
<Skeleton className="h-4 w-4 rounded" />
<Skeleton className="h-4 w-24" />
<Skeleton className="h-4 w-16 ml-auto" />
</div>
<Skeleton className="h-3 w-32" />
</div>
))}
</div>
) : !payments || payments.length === 0 ? (
<div className="flex-1 flex items-center justify-center">
<div className="text-center text-muted-foreground">
<CreditCard className="h-10 w-10 mx-auto mb-3 opacity-50" />
<p className="text-sm">No transactions yet</p>
<p className="text-xs">Your payment history will appear here</p>
</div>
</div>
) : (
<div className="space-y-2 pb-2">
{payments.map((payment) => (
<div
key={payment.id}
className="p-3 border rounded-lg space-y-2 hover:bg-muted/30 transition-colors"
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 min-w-0 flex-1">
{getStatusIcon(payment.status)}
<span className="text-sm font-medium truncate">
{payment.method === 'stripe' ? 'Credit Card' : 'Lightning'}
</span>
<Badge variant={getStatusVariant(payment.status)} className="text-xs flex-shrink-0">
{payment.status}
</Badge>
</div>
<div className="text-right flex-shrink-0">
<p className="text-sm font-medium">{formatCurrency(payment.amount)}</p>
{payment.fee > 0 && (
<p className="text-xs text-muted-foreground">
+{formatCurrency(payment.fee)}
</p>
)}
</div>
</div>
<div className="flex items-center justify-between text-xs text-muted-foreground">
<span>{formatDate(payment.created_at)}</span>
{payment.status === 'pending' && (
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => checkPaymentMutation.mutate(payment.id)}
disabled={refreshingPayments.has(payment.id)}
className="h-6 px-2 text-xs"
title="Refresh payment status"
>
<RotateCcw className={`h-3 w-3 ${refreshingPayments.has(payment.id) ? 'animate-spin' : ''}`} />
</Button>
{payment.url && (
<Button
variant="ghost"
size="sm"
onClick={() => {
if (payment.method === 'lightning') {
setLightningInvoice(payment.url);
} else {
window.open(payment.url, '_blank');
}
}}
className="h-6 px-2 text-xs"
>
<ExternalLink className="h-3 w-3 mr-1" />
{payment.method === 'lightning' ? 'Pay' : 'Pay'}
</Button>
)}
</div>
)}
</div>
</div>
))}
</div>
)}
</div>
</div>
</div>
)}
</DialogContent>
</Dialog>
);
}
+52
View File
@@ -0,0 +1,52 @@
import { describe, it, expect } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { LanguagePicker } from './LanguagePicker';
describe('LanguagePicker', () => {
it('renders language picker with default English selection', () => {
render(
<TestApp>
<LanguagePicker />
</TestApp>
);
// Should show the trigger button
expect(screen.getByRole('combobox')).toBeInTheDocument();
});
it('shows language options when opened', async () => {
render(
<TestApp>
<LanguagePicker />
</TestApp>
);
// Click to open the dropdown
const trigger = screen.getByRole('combobox');
fireEvent.click(trigger);
// Should show all language options (using getAllByText since there might be duplicates)
expect(screen.getAllByText('System').length).toBeGreaterThan(0);
expect(screen.getAllByText('English').length).toBeGreaterThan(0);
expect(screen.getAllByText('Portuguese').length).toBeGreaterThan(0);
expect(screen.getAllByText('Chinese').length).toBeGreaterThan(0);
});
it('displays flag emojis for languages', async () => {
render(
<TestApp>
<LanguagePicker />
</TestApp>
);
// Click to open the dropdown
const trigger = screen.getByRole('combobox');
fireEvent.click(trigger);
// Should show flag emojis (using getAllByText since there might be duplicates)
expect(screen.getAllByText('🇺🇸').length).toBeGreaterThan(0);
expect(screen.getAllByText('🇧🇷').length).toBeGreaterThan(0);
expect(screen.getAllByText('🇨🇳').length).toBeGreaterThan(0);
});
});
+53
View File
@@ -0,0 +1,53 @@
import { useTranslation } from 'react-i18next';
import { Languages } from 'lucide-react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useAppContext } from '@/hooks/useAppContext';
interface LanguagePickerProps {
className?: string;
}
export function LanguagePicker({ className }: LanguagePickerProps) {
const { t } = useTranslation();
const { config, updateConfig } = useAppContext();
const handleLanguageChange = (language: string) => {
updateConfig((prev) => ({ ...prev, language: language === 'system' ? undefined : language }));
};
return (
<Select value={config.language ?? 'system'} onValueChange={handleLanguageChange}>
<SelectTrigger className={className}>
<div className="flex items-center gap-2">
<SelectValue />
</div>
</SelectTrigger>
<SelectContent>
<SelectItem value="system">
<div className="flex items-center gap-2">
<Languages className="h-4 w-4" />
{t('systemLanguage')}
</div>
</SelectItem>
<SelectItem value="en">
<div className="flex items-center gap-2">
<span className="text-lg">🇺🇸</span>
{t('english')}
</div>
</SelectItem>
<SelectItem value="pt">
<div className="flex items-center gap-2">
<span className="text-lg">🇧🇷</span>
{t('portuguese')}
</div>
</SelectItem>
<SelectItem value="zh">
<div className="flex items-center gap-2">
<span className="text-lg">🇨🇳</span>
{t('chinese')}
</div>
</SelectItem>
</SelectContent>
</Select>
);
}
+89
View File
@@ -0,0 +1,89 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
// Mock QRCode
vi.mock('qrcode', () => ({
default: {
toDataURL: vi.fn().mockResolvedValue('data:image/png;base64,mock-qr-code'),
},
}));
// Mock WebLN
const mockWebLN = {
enable: vi.fn().mockResolvedValue(undefined),
sendPayment: vi.fn().mockResolvedValue({ preimage: 'mock-preimage' }),
};
// We need to import the component after mocking
const { CreditsDialog } = await import('./CreditsDialog');
const mockConnection = {
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
};
describe('Lightning Payment', () => {
beforeEach(() => {
vi.clearAllMocks();
// Reset WebLN mock
Object.defineProperty(window, 'webln', {
value: undefined,
writable: true,
});
});
it('shows QR code for Lightning payment', async () => {
render(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
// Should show the normal form initially
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
});
it('shows WebLN button when available', async () => {
// Mock WebLN availability
Object.defineProperty(window, 'webln', {
value: mockWebLN,
writable: true,
});
render(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
// Should show the normal form initially
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
});
it('displays copy invoice button', async () => {
render(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
// Should show the normal form initially
expect(screen.getByText('Payment Method')).toBeInTheDocument();
});
});
+15 -11
View File
@@ -1,5 +1,6 @@
import { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -23,8 +24,9 @@ export function ModelSelector({
onChange,
className,
disabled = false,
placeholder = "Select or enter a model...",
placeholder,
}: ModelSelectorProps) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const [isCustomInput, setIsCustomInput] = useState(false);
const [customValue, setCustomValue] = useState('');
@@ -32,6 +34,8 @@ export function ModelSelector({
const { models, isLoading, error, refetch } = useProviderModels();
const navigate = useNavigate();
const defaultPlaceholder = t('selectOrEnterModel');
const recentlyUsedModels = useMemo(() => settings.recentlyUsedModels || [], [settings.recentlyUsedModels]);
// Group models by provider
@@ -125,14 +129,14 @@ export function ModelSelector({
disabled={disabled}
>
<span className="w-full truncate">
{value || placeholder}
{value || placeholder || defaultPlaceholder}
</span>
<ChevronDown className="size-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-96 p-0" align="end">
<Command>
{isConfigured && <CommandInput placeholder="Search models..." className="h-9" />}
{isConfigured && <CommandInput placeholder={t('searchModels')} className="h-9" />}
<CommandList className="max-h-[300px]">
{/* Custom model option and manage providers */}
<CommandGroup>
@@ -143,7 +147,7 @@ export function ModelSelector({
className="cursor-pointer"
>
<Edit3 className="mr-2 h-4 w-4" />
Enter custom model...
{t('enterCustomModel')}
</CommandItem>
)}
<CommandItem
@@ -152,7 +156,7 @@ export function ModelSelector({
className="cursor-pointer"
>
<Settings className="mr-2 h-4 w-4" />
Manage providers...
{t('manageProviders')}
</CommandItem>
</CommandGroup>
@@ -160,13 +164,13 @@ export function ModelSelector({
<CommandEmpty>
<div className="py-6 text-center text-sm text-muted-foreground">
<p>No models found.</p>
<p className="mt-2 text-xs">Try using a custom model instead.</p>
<p>{t('noModelsFound')}</p>
<p className="mt-2 text-xs">{t('tryCustomModel')}</p>
</div>
</CommandEmpty>
{recentlyUsedModels.length > 0 && (
<CommandGroup heading="Recently Used">
<CommandGroup heading={t('recentlyUsed')}>
{recentlyUsedModels.map((model) => (
<CommandItem
key={model}
@@ -190,7 +194,7 @@ export function ModelSelector({
{/* Loading state */}
{isLoading && (
<CommandGroup heading="Loading Models...">
<CommandGroup heading={t('loading')}>
<div className="px-2 py-1.5">
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
@@ -203,7 +207,7 @@ export function ModelSelector({
{/* Error state */}
{error && !isLoading && (
<CommandGroup heading="Error Loading Models">
<CommandGroup heading={t('errorLoadingModels')}>
<div className="px-2 py-1.5 text-sm text-muted-foreground">
<div className="flex items-start gap-2">
<AlertCircle className="h-4 w-4 text-destructive flex-shrink-0 mt-0.5" />
@@ -216,7 +220,7 @@ export function ModelSelector({
className="h-7 text-xs"
>
<RefreshCw className="h-3 w-3 mr-1" />
Retry
{t('retry')}
</Button>
</div>
</div>
+145
View File
@@ -0,0 +1,145 @@
import { render, screen, fireEvent } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { ProjectSidebar } from './ProjectSidebar';
import { useProjects } from '@/hooks/useProjects';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { TestApp } from '@/test/TestApp';
// Mock the hooks
vi.mock('@/hooks/useProjects');
vi.mock('@/hooks/useLocalStorage');
vi.mock('@/hooks/useProjectSessionStatus', () => ({
useProjectSessionStatus: () => ({ hasRunningSessions: false })
}));
vi.mock('react-router-dom', async (importOriginal) => {
const actual = await importOriginal() as Record<string, unknown>;
return {
...actual,
useNavigate: () => vi.fn()
};
});
vi.mock('@tanstack/react-query', async (importOriginal) => {
const actual = await importOriginal() as Record<string, unknown>;
return {
...actual,
useQueryClient: () => ({
invalidateQueries: vi.fn(),
resetQueries: vi.fn()
})
};
});
// Mock window.open for help button test
const mockWindowOpen = vi.fn();
Object.defineProperty(window, 'open', {
value: mockWindowOpen,
writable: true
});
const mockUseProjects = vi.mocked(useProjects);
const mockUseLocalStorage = vi.mocked(useLocalStorage);
describe('ProjectSidebar', () => {
beforeEach(() => {
mockUseProjects.mockReturnValue({
data: [],
isLoading: false,
error: null
} as unknown as ReturnType<typeof useProjects>);
mockUseLocalStorage.mockReturnValue([[], vi.fn()]);
});
it('renders sidebar header with logo', () => {
render(
<TestApp>
<ProjectSidebar
selectedProject={null}
onSelectProject={vi.fn()}
/>
</TestApp>
);
expect(screen.getByText('🎭')).toBeInTheDocument();
expect(screen.getByText('Shakespeare')).toBeInTheDocument();
});
it('shows collapse button when onToggleSidebar is provided', () => {
const mockToggle = vi.fn();
render(
<TestApp>
<ProjectSidebar
selectedProject={null}
onSelectProject={vi.fn()}
onToggleSidebar={mockToggle}
/>
</TestApp>
);
const collapseButton = screen.getByLabelText('Collapse sidebar');
expect(collapseButton).toBeInTheDocument();
fireEvent.click(collapseButton);
expect(mockToggle).toHaveBeenCalledTimes(1);
});
it('does not show collapse button when onToggleSidebar is not provided', () => {
render(
<TestApp>
<ProjectSidebar
selectedProject={null}
onSelectProject={vi.fn()}
/>
</TestApp>
);
expect(screen.queryByLabelText('Collapse sidebar')).not.toBeInTheDocument();
});
it('renders settings and help buttons at the bottom', () => {
render(
<TestApp>
<ProjectSidebar
selectedProject={null}
onSelectProject={vi.fn()}
/>
</TestApp>
);
expect(screen.getByText('Settings')).toBeInTheDocument();
expect(screen.getByLabelText('Help')).toBeInTheDocument();
});
it('shows new project button', () => {
render(
<TestApp>
<ProjectSidebar
selectedProject={null}
onSelectProject={vi.fn()}
/>
</TestApp>
);
expect(screen.getByText('New Project')).toBeInTheDocument();
});
it('opens help documentation when help button is clicked', () => {
render(
<TestApp>
<ProjectSidebar
selectedProject={null}
onSelectProject={vi.fn()}
/>
</TestApp>
);
const helpButton = screen.getByLabelText('Help');
fireEvent.click(helpButton);
expect(mockWindowOpen).toHaveBeenCalledWith(
'https://soapbox.pub/shakespeare-resources/',
'_blank'
);
});
});
+72 -23
View File
@@ -1,13 +1,14 @@
import React, { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Plus, Folder, GitBranch, Settings, Loader2, ChevronDown, Star } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { LoginArea } from '@/components/auth/LoginArea';
import { useProjects } from '@/hooks/useProjects';
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { Project } from '@/lib/ProjectsManager';
import { cn } from '@/lib/utils';
import { useQueryClient } from '@tanstack/react-query';
@@ -76,22 +77,44 @@ interface ProjectSidebarProps {
selectedProject: Project | null;
onSelectProject: (project: Project | null) => void;
className?: string;
onToggleSidebar?: () => void;
onClose?: () => void;
}
export function ProjectSidebar({
selectedProject,
onSelectProject,
className
className,
onToggleSidebar,
onClose
}: ProjectSidebarProps) {
const { t } = useTranslation();
const queryClient = useQueryClient();
const { data: projects = [], isLoading, error } = useProjects();
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
const isMobile = useIsMobile();
const navigate = useNavigate();
// Custom navigate function that closes sidebar on mobile
const navigateAndClose = (path: string) => {
navigate(path);
if (isMobile && onClose) {
onClose();
}
};
const handleNewProject = () => {
onSelectProject(null);
navigate('/');
navigateAndClose('/');
};
const handleToggleSidebar = () => {
if (onToggleSidebar) {
onToggleSidebar();
} else if (onClose && isMobile) {
onClose();
}
};
useEffect(() => {
@@ -108,7 +131,7 @@ export function ProjectSidebar({
<div className="flex px-4 h-12 border-b border-sidebar-border bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10">
<div className="flex items-center justify-between w-full">
<button
onClick={() => navigate('/')}
onClick={() => navigateAndClose('/')}
className="flex items-center gap-3 hover:opacity-80 transition-opacity text-left"
>
<span className="text-2xl">🎭</span>
@@ -116,16 +139,23 @@ export function ProjectSidebar({
Shakespeare
</h1>
</button>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
onClick={() => navigate('/settings')}
>
<Settings className="h-4 w-4 text-primary/60 hover:text-primary" />
</Button>
</div>
{(onToggleSidebar || (onClose && isMobile)) && (
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
onClick={handleToggleSidebar}
aria-label={(onClose && isMobile) ? t('closeSidebar') : t('collapseSidebar')}
>
{(onClose && isMobile) ? (
<X className="h-4 w-4 text-primary/60 hover:text-primary" />
) : (
<Columns2 className="h-4 w-4 text-primary/60 hover:text-primary" />
)}
</Button>
</div>
)}
</div>
</div>
@@ -139,7 +169,7 @@ export function ProjectSidebar({
className="flex-1 flex items-center justify-center px-3 py-2 text-sm font-medium text-primary-foreground rounded-l-md hover:bg-white/10 transition-colors"
>
<Plus className="h-4 w-4 mr-2" />
New Project
{t('newProject')}
</button>
<div className="w-px bg-white/20" />
<DropdownMenu>
@@ -150,11 +180,11 @@ export function ProjectSidebar({
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem
onClick={() => navigate('/clone')}
onClick={() => navigateAndClose('/clone')}
className="flex items-center gap-2 w-full"
>
<GitBranch className="h-4 w-4" />
Import Repository
{t('importRepository')}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -176,8 +206,8 @@ export function ProjectSidebar({
) : projects.length === 0 ? (
<div className="text-center p-6 text-muted-foreground">
<Folder className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">No projects yet</p>
<p className="text-xs">Create your first project to get started</p>
<p className="text-sm">{t('noProjectsYet')}</p>
<p className="text-xs">{t('createFirstProject')}</p>
</div>
) : (
<div className="space-y-1">
@@ -195,9 +225,28 @@ export function ProjectSidebar({
</div>
</div>
{/* Account Selector at Bottom */}
<div className="p-4 border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto">
<LoginArea className="w-full" />
{/* Settings and Help at Bottom */}
<div className="p-2 border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto">
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="sm"
className="flex-1 h-9 justify-start gap-2 text-sidebar-foreground dark:hover:text-sidebar-primary hover:bg-primary/10 dark:hover:bg-sidebar-accent/30 transition-all duration-200"
onClick={() => navigateAndClose('/settings')}
>
<Settings className="h-4 w-4 transition-colors duration-200" />
{t('settings')}
</Button>
<Button
variant="ghost"
size="sm"
className="h-9 w-9 p-0 text-sidebar-foreground dark:hover:text-sidebar-primary hover:bg-primary/10 dark:hover:bg-sidebar-accent/30 transition-all duration-200"
onClick={() => window.open('https://soapbox.pub/shakespeare-resources/', '_blank')}
aria-label={t('help')}
>
<HelpCircle className="h-4 w-4 transition-colors duration-200" />
</Button>
</div>
</div>
</div>
);
+55 -26
View File
@@ -1,8 +1,9 @@
import { useState, useEffect } from 'react';
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Menu, Columns2, Bot, GitBranch, Database } from 'lucide-react';
import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react';
import { ProjectSidebar } from '@/components/ProjectSidebar';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useIsMobile } from '@/hooks/useIsMobile';
@@ -18,31 +19,54 @@ interface SettingsItem {
href: string;
}
const settingsItems: SettingsItem[] = [
// Define settings items as a function to get fresh translations
const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [
{
id: 'preferences',
title: t('preferences'),
description: t('preferencesDescription'),
icon: Settings2,
href: '/settings/preferences',
},
{
id: 'ai',
title: 'AI Settings',
description: 'Configure AI providers and API keys',
title: t('aiSettings'),
description: t('aiSettingsDescription'),
icon: Bot,
href: '/settings/ai',
},
{
id: 'git',
title: 'Git Settings',
description: 'Configure Git credentials for HTTP authentication',
title: t('gitSettings'),
description: t('gitSettingsDescription'),
icon: GitBranch,
href: '/settings/git',
},
{
id: 'nostr',
title: t('nostrSettings'),
description: t('nostrSettingsDescription'),
icon: Wifi,
href: '/settings/nostr',
},
{
id: 'data',
title: 'Data',
description: 'Export files and manage local data',
title: t('dataSettings'),
description: t('dataSettingsDescription'),
icon: Database,
href: '/settings/data',
},
{
id: 'about',
title: t('aboutShakespeare'),
description: t('aboutShakespeareDescription'),
icon: Info,
href: '/settings/about',
},
];
export function SettingsLayout() {
const { t } = useTranslation();
const navigate = useNavigate();
const location = useLocation();
const isMobile = useIsMobile();
@@ -61,7 +85,7 @@ export function SettingsLayout() {
// Set initial sidebar state based on projects and device type
if (!hasSetInitialState && !isMobile) {
// On desktop, show sidebar if there are projects
setIsSidebarVisible(projectList.length > 0);
setIsSidebarVisible(true);
setHasSetInitialState(true);
} else if (!hasSetInitialState && isMobile) {
// On mobile, always start hidden
@@ -90,24 +114,25 @@ export function SettingsLayout() {
};
// Get current settings page
const settingsItems = getSettingsItems(t);
const currentPath = location.pathname;
const currentSettingsId = settingsItems.find(item => item.href === currentPath)?.id;
if (isMobile) {
return (
<div className="min-h-dvh bg-white">
<div className="min-h-dvh bg-background">
{/* Mobile Header */}
<header className="h-12 border-b bg-white px-4 py-3 flex items-center justify-between">
<header className="h-12 border-b bg-background px-4 py-3 flex items-center justify-between">
<div className="flex items-center space-x-2">
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
aria-label="Toggle sidebar"
aria-label={t('toggleSidebar')}
>
<Menu className="h-4 w-4" />
</Button>
<h1 className="text-lg font-semibold">Settings</h1>
<h1 className="text-lg font-semibold">{t('settings')}</h1>
</div>
</header>
@@ -125,6 +150,7 @@ export function SettingsLayout() {
setIsSidebarVisible(false);
handleProjectSelect(project);
}}
onClose={() => setIsSidebarVisible(false)}
/>
</div>
</div>
@@ -137,7 +163,7 @@ export function SettingsLayout() {
// Desktop 3-column layout
return (
<div className="h-screen flex bg-white overflow-hidden">
<div className="h-screen flex bg-background overflow-hidden">
{/* Left Column - Projects Sidebar (optionally hidden) */}
{isSidebarVisible && (
<div className="w-80 border-r bg-sidebar flex-shrink-0">
@@ -145,26 +171,29 @@ export function SettingsLayout() {
selectedProject={null}
onSelectProject={handleProjectSelect}
className="h-full"
onToggleSidebar={() => setIsSidebarVisible(false)}
/>
</div>
)}
{/* Middle Column - Settings Navigation */}
<div className="w-96 border-r bg-white flex flex-col flex-shrink-0">
<div className="w-96 border-r bg-background flex flex-col flex-shrink-0">
{/* Header with toggle button */}
<div className="h-12 px-4 py-2 border-b flex-shrink-0">
<div className="flex items-center gap-3">
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
className="h-8 w-8 p-0"
aria-label="Toggle sidebar"
>
{isSidebarVisible ? <Columns2 className="h-4 w-4" /> : <Menu className="h-4 w-4" />}
</Button>
{!isSidebarVisible && (
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(true)}
className="h-8 w-8 p-0"
aria-label={t('openSidebar')}
>
<Menu className="h-4 w-4" />
</Button>
)}
<h1 className="text-xl font-bold flex items-center gap-2">
Settings
{t('settings')}
</h1>
</div>
</div>
@@ -206,7 +235,7 @@ export function SettingsLayout() {
</div>
{/* Right Column - Settings Content - Scrollable */}
<ScrollArea className="flex-1 bg-white">
<ScrollArea className="flex-1 bg-background">
<div className="max-w-4xl">
<Outlet />
</div>
+22 -27
View File
@@ -1,5 +1,6 @@
import { useState, useRef, useEffect, forwardRef, useImperativeHandle, useMemo, useCallback } from 'react';
import { useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Skeleton } from '@/components/ui/skeleton';
@@ -67,6 +68,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
isBuildLoading: externalIsBuildLoading,
isDeployLoading: externalIsDeployLoading
}, ref) => {
const { t } = useTranslation();
const [input, setInput] = useState('');
const [systemPrompt, setSystemPrompt] = useState('');
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
@@ -295,18 +297,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
}, [projectId, scrolledProjects]);
// Also scroll on initial mount if we have a projectId
useEffect(() => {
if (projectId && !scrolledProjects.has(projectId)) {
const timer = setTimeout(() => {
scrollToBottom();
scrolledProjects.add(projectId);
}, 100);
return () => clearTimeout(timer);
}
}, []); // Empty dependency array = runs on mount
const handleFileSelect = (file: File) => {
setAttachedFiles(prev => [...prev, file]);
};
@@ -429,12 +419,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<div className="text-center space-y-4 max-w-md mx-auto p-6">
<div className="text-4xl mb-4">🤖</div>
<div>
<h3 className="text-lg font-semibold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">AI Assistant Not Configured</h3>
<h3 className="text-lg font-semibold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">{t('aiNotConfigured')}</h3>
<p className="text-sm text-muted-foreground mb-4">
Please configure your AI settings to start building with AI assistance.
{t('configureAI')}
</p>
<p className="text-sm text-muted-foreground">
Use the menu in the top bar to access AI Settings.
{t('useMenuForAI')}
</p>
</div>
</div>
@@ -457,16 +447,16 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<div className="text-6xl mb-6">🎭</div>
<div>
<h3 className="text-xl font-semibold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Welcome to Shakespeare
{t('welcomeToShakespeare')}
</h3>
<p className="text-muted-foreground mb-6 leading-relaxed">
Your AI-powered development assistant is ready to help you build, edit, and enhance your project.
{t('aiAssistantReady')}
</p>
<div className="space-y-2 text-sm text-muted-foreground">
<p>💡 Ask me to add new features</p>
<p>📝 Request file edits and improvements</p>
<p>🔧 Get help with debugging and optimization</p>
<p>🚀 Build and deploy your project</p>
<p>{t('askMeFeatures')}</p>
<p>{t('requestEdits')}</p>
<p>{t('getHelp')}</p>
<p>{t('buildDeploy')}</p>
</div>
</div>
</div>
@@ -501,11 +491,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
);
})}
{streamingMessage && (
streamingMessage.content ? (
streamingMessage.content || streamingMessage.reasoning_content ? (
<AIMessageItem
key="streaming-message"
message={streamingMessage}
isCurrentlyLoading={isLoading}
reasoningContent={streamingMessage.reasoning_content}
/>
) : (
!(streamingMessage?.tool_calls?.[0]?.type === 'function') && (
@@ -524,7 +515,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<div className="flex items-center gap-2 px-2 py-1 text-xs text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin flex-shrink-0" />
<span className="font-medium">
Running {streamingMessage.tool_calls?.[0]?.function?.name || 'tool'}...
{t('running')} {streamingMessage.tool_calls?.[0]?.function?.name || 'tool'}...
</span>
</div>
</div>
@@ -555,7 +546,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onFocus={handleFirstInteraction}
placeholder={providerModel.trim() ? "Ask me to add features, edit files, or build your project..." : "Please select a model to start chatting..."}
placeholder={providerModel.trim() ? t('askToAddFeatures') : t('selectModelFirst')}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isLoading || !providerModel.trim()}
rows={1}
@@ -595,7 +586,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</div>
</TooltipTrigger>
<TooltipContent>
<p>Context usage: {lastInputTokens.toLocaleString()} / {currentModel.contextLength.toLocaleString()} tokens ({contextUsagePercentage.toFixed(1)}%)</p>
<p>{t('contextUsage', {
tokens: lastInputTokens.toLocaleString(),
total: currentModel.contextLength.toLocaleString(),
percentage: contextUsagePercentage.toFixed(1)
})}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
@@ -611,7 +606,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</div>
</TooltipTrigger>
<TooltipContent>
<p>Total cost for this chat session</p>
<p>{t('totalCostSession')}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
@@ -624,7 +619,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
onChange={setProviderModel}
className="w-full"
disabled={isLoading}
placeholder="Choose a model..."
placeholder={t('chooseModel')}
/>
</div>
+6 -4
View File
@@ -1,4 +1,5 @@
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { CardContent, CardHeader, CardTitle } from '@/components/ui/card';
@@ -15,6 +16,7 @@ interface FileEditorProps {
}
export function FileEditor({ filePath, content, onSave, isLoading, projectId }: FileEditorProps) {
const { t } = useTranslation();
const [editedContent, setEditedContent] = useState(content);
const [isSaving, setIsSaving] = useState(false);
const [hasChanges, setHasChanges] = useState(false);
@@ -99,7 +101,7 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
<CardTitle className={cn("text-sm sm:text-base truncate flex-1 mr-2", gitStatusClasses)}>{filePath}</CardTitle>
<div className="flex items-center space-x-1 sm:space-x-2">
{hasChanges && (
<span className="text-xs sm:text-sm text-muted-foreground hidden sm:inline">Unsaved changes</span>
<span className="text-xs sm:text-sm text-muted-foreground hidden sm:inline">{t('unsavedChanges')}</span>
)}
<Button
onClick={handleSave}
@@ -110,19 +112,19 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
{isSaving ? (
<>
<Loader2 className="mr-1 sm:mr-2 h-4 w-4 animate-spin" />
<span className="hidden sm:inline">Saving...</span>
<span className="hidden sm:inline">{t('saving')}</span>
</>
) : (
<>
<Save className="sm:mr-2 h-4 w-4" />
<span className="hidden sm:inline">Save</span>
<span className="hidden sm:inline">{t('save')}</span>
</>
)}
</Button>
</div>
</div>
<div className="text-xs text-muted-foreground mt-1">
Language: {getLanguageFromPath(filePath)}
{t('languageLabel')}: {getLanguageFromPath(filePath)}
</div>
</CardHeader>
+5 -3
View File
@@ -1,4 +1,5 @@
import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useFS } from '@/hooks/useFS';
import { useGitStatus } from '@/hooks/useGitStatus';
@@ -22,6 +23,7 @@ interface FileNode {
}
export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProps) {
const { t } = useTranslation();
const [tree, setTree] = useState<FileNode[]>([]);
const [filteredTree, setFilteredTree] = useState<FileNode[]>([]);
const [isLoading, setIsLoading] = useState(true);
@@ -179,7 +181,7 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
for (const node of nodes) {
if (node.type === 'file') {
const fileNameMatch = node.name.toLowerCase().includes(searchTermLower);
if (fileNameMatch) {
results.push(node);
}
@@ -296,7 +298,7 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
<div className="relative">
<Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search files..."
placeholder={t('searchFiles')}
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-8"
@@ -313,7 +315,7 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
</div>
) : filteredTree.length === 0 ? (
<div className="text-center text-sm text-muted-foreground py-4">
{searchTerm ? 'No files found matching your search' : 'No files found'}
{searchTerm ? t('noFilesFoundSearch') : t('noFilesFound')}
</div>
) : (
filteredTree.map(node => renderNode(node))
+175 -28
View File
@@ -1,18 +1,27 @@
import { encodeBase64 } from '@std/encoding/base64';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useFS } from '@/hooks/useFS';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { FolderOpen, ArrowLeft } from 'lucide-react';
import { FolderOpen, ArrowLeft, X, Bug, Copy, Check } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { FileTree } from './FileTree';
import { FileEditor } from './FileEditor';
// Get iframe domain from environment variable
const IFRAME_DOMAIN = import.meta.env.VITE_IFRAME_DOMAIN || 'local-shakespeare.dev';
interface PreviewPaneProps {
projectId: string;
activeTab: 'preview' | 'code';
@@ -39,7 +48,7 @@ interface JSONRPCResponse {
statusText: string;
headers: Record<string, string>;
body: string | null;
};
}
error?: {
code: number;
message: string;
@@ -48,7 +57,14 @@ interface JSONRPCResponse {
id: number;
}
interface ConsoleMessage {
id: number;
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
message: string;
}
export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
const { t } = useTranslation();
const [selectedFile, setSelectedFile] = useState<string | null>(null);
const [fileContent, setFileContent] = useState<string>('');
const [isLoading, setIsLoading] = useState(false);
@@ -58,6 +74,8 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
const [currentPath, setCurrentPath] = useState('/');
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
const [historyIndex, setHistoryIndex] = useState(0);
const [consoleMessages, setConsoleMessages] = useState<ConsoleMessage[]>([]);
const [copiedMessageId, setCopiedMessageId] = useState<number | null>(null);
const iframeRef = useRef<HTMLIFrameElement>(null);
const { fs } = useFS();
const projectsManager = useProjectsManager();
@@ -127,7 +145,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
const navigateToPath = useCallback((path: string) => {
if (iframeRef.current) {
const baseUrl = `https://${projectId}.local-shakespeare.dev`;
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
const newUrl = `${baseUrl}${path}`;
iframeRef.current.src = newUrl;
setCurrentPath(path);
@@ -148,7 +166,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
setCurrentPath(path);
if (iframeRef.current) {
const baseUrl = `https://${projectId}.local-shakespeare.dev`;
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
const newUrl = `${baseUrl}${path}`;
iframeRef.current.src = newUrl;
}
@@ -163,7 +181,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
setCurrentPath(path);
if (iframeRef.current) {
const baseUrl = `https://${projectId}.local-shakespeare.dev`;
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
const newUrl = `${baseUrl}${path}`;
iframeRef.current.src = newUrl;
}
@@ -173,18 +191,46 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
const sendResponse = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
console.log(`Sending response to iframe:`, message);
const targetOrigin = `https://${projectId}.local-shakespeare.dev`;
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
}
}, [projectId]);
const sendError = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
const targetOrigin = `https://${projectId}.local-shakespeare.dev`;
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
}
}, [projectId]);
const handleConsoleMessage = useCallback((message: {
jsonrpc: '2.0';
method: 'console';
params: {
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
message: string;
};
}) => {
const { params } = message;
// Normalize level to ensure it's one of our supported types
let normalizedLevel: ConsoleMessage['level'] = 'log';
if (['log', 'warn', 'error', 'info', 'debug'].includes(params.level)) {
normalizedLevel = params.level as ConsoleMessage['level'];
}
const newConsoleMessage: ConsoleMessage = {
id: Date.now(),
level: normalizedLevel,
message: params.message,
};
setConsoleMessages(prev => [...prev, newConsoleMessage]);
// Log to parent console for debugging with appropriate level
console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`);
}, []);
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
const { params, id } = request;
const { request: fetchRequest } = params;
@@ -194,7 +240,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
try {
// Parse the URL and validate origin
const url = new URL(fetchRequest.url);
const expectedOrigin = `https://${projectId}.local-shakespeare.dev`;
const expectedOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
if (url.origin !== expectedOrigin) {
console.log(`Invalid origin: ${url.origin}, expected: ${expectedOrigin}`);
@@ -290,7 +336,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
// Verify origin for security
const expectedOrigin = `https://${projectId}.local-shakespeare.dev`;
const expectedOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
if (event.origin !== expectedOrigin) {
console.log(`Ignoring message from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`);
return;
@@ -300,12 +346,14 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
console.log('Received message from iframe:', message);
if (message.jsonrpc === '2.0' && message.method === 'fetch') {
handleFetch(message);
} else if (message.jsonrpc === '2.0' && message.method === 'console') {
handleConsoleMessage(message);
}
};
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, [handleFetch, projectId]);
}, [handleFetch, handleConsoleMessage, projectId]);
useEffect(() => {
if (selectedFile) {
@@ -350,24 +398,123 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
}
};
const ConsoleDropdown = () => {
const getLevelColor = (level: ConsoleMessage['level']) => {
switch (level) {
case 'error': return 'text-red-500';
case 'warn': return 'text-yellow-500';
case 'info': return 'text-blue-500';
case 'debug': return 'text-gray-500';
default: return 'text-gray-400';
}
};
const getLevelIcon = (level: ConsoleMessage['level']) => {
switch (level) {
case 'error': return '!';
case 'warn': return '⚠';
case 'info': return 'ℹ';
case 'debug': return '🔍';
default: return '•';
}
};
const clearConsole = () => {
setConsoleMessages([]);
};
const copyMessageToClipboard = async (msg: ConsoleMessage) => {
try {
// Create a formatted string with all message details
const formattedMessage = `[${msg.level.toUpperCase()}] ${msg.message}`;
await navigator.clipboard.writeText(formattedMessage);
setCopiedMessageId(msg.id);
// Reset the copied state after 2 seconds
setTimeout(() => {
setCopiedMessageId(null);
}, 2000);
} catch (error) {
console.error('Failed to copy message to clipboard:', error);
}
};
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm" className="h-8 w-8 p-0 relative">
<Bug className="h-4 w-4" />
{consoleMessages.some(msg => msg.level === 'error') && (
<span className="absolute bottom-0 left-0 h-2 w-2 bg-red-500 rounded-full"></span>
)}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-96 max-w-96 max-h-96 overflow-x-hidden">
<div className="flex items-center justify-between p-2 border-b">
<span className="font-medium text-sm">Console Output ({consoleMessages.length})</span>
<Button variant="ghost" size="sm" onClick={clearConsole}>
<X className="h-3 w-3" />
</Button>
</div>
<ScrollArea className="h-80 w-full max-w-full overflow-x-hidden">
<div className="space-y-1 p-2 w-full max-w-full overflow-x-hidden">
{consoleMessages.length === 0 ? (
<div className="text-center text-muted-foreground text-sm py-4">
No console messages
</div>
) : (
consoleMessages.map((msg) => (
<div
key={msg.id}
className={`text-xs font-mono p-2 rounded ${getLevelColor(msg.level)} bg-muted/50 group relative w-full overflow-hidden`}
>
<div className="flex items-start justify-between w-full">
<div className="whitespace-pre-wrap break-all flex-1 pr-2 overflow-x-hidden">{getLevelIcon(msg.level)} {msg.message}</div>
<Button
variant="ghost"
size="sm"
onClick={() => copyMessageToClipboard(msg)}
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex-shrink-0"
>
{copiedMessageId === msg.id ? (
<Check className="h-3 w-3 text-green-500" />
) : (
<Copy className="h-3 w-3" />
)}
</Button>
</div>
</div>
))
)}
</div>
</ScrollArea>
</DropdownMenuContent>
</DropdownMenu>
);
};
return (
<div className="h-full">
<Tabs value={activeTab} className="h-full">
<TabsContent value="preview" className="h-full mt-0">
{hasBuiltProject ? (
<div className="h-full w-full flex flex-col">
<BrowserAddressBar
currentPath={currentPath}
onNavigate={navigateToPath}
onRefresh={refreshIframe}
onBack={goBack}
onForward={goForward}
canGoBack={historyIndex > 0}
canGoForward={historyIndex < navigationHistory.length - 1}
/>
<div className="flex items-center border-b w-full">
<BrowserAddressBar
currentPath={currentPath}
onNavigate={navigateToPath}
onRefresh={refreshIframe}
onBack={goBack}
onForward={goForward}
canGoBack={historyIndex > 0}
canGoForward={historyIndex < navigationHistory.length - 1}
extraContent={<ConsoleDropdown />}
/>
</div>
<iframe
ref={iframeRef}
src={`https://${projectId}.local-shakespeare.dev${currentPath}`}
src={`https://${projectId}.${IFRAME_DOMAIN}${currentPath}`}
className="w-full flex-1 border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin"
@@ -376,9 +523,9 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
) : (
<div className="h-full flex items-center justify-center bg-muted">
<div className="text-center">
<h3 className="text-lg font-semibold mb-2">Project Preview</h3>
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
<p className="text-muted-foreground mb-4">
Build your project to see the preview here
{t('buildProjectToSeePreview')}
</p>
</div>
</div>
@@ -392,7 +539,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
<>
<div className="p-3 border-b bg-gradient-to-r from-primary/5 to-accent/5">
<div className="flex items-center justify-between">
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">File Explorer</h3>
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">{t('fileExplorer')}</h3>
<GitStatusIndicator projectId={projectId} />
</div>
</div>
@@ -419,7 +566,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
<ArrowLeft className="h-4 w-4" />
</Button>
<h3 className="font-semibold flex-1 truncate bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
{selectedFile ? selectedFile.split('/').pop() : 'File Editor'}
{selectedFile ? selectedFile.split('/').pop() : t('fileEditor')}
</h3>
<GitStatusIndicator projectId={projectId} />
</div>
@@ -437,7 +584,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
<div className="text-center">
<FolderOpen className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
<p className="text-muted-foreground">
Select a file from the explorer to edit
{t('selectFileFromExplorer')}
</p>
<Button
variant="outline"
@@ -445,7 +592,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
onClick={() => setMobileCodeView('explorer')}
className="mt-4"
>
Open File Explorer
{t('openFileExplorer')}
</Button>
</div>
</div>
@@ -459,7 +606,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
<div className="w-1/3 border-r">
<div className="p-4 border-b bg-gradient-to-r from-primary/5 to-accent/5">
<div className="flex items-center justify-between">
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">File Explorer</h3>
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">{t('fileExplorer')}</h3>
<GitStatusIndicator projectId={projectId} />
</div>
</div>
@@ -488,7 +635,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
<div className="h-full flex items-center justify-center">
<div className="text-center">
<p className="text-muted-foreground">
Select a file from the explorer to edit
{t('selectFileFromExplorer')}
</p>
</div>
</div>
+57
View File
@@ -0,0 +1,57 @@
import { ChevronsUpDown, Monitor, Moon, Sun } from "lucide-react";
import { useTranslation } from 'react-i18next';
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useTheme } from "@/hooks/useTheme";
import { type Theme } from "@/contexts/AppContext";
export function ThemePicker() {
const { t } = useTranslation();
const { theme, setTheme } = useTheme();
const themeOptions: { value: Theme; label: string; icon: React.ComponentType<{ className?: string }> }[] = [
{ value: "system", label: t('system'), icon: Monitor },
{ value: "light", label: t('light'), icon: Sun },
{ value: "dark", label: t('dark'), icon: Moon },
];
const currentTheme = themeOptions.find(option => option.value === theme);
const CurrentIcon = currentTheme?.icon || Monitor;
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="w-full justify-between">
<div className="flex items-center gap-2">
<CurrentIcon className="h-4 w-4" />
<span>{currentTheme?.label || t('system')}</span>
</div>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-[180px]">
{themeOptions.map((option) => {
const Icon = option.icon;
return (
<DropdownMenuItem
key={option.value}
onClick={() => setTheme(option.value)}
className="flex items-center gap-2"
>
<Icon className="h-4 w-4" />
<span>{option.label}</span>
{theme === option.value && (
<div className="ml-auto h-2 w-2 rounded-full bg-primary" />
)}
</DropdownMenuItem>
);
})}
</DropdownMenuContent>
</DropdownMenu>
);
}
@@ -0,0 +1,65 @@
import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import { AccountSwitcher } from './AccountSwitcher';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
// Mock the hooks
vi.mock('@/hooks/useLoggedInAccounts');
vi.mock('react-router-dom', () => ({
useNavigate: () => vi.fn()
}));
// Mock the RelaySelector component
vi.mock('@/components/RelaySelector', () => ({
RelaySelector: ({ className }: { className?: string }) => (
<div data-testid="relay-selector" className={className}>Relay Selector</div>
)
}));
const mockUseLoggedInAccounts = vi.mocked(useLoggedInAccounts);
describe('AccountSwitcher', () => {
it('renders account switcher with dropdown trigger', () => {
mockUseLoggedInAccounts.mockReturnValue({
authors: [{
id: 'user1',
pubkey: 'pubkey1',
metadata: { name: 'Test User' }
}],
currentUser: {
id: 'user1',
pubkey: 'pubkey1',
metadata: { name: 'Test User' }
},
otherUsers: [],
setLogin: vi.fn(),
removeLogin: vi.fn(),
isLoading: false
});
render(<AccountSwitcher onAddAccountClick={vi.fn()} />);
// Should show the user's name
expect(screen.getByText('Test User')).toBeInTheDocument();
// Should show dropdown trigger button
expect(screen.getByRole('button')).toBeInTheDocument();
});
it('returns null when no current user', () => {
mockUseLoggedInAccounts.mockReturnValue({
authors: [],
currentUser: undefined,
otherUsers: [],
setLogin: vi.fn(),
removeLogin: vi.fn(),
isLoading: false
});
const { container } = render(<AccountSwitcher onAddAccountClick={vi.fn()} />);
expect(container.firstChild).toBeNull();
});
});
+39 -23
View File
@@ -1,7 +1,7 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { ChevronDown, LogOut, UserIcon, UserPlus } from 'lucide-react';
import { ChevronDown, LogOut, UserIcon, UserPlus, Settings, HelpCircle } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
@@ -10,9 +10,9 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu.tsx';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
import { RelaySelector } from '@/components/RelaySelector';
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
import { genUserName } from '@/lib/genUserName';
import { useNavigate } from 'react-router-dom';
interface AccountSwitcherProps {
onAddAccountClick: () => void;
@@ -20,6 +20,7 @@ interface AccountSwitcherProps {
export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
const { currentUser, otherUsers, setLogin, removeLogin } = useLoggedInAccounts();
const navigate = useNavigate();
if (!currentUser) return null;
@@ -42,27 +43,42 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
</button>
</DropdownMenuTrigger>
<DropdownMenuContent className='w-56 p-2 animate-scale-in'>
<div className='font-medium text-sm px-2 py-1.5'>Switch Relay</div>
<RelaySelector className="w-full" />
<DropdownMenuSeparator />
<div className='font-medium text-sm px-2 py-1.5'>Switch Account</div>
{otherUsers.map((user) => (
<DropdownMenuItem
key={user.id}
onClick={() => setLogin(user.id)}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
>
<Avatar className='w-8 h-8'>
<AvatarImage src={user.metadata.picture} alt={getDisplayName(user)} />
<AvatarFallback>{getDisplayName(user)?.charAt(0) || <UserIcon />}</AvatarFallback>
</Avatar>
<div className='flex-1 truncate'>
<p className='text-sm font-medium'>{getDisplayName(user)}</p>
</div>
{user.id === currentUser.id && <div className='w-2 h-2 rounded-full bg-primary'></div>}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
{otherUsers.length > 0 && (
<>
<div className='font-medium text-sm px-2 py-1.5'>Switch Account</div>
{otherUsers.map((user) => (
<DropdownMenuItem
key={user.id}
onClick={() => setLogin(user.id)}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
>
<Avatar className='w-8 h-8'>
<AvatarImage src={user.metadata.picture} alt={getDisplayName(user)} />
<AvatarFallback>{getDisplayName(user)?.charAt(0) || <UserIcon />}</AvatarFallback>
</Avatar>
<div className='flex-1 truncate'>
<p className='text-sm font-medium'>{getDisplayName(user)}</p>
</div>
{user.id === currentUser.id && <div className='w-2 h-2 rounded-full bg-primary'></div>}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
</>
)}
<DropdownMenuItem
onClick={() => navigate('/settings')}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
>
<Settings className='w-4 h-4' />
<span>Settings</span>
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => window.open('https://soapbox.pub/shakespeare-resources/', '_blank')}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
>
<HelpCircle className='w-4 h-4' />
<span>Help</span>
</DropdownMenuItem>
<DropdownMenuItem
onClick={onAddAccountClick}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
+116
View File
@@ -0,0 +1,116 @@
import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import { LoginArea } from './LoginArea';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
// Mock the hooks
vi.mock('@/hooks/useLoggedInAccounts');
vi.mock('@/hooks/useAppContext', () => ({
useAppContext: () => ({
config: { relayUrl: 'wss://relay.damus.io' },
updateConfig: vi.fn(),
presetRelays: [
{ name: 'Damus', url: 'wss://relay.damus.io' }
]
})
}));
// Mock the components
vi.mock('./AccountSwitcher', () => ({
AccountSwitcher: ({ onAddAccountClick }: { onAddAccountClick: () => void }) => (
<div data-testid="account-switcher">
<button onClick={onAddAccountClick}>Add Account</button>
</div>
)
}));
// Mock react-router-dom
vi.mock('react-router-dom', () => ({
useNavigate: () => vi.fn()
}));
vi.mock('@/components/RelaySelector', () => ({
RelaySelector: ({ className }: { className?: string }) => (
<div data-testid="relay-selector" className={className}>Relay Selector</div>
)
}));
vi.mock('./LoginDialog', () => ({
default: ({ isOpen }: { isOpen: boolean; onClose: () => void }) =>
isOpen ? <div data-testid="login-dialog">Login Dialog</div> : null
}));
vi.mock('./SignupDialog', () => ({
default: ({ isOpen }: { isOpen: boolean; onClose: () => void }) =>
isOpen ? <div data-testid="signup-dialog">Signup Dialog</div> : null
}));
const mockUseLoggedInAccounts = vi.mocked(useLoggedInAccounts);
describe('LoginArea', () => {
it('shows AccountSwitcher when user is logged in', () => {
mockUseLoggedInAccounts.mockReturnValue({
authors: [{
id: 'user1',
pubkey: 'pubkey1',
metadata: { name: 'Test User' }
}],
currentUser: {
id: 'user1',
pubkey: 'pubkey1',
metadata: { name: 'Test User' }
},
otherUsers: [],
setLogin: vi.fn(),
removeLogin: vi.fn(),
isLoading: false
});
render(<LoginArea />);
expect(screen.getByTestId('account-switcher')).toBeInTheDocument();
});
it('maintains consistent layout structure whether logged in or not', () => {
// Test logged out state
mockUseLoggedInAccounts.mockReturnValue({
authors: [],
currentUser: undefined,
otherUsers: [],
setLogin: vi.fn(),
removeLogin: vi.fn(),
isLoading: false
});
const { rerender } = render(<LoginArea />);
const loggedOutContainer = screen.getByRole('button');
expect(loggedOutContainer).toHaveClass('flex', 'items-center', 'gap-3', 'p-3', 'rounded-full');
// Test logged in state
mockUseLoggedInAccounts.mockReturnValue({
authors: [{
id: 'user1',
pubkey: 'pubkey1',
metadata: { name: 'Test User' }
}],
currentUser: {
id: 'user1',
pubkey: 'pubkey1',
metadata: { name: 'Test User' }
},
otherUsers: [],
setLogin: vi.fn(),
removeLogin: vi.fn(),
isLoading: false
});
rerender(<LoginArea />);
// Both states should maintain similar structure
expect(screen.getByTestId('account-switcher')).toBeInTheDocument();
});
});
+59 -18
View File
@@ -2,20 +2,31 @@
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { useState } from 'react';
import { User, UserPlus } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx';
import { useTranslation } from 'react-i18next';
import { User, UserPlus, ChevronDown, Settings, HelpCircle } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu.tsx';
import { Avatar, AvatarFallback } from '@/components/ui/avatar.tsx';
import LoginDialog from './LoginDialog';
import SignupDialog from './SignupDialog';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
import { AccountSwitcher } from './AccountSwitcher';
import { cn } from '@/lib/utils';
import { useNavigate } from 'react-router-dom';
export interface LoginAreaProps {
className?: string;
}
export function LoginArea({ className }: LoginAreaProps) {
const { t } = useTranslation();
const { currentUser } = useLoggedInAccounts();
const navigate = useNavigate();
const [loginDialogOpen, setLoginDialogOpen] = useState(false);
const [signupDialogOpen, setSignupDialogOpen] = useState(false);
@@ -29,22 +40,52 @@ export function LoginArea({ className }: LoginAreaProps) {
{currentUser ? (
<AccountSwitcher onAddAccountClick={() => setLoginDialogOpen(true)} />
) : (
<div className="flex gap-3 justify-center">
<Button
onClick={() => setLoginDialogOpen(true)}
className='flex items-center gap-2 px-4 py-2 rounded-full bg-primary text-primary-foreground w-full font-medium transition-all hover:bg-primary/90 animate-scale-in'
>
<User className='w-4 h-4' />
<span className='truncate'>Log in</span>
</Button><Button
onClick={() => setSignupDialogOpen(true)}
variant="outline"
className="flex items-center gap-2 px-4 py-2 rounded-full font-medium transition-all"
>
<UserPlus className="w-4 h-4" />
<span>Sign Up</span>
</Button>
</div>
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<button className='flex items-center gap-3 p-3 rounded-full hover:bg-accent transition-all w-full text-foreground'>
<Avatar className='w-10 h-10'>
<AvatarFallback>
<User className='w-5 h-5 text-muted-foreground' />
</AvatarFallback>
</Avatar>
<div className='flex-1 text-left truncate'>
<p className='font-medium text-sm truncate'>{t('anonymous')}</p>
</div>
<ChevronDown className='w-4 h-4 text-muted-foreground' />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent className='w-56 p-2 animate-scale-in'>
<DropdownMenuItem
onClick={() => navigate('/settings')}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
>
<Settings className='w-4 h-4' />
<span>{t('settings')}</span>
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => window.open('https://soapbox.pub/shakespeare-resources/', '_blank')}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
>
<HelpCircle className='w-4 h-4' />
<span>{t('help')}</span>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => setLoginDialogOpen(true)}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
>
<User className='w-4 h-4' />
<span>{t('logIn')}</span>
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setSignupDialogOpen(true)}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
>
<UserPlus className='w-4 h-4' />
<span>{t('signUp')}</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
<LoginDialog
+9 -3
View File
@@ -3,6 +3,7 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { ChevronLeft, ChevronRight, RefreshCw } from 'lucide-react';
import { cn } from '@/lib/utils';
import { ReactNode } from 'react';
interface BrowserAddressBarProps {
currentPath?: string;
@@ -13,6 +14,7 @@ interface BrowserAddressBarProps {
canGoBack?: boolean;
canGoForward?: boolean;
className?: string;
extraContent?: ReactNode;
}
export function BrowserAddressBar({
@@ -24,18 +26,19 @@ export function BrowserAddressBar({
canGoBack = false,
canGoForward = false,
className,
extraContent,
}: BrowserAddressBarProps) {
const [inputValue, setInputValue] = useState(currentPath);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
let path = inputValue.trim();
// Ensure path starts with /
if (!path.startsWith('/')) {
path = '/' + path;
}
onNavigate?.(path);
};
@@ -45,7 +48,7 @@ export function BrowserAddressBar({
return (
<div className={cn(
"flex items-center gap-1 p-2 border-b bg-background",
"flex items-center gap-1 p-2 border-b bg-background w-full",
className
)}>
{/* Navigation buttons */}
@@ -91,6 +94,9 @@ export function BrowserAddressBar({
className="h-8 bg-muted/50 border-muted-foreground/20 focus:bg-background"
/>
</form>
{/* Extra content */}
{extraContent}
</div>
);
}
+48
View File
@@ -0,0 +1,48 @@
import * as React from "react"
import { Eye, EyeOff } from "lucide-react"
import { cn } from "@/lib/utils"
const PasswordInput = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>(
({ className, ...props }, ref) => {
const [showPassword, setShowPassword] = React.useState(false)
const [isFocused, setIsFocused] = React.useState(false)
return (
<div className={cn("relative", className)}>
<input
type={showPassword ? "text" : "password"}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 pr-10 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
isFocused && "ring-2 ring-ring ring-offset-2"
)}
ref={ref}
onFocus={(e) => {
setIsFocused(true)
props.onFocus?.(e)
}}
onBlur={(e) => {
setIsFocused(false)
props.onBlur?.(e)
}}
{...props}
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 rounded-sm disabled:cursor-not-allowed disabled:opacity-50"
disabled={props.disabled}
aria-label={showPassword ? "Hide password" : "Show password"}
>
{showPassword ? (
<EyeOff className="h-4 w-4" />
) : (
<Eye className="h-4 w-4" />
)}
</button>
</div>
)
}
)
PasswordInput.displayName = "PasswordInput"
export { PasswordInput }
+2
View File
@@ -9,6 +9,8 @@ export interface AppConfig {
relayUrl: string;
/** Deploy server domain (e.g., "shakespeare.wtf") */
deployServer: string;
/** Selected language */
language?: string;
}
export interface AppContextType {
+4 -1
View File
@@ -18,6 +18,7 @@ interface UseAIChatSessionOptions {
interface StreamingMessage {
role: 'assistant';
content: string;
reasoning_content?: string;
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
}
@@ -68,16 +69,18 @@ export function useAIChat({
setStreamingMessage({
role: 'assistant',
content: '',
reasoning_content: '',
});
}
}
}, [projectId]);
useSessionSubscription('streamingUpdate', (updatedProjectId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => {
useSessionSubscription('streamingUpdate', (updatedProjectId: string, content: string, reasoningContent?: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => {
if (updatedProjectId === projectId) {
setStreamingMessage({
role: 'assistant',
content,
reasoning_content: reasoningContent,
tool_calls: toolCalls
});
}
+69
View File
@@ -0,0 +1,69 @@
import { useQuery } from '@tanstack/react-query';
import { z } from 'zod';
import { createAIClient } from '@/lib/ai-client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import type { AIConnection } from '@/contexts/AISettingsContext';
// Zod schemas for the two possible response formats
const creditsResponseV1Schema = z.object({
object: z.literal('credits'),
amount: z.number(),
});
const creditsResponseV2Schema = z.object({
data: z.object({
total_credits: z.number(),
total_usage: z.number(),
}),
});
// Union schema to handle both response formats
const creditsResponseSchema = z.union([creditsResponseV1Schema, creditsResponseV2Schema]);
// Normalized response type (always in V1 format)
export interface CreditsResponse {
object: 'credits';
amount: number;
}
/**
* Custom hook to fetch AI provider credits
* @param providerId - The ID of the AI provider
* @param connection - The AI connection configuration
* @returns Query result with credits information
*/
export function useAICredits(providerId: string, connection: AIConnection) {
const { user } = useCurrentUser();
return useQuery({
queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId],
queryFn: async (): Promise<CreditsResponse> => {
try {
const ai = createAIClient(connection, user);
const data = await ai.get('/credits');
// Validate and normalize the response
const parsed = creditsResponseSchema.parse(data);
// Convert V2 format to V1 format if needed
if ('data' in parsed) {
return {
object: 'credits',
amount: parsed.data.total_credits - parsed.data.total_usage,
};
}
// Already in V1 format
return parsed;
} catch (error) {
if (error instanceof Error && !error.message.includes('Connection error')) {
console.error('Error fetching AI credits:', error);
}
throw error;
}
},
retry: false, // Don't retry as not all providers support this endpoint
refetchOnWindowFocus: false,
staleTime: 5 * 60 * 1000, // 5 minutes
});
}
+178 -32
View File
@@ -171,7 +171,7 @@ describe('useAIProjectId', () => {
);
});
it('should retry with new names when project exists', async () => {
it('should fallback to untitled when project exists', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: {
@@ -187,25 +187,20 @@ describe('useAIProjectId', () => {
addRecentlyUsedModel: vi.fn(),
});
// Mock multiple responses - first one exists, second one is unique
const mockCompletion1 = {
// Mock AI response - returns a project name that already exists
const mockCompletion = {
choices: [{ message: { content: 'existing-project' } }]
};
const mockCompletion2 = {
choices: [{ message: { content: 'unique-project' } }]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn()
.mockResolvedValueOnce(mockCompletion1)
.mockResolvedValueOnce(mockCompletion2)
create: vi.fn().mockResolvedValueOnce(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
// Mock getProject - first call returns project (exists), second returns null (unique)
// Mock getProject - first call returns project (exists), second returns null (untitled is available)
const mockGetProject = vi.fn()
.mockResolvedValueOnce({ id: 'existing-project', name: 'Existing Project', path: '/projects/existing-project', lastModified: new Date() })
.mockResolvedValueOnce(null);
@@ -219,22 +214,16 @@ describe('useAIProjectId', () => {
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('unique-project');
expect(projectId).toBe('untitled');
expect(mockGetProject).toHaveBeenCalledTimes(2);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'existing-project');
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'unique-project');
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'untitled');
// Should have called AI twice - once for initial name, once for retry
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(2);
// Second call should include the "already taken" message
const mockCreate = mockOpenAI.chat.completions.create as ReturnType<typeof vi.fn>;
const secondCallArgs = mockCreate.mock.calls[1][0];
expect(secondCallArgs.messages).toHaveLength(3);
expect(secondCallArgs.messages[2].content).toContain('already taken');
// Should have called AI only once
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
});
it('should throw error after maximum iterations', async () => {
it('should fallback to untitled-1 when untitled exists', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: {
@@ -250,7 +239,7 @@ describe('useAIProjectId', () => {
addRecentlyUsedModel: vi.fn(),
});
// Mock AI to always return the same name
// Mock AI to return a project name that already exists
const mockCompletion = {
choices: [{ message: { content: 'taken-project' } }]
};
@@ -263,13 +252,11 @@ describe('useAIProjectId', () => {
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
// Mock getProject to always return a project (project always exists)
const mockGetProject = vi.fn().mockResolvedValue({
id: 'taken-project',
name: 'Taken Project',
path: '/projects/taken-project',
lastModified: new Date()
});
// Mock getProject - taken-project exists, untitled exists, untitled-1 is available
const mockGetProject = vi.fn()
.mockResolvedValueOnce({ id: 'taken-project', name: 'Taken Project', path: '/projects/taken-project', lastModified: new Date() })
.mockResolvedValueOnce({ id: 'untitled', name: 'Untitled', path: '/projects/untitled', lastModified: new Date() })
.mockResolvedValueOnce(null);
const mockProjectsManager = {
getProject: mockGetProject,
@@ -278,11 +265,170 @@ describe('useAIProjectId', () => {
const { result } = renderHook(() => useAIProjectId());
await expect(result.current.generateProjectId('openai/gpt-4', 'A social media app for developers'))
.rejects.toThrow('Failed to generate a unique project name after 3 attempts');
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('untitled-1');
expect(mockGetProject).toHaveBeenCalledTimes(3);
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(3);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'taken-project');
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'untitled');
expect(mockGetProject).toHaveBeenNthCalledWith(3, 'untitled-1');
// Should have called AI only once
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
});
it('should fallback to untitled when AI generates too long name', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
},
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
addProvider: vi.fn(),
removeProvider: vi.fn(),
updateProvider: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
// Mock AI to return a very long project name (over 50 characters)
const mockCompletion = {
choices: [{ message: { content: 'this-is-a-very-long-project-name-that-exceeds-the-maximum-allowed-length-limit' } }]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
// Mock getProject - untitled is available
const mockGetProject = vi.fn().mockResolvedValue(null);
const mockProjectsManager = {
getProject: mockGetProject,
} as unknown as ProjectsManager;
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
const { result } = renderHook(() => useAIProjectId());
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('untitled');
expect(mockGetProject).toHaveBeenCalledTimes(1);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'untitled');
// Should have called AI only once
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
});
it('should fallback to untitled when AI generates invalid name', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
},
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
addProvider: vi.fn(),
removeProvider: vi.fn(),
updateProvider: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
// Mock AI to return an invalid project name (doesn't match regex)
const mockCompletion = {
choices: [{ message: { content: 'Invalid Project Name!' } }]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
// Mock getProject - untitled is available
const mockGetProject = vi.fn().mockResolvedValue(null);
const mockProjectsManager = {
getProject: mockGetProject,
} as unknown as ProjectsManager;
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
const { result } = renderHook(() => useAIProjectId());
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('untitled');
expect(mockGetProject).toHaveBeenCalledTimes(1);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'untitled');
// Should have called AI only once
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
});
it('should fallback to untitled-2 when untitled and untitled-1 exist', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
},
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
addProvider: vi.fn(),
removeProvider: vi.fn(),
updateProvider: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
// Mock AI to return a project name that already exists
const mockCompletion = {
choices: [{ message: { content: 'taken-project' } }]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
// Mock getProject - taken-project exists, untitled exists, untitled-1 exists, untitled-2 is available
const mockGetProject = vi.fn()
.mockResolvedValueOnce({ id: 'taken-project', name: 'Taken Project', path: '/projects/taken-project', lastModified: new Date() })
.mockResolvedValueOnce({ id: 'untitled', name: 'Untitled', path: '/projects/untitled', lastModified: new Date() })
.mockResolvedValueOnce({ id: 'untitled-1', name: 'Untitled 1', path: '/projects/untitled-1', lastModified: new Date() })
.mockResolvedValueOnce(null);
const mockProjectsManager = {
getProject: mockGetProject,
} as unknown as ProjectsManager;
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
const { result } = renderHook(() => useAIProjectId());
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('untitled-2');
expect(mockGetProject).toHaveBeenCalledTimes(4);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'taken-project');
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'untitled');
expect(mockGetProject).toHaveBeenNthCalledWith(3, 'untitled-1');
expect(mockGetProject).toHaveBeenNthCalledWith(4, 'untitled-2');
// Should have called AI only once
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
});
it('should handle loading state correctly', async () => {
+36 -49
View File
@@ -38,58 +38,45 @@ export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
{ role: 'user' as const, content: prompt }
];
let iterations = 0;
const maxIterations = 3;
// Try once to generate a project name
const completion = await openai.chat.completions.create({
model,
messages,
temperature: 1,
});
while (iterations < maxIterations) {
iterations++;
const completion = await openai.chat.completions.create({
model,
messages,
temperature: 1,
});
const projectName = completion.choices[0]?.message?.content?.trim();
if (!projectName) {
throw new Error('Failed to generate project name');
}
// Convert the name into kebab-case
const projectId = projectName
.toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with hyphens
.replace(/[^a-z0-9-]/g, '') // Remove invalid characters
.replace(/-+/g, '-') // Replace multiple hyphens with a single hyphen
.replace(/^-+|-+$/g, ''); // Trim hyphens from start and end
if (!projectId) {
throw new Error('Generated project ID is empty after formatting');
}
// Validate the generated ID
const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
if (!validIdRegex.test(projectId)) {
throw new Error('Generated project ID is invalid');
}
// Check if project exists
const existingProject = await projectsManager.getProject(projectId);
if (existingProject !== null) {
// Add user message indicating the name is already taken
messages.push({
role: 'user',
content: `The name "${projectName}" (project ID: ${projectId}) is already taken. Please generate another unique name.`
});
continue; // Try again with updated conversation
}
// If we reach here, the project ID is valid and unique
return projectId;
const projectId = completion.choices[0]?.message?.content?.trim();
if (!projectId) {
throw new Error('Failed to generate project name');
}
// If we've exceeded max iterations, throw an error
throw new Error(`Failed to generate a unique project name after ${maxIterations} attempts`);
// Validate the generated ID directly (no conversion)
const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
if (projectId.length <= 50 && validIdRegex.test(projectId)) {
// Check if project exists
const existingProject = await projectsManager.getProject(projectId);
if (existingProject === null) {
// Valid and unique project ID
return projectId;
}
}
// If we reach here, either the regex failed or the project already exists
// Fall back to "untitled" with number suffixes
let fallbackId = 'untitled';
let counter = 1;
// Check if base "untitled" exists
let existingProject = await projectsManager.getProject(fallbackId);
// Keep incrementing until we find an available name
while (existingProject !== null) {
fallbackId = `untitled-${counter}`;
existingProject = await projectsManager.getProject(fallbackId);
counter++;
}
return fallbackId;
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Failed to generate project ID';
onError?.(errorMessage);
+157
View File
@@ -0,0 +1,157 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { useGitHubOAuth } from './useGitHubOAuth';
import { TestApp } from '@/test/TestApp';
// Mock environment variables for testing
vi.stubEnv('VITE_GITHUB_OAUTH_CLIENT_ID', '********************');
vi.stubEnv('VITE_GITHUB_OAUTH_CLIENT_SECRET', '****************************************');
// Mock crypto.subtle for PKCE testing
const mockCryptoSubtle = {
digest: vi.fn(),
};
const mockCrypto = {
getRandomValues: vi.fn(),
randomUUID: vi.fn(),
subtle: mockCryptoSubtle,
};
Object.defineProperty(global, 'crypto', {
value: mockCrypto,
writable: true,
});
// Mock btoa for base64 encoding
global.btoa = vi.fn((str: string) => Buffer.from(str, 'binary').toString('base64'));
describe('useGitHubOAuth PKCE', () => {
beforeEach(() => {
vi.clearAllMocks();
localStorage.clear();
// Setup crypto mocks
mockCrypto.getRandomValues.mockImplementation((array: Uint8Array) => {
// Fill with predictable values for testing
for (let i = 0; i < array.length; i++) {
array[i] = i % 256;
}
return array;
});
mockCrypto.randomUUID.mockReturnValue('test-state-uuid');
// Mock SHA-256 digest to return predictable hash
mockCryptoSubtle.digest.mockResolvedValue(
new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32])
);
});
afterEach(() => {
localStorage.clear();
});
it('should validate state parameter in callback', async () => {
// Setup stored state
localStorage.setItem('github_oauth_state', 'correct-state');
localStorage.setItem('github_oauth_code_verifier', 'test-verifier');
const { result } = renderHook(() => useGitHubOAuth(), {
wrapper: TestApp,
});
// Mock fetch for token exchange and user info (using corsproxy.io URLs)
const mockFetch = vi.fn()
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ access_token: 'test-token' }),
})
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ login: 'testuser' }),
});
global.fetch = mockFetch;
let success: boolean | undefined;
await act(async () => {
success = await result.current.handleCallback('test-code', 'correct-state');
});
expect(success).toBe(true);
expect(localStorage.getItem('github_oauth_state')).toBeNull();
expect(localStorage.getItem('github_oauth_code_verifier')).toBeNull();
});
it('should reject invalid state parameter', async () => {
localStorage.setItem('github_oauth_state', 'correct-state');
localStorage.setItem('github_oauth_code_verifier', 'test-verifier');
const { result } = renderHook(() => useGitHubOAuth(), {
wrapper: TestApp,
});
let success: boolean | undefined;
await act(async () => {
success = await result.current.handleCallback('test-code', 'wrong-state');
});
expect(success).toBe(false);
expect(result.current.error).toBe('Invalid OAuth state parameter');
// Should clean up on error
expect(localStorage.getItem('github_oauth_state')).toBeNull();
expect(localStorage.getItem('github_oauth_code_verifier')).toBeNull();
});
it('should reject missing code verifier', async () => {
localStorage.setItem('github_oauth_state', 'correct-state');
// Don't set code verifier
const { result } = renderHook(() => useGitHubOAuth(), {
wrapper: TestApp,
});
let success: boolean | undefined;
await act(async () => {
success = await result.current.handleCallback('test-code', 'correct-state');
});
expect(success).toBe(false);
expect(result.current.error).toBe('PKCE code verifier not found. Please restart the OAuth flow.');
});
it('should include code_verifier in token request', async () => {
localStorage.setItem('github_oauth_state', 'correct-state');
localStorage.setItem('github_oauth_code_verifier', 'test-verifier');
const { result } = renderHook(() => useGitHubOAuth(), {
wrapper: TestApp,
});
const mockFetch = vi.fn()
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ access_token: 'test-token' }),
})
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ login: 'testuser' }),
});
global.fetch = mockFetch;
await act(async () => {
await result.current.handleCallback('test-code', 'correct-state');
});
// Check that the token request includes the code verifier
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('corsproxy.io/?url=https://github.com/login/oauth/access_token'),
expect.objectContaining({
method: 'POST',
body: expect.stringContaining('"code_verifier":"test-verifier"'),
})
);
});
});
+73 -19
View File
@@ -25,7 +25,28 @@ export function useGitHubOAuth() {
import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET
);
const initiateOAuth = useCallback(() => {
// Generate a cryptographically secure random string for PKCE code verifier
const generateCodeVerifier = (): string => {
const array = new Uint8Array(32);
crypto.getRandomValues(array);
return btoa(String.fromCharCode(...array))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
};
// Create SHA-256 hash of the code verifier for PKCE code challenge
const generateCodeChallenge = async (codeVerifier: string): Promise<string> => {
const encoder = new TextEncoder();
const data = encoder.encode(codeVerifier);
const digest = await crypto.subtle.digest('SHA-256', data);
return btoa(String.fromCharCode(...new Uint8Array(digest)))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
};
const initiateOAuth = useCallback(async () => {
const clientId = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID;
if (!clientId) {
@@ -33,19 +54,36 @@ export function useGitHubOAuth() {
return;
}
// Generate a random state parameter for security
const state = crypto.randomUUID();
localStorage.setItem('github_oauth_state', state);
try {
// Generate PKCE parameters
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
// Redirect to GitHub OAuth
const params = new URLSearchParams({
client_id: clientId,
redirect_uri: window.location.origin + '/',
scope: 'repo',
state: state,
});
// Generate a random state parameter for security
const state = crypto.randomUUID();
window.location.href = `https://github.com/login/oauth/authorize?${params.toString()}`;
// Store both state and code verifier for later use
localStorage.setItem('github_oauth_state', state);
localStorage.setItem('github_oauth_code_verifier', codeVerifier);
// Redirect to GitHub OAuth with PKCE parameters
const params = new URLSearchParams({
client_id: clientId,
redirect_uri: window.location.origin + '/oauth/github',
scope: 'repo',
state: state,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
});
window.location.href = `https://github.com/login/oauth/authorize?${params.toString()}`;
} catch (error) {
console.error('Failed to initiate OAuth with PKCE:', error);
setState(prev => ({
...prev,
error: 'Failed to generate PKCE parameters. Please try again.'
}));
}
}, []);
const handleCallback = useCallback(async (code: string, state: string) => {
@@ -58,8 +96,15 @@ export function useGitHubOAuth() {
throw new Error('Invalid OAuth state parameter');
}
// Clean up stored state
// Get the stored code verifier for PKCE
const codeVerifier = localStorage.getItem('github_oauth_code_verifier');
if (!codeVerifier) {
throw new Error('PKCE code verifier not found. Please restart the OAuth flow.');
}
// Clean up stored values
localStorage.removeItem('github_oauth_state');
localStorage.removeItem('github_oauth_code_verifier');
const clientId = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID;
const clientSecret = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET;
@@ -68,18 +113,22 @@ export function useGitHubOAuth() {
throw new Error('GitHub OAuth credentials not configured');
}
// Exchange code for access token
// Exchange code for access token with PKCE code verifier
const tokenRequestBody = {
client_id: clientId,
client_secret: clientSecret,
code: code,
redirect_uri: window.location.origin + '/oauth/github',
code_verifier: codeVerifier,
};
const tokenResponse = await fetch('https://corsproxy.io/?url=https://github.com/login/oauth/access_token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
client_id: clientId,
client_secret: clientSecret,
code: code,
}),
body: JSON.stringify(tokenRequestBody),
});
if (!tokenResponse.ok) {
@@ -116,6 +165,11 @@ export function useGitHubOAuth() {
return true;
} catch (error) {
console.error('GitHub OAuth error:', error);
// Clean up any remaining OAuth data on error
localStorage.removeItem('github_oauth_state');
localStorage.removeItem('github_oauth_code_verifier');
setState(prev => ({
...prev,
isLoading: false,
+2 -1
View File
@@ -14,7 +14,7 @@ export function useLoggedInAccounts() {
const { nostr } = useNostr();
const { logins, setLogin, removeLogin } = useNostrLogin();
const { data: authors = [] } = useQuery({
const { data: authors = [], isLoading } = useQuery({
queryKey: ['logins', logins.map((l) => l.id).join(';')],
queryFn: async ({ signal }) => {
const events = await nostr.query(
@@ -52,5 +52,6 @@ export function useLoggedInAccounts() {
otherUsers,
setLogin,
removeLogin,
isLoading,
};
}
+24
View File
@@ -0,0 +1,24 @@
import { useEffect, useState } from "react";
export function useSystemTheme() {
const getSystemTheme = (): "dark" | "light" =>
window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
const [theme, setTheme] = useState<"dark" | "light">(getSystemTheme);
useEffect(() => {
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
const handler = (event: MediaQueryListEvent): void => {
setTheme(event.matches ? "dark" : "light");
};
// Attach listener
mediaQuery.addEventListener("change", handler);
// Cleanup
return () => mediaQuery.removeEventListener("change", handler);
}, []);
return theme;
}
+12 -1
View File
@@ -1,15 +1,26 @@
import { type Theme } from "@/contexts/AppContext";
import { useAppContext } from "@/hooks/useAppContext";
import { useSystemTheme } from "./useSystemTheme";
/**
* Hook to get and set the active theme
* @returns Theme context with theme and setTheme
*/
export function useTheme(): { theme: Theme; setTheme: (theme: Theme) => void } {
export function useTheme(): {
theme: Theme;
systemTheme: "light" | "dark";
displayTheme: "light" | "dark";
setTheme: (theme: Theme) => void;
} {
const { config, updateConfig } = useAppContext();
const systemTheme = useSystemTheme();
const displayTheme = config.theme === 'system' ? systemTheme : config.theme;
return {
theme: config.theme,
systemTheme,
displayTheme,
setTheme: (theme: Theme) => {
updateConfig((currentConfig) => ({
...currentConfig,
+2
View File
@@ -0,0 +1,2 @@
// Re-export useTranslation from react-i18next for consistency
export { useTranslation } from 'react-i18next';
+4
View File
@@ -247,6 +247,10 @@
max-height: 100dvh;
}
pre.shiki {
background-color: transparent !important;
}
/* Fallback for browsers that don't support dvh */
@supports not (height: 100dvh) {
.h-dvh {
+97
View File
@@ -0,0 +1,97 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { SessionManager, type AIMessage } from './SessionManager';
import type { JSRuntimeFS } from './JSRuntime';
// Mock the filesystem
const mockFS: JSRuntimeFS = {
readFile: vi.fn(),
writeFile: vi.fn(),
readdir: vi.fn(),
mkdir: vi.fn(),
rmdir: vi.fn(),
unlink: vi.fn(),
stat: vi.fn(),
exists: vi.fn(),
copyFile: vi.fn(),
rename: vi.fn(),
symlink: vi.fn(),
readlink: vi.fn(),
chmod: vi.fn(),
chown: vi.fn(),
utimes: vi.fn(),
realpath: vi.fn(),
} as unknown as JSRuntimeFS;
describe('SessionManager', () => {
let sessionManager: SessionManager;
const mockAISettings = {
providers: {
'test-provider': {
baseURL: 'https://api.test.com',
apiKey: 'test-key'
}
}
};
beforeEach(() => {
sessionManager = new SessionManager(mockFS, mockAISettings);
});
it('should initialize streaming message with reasoning content', async () => {
const projectId = 'test-project';
const tools = {};
const customTools = {};
const session = await sessionManager.loadSession(projectId, tools, customTools);
expect(session.projectId).toBe(projectId);
expect(session.streamingMessage).toBeUndefined();
});
it('should emit streamingUpdate events with reasoning content', () => {
const projectId = 'test-project';
const mockListener = vi.fn();
sessionManager.on('streamingUpdate', mockListener);
// Simulate a streaming update with reasoning content
sessionManager.emit('streamingUpdate', projectId, 'content', 'reasoning', undefined);
expect(mockListener).toHaveBeenCalledWith(projectId, 'content', 'reasoning', undefined);
});
it('should handle streaming message with reasoning content', async () => {
const projectId = 'test-project';
const tools = {};
const customTools = {};
const session = await sessionManager.loadSession(projectId, tools, customTools);
// Manually set a streaming message to test the structure
session.streamingMessage = {
role: 'assistant',
content: 'test content',
reasoning_content: 'test reasoning',
tool_calls: undefined
};
expect(session.streamingMessage.reasoning_content).toBe('test reasoning');
expect(session.streamingMessage.content).toBe('test content');
});
it('should support assistant messages with reasoning content', () => {
// Test that AIMessage type supports reasoning content
const messageWithReasoning: AIMessage = {
role: 'assistant',
content: 'Here is my response',
reasoning_content: 'Let me think about this step by step...'
};
expect(messageWithReasoning.role).toBe('assistant');
expect(messageWithReasoning.content).toBe('Here is my response');
expect('reasoning_content' in messageWithReasoning).toBe(true);
if ('reasoning_content' in messageWithReasoning) {
expect(messageWithReasoning.reasoning_content).toBe('Let me think about this step by step...');
}
});
});
+23 -4
View File
@@ -6,7 +6,12 @@ import { createAIClient } from './ai-client';
import type { Tool } from './tools/Tool';
import type { NUser } from '@nostrify/react/login';
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
role: 'assistant';
content: string;
reasoning_content?: string;
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
};
export interface SessionState {
projectId: string;
@@ -18,6 +23,7 @@ export interface SessionState {
streamingMessage?: {
role: 'assistant';
content: string;
reasoning_content?: string;
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
};
isLoading: boolean;
@@ -32,7 +38,7 @@ export interface SessionManagerEvents {
sessionCreated: (projectId: string) => void;
sessionDeleted: (projectId: string) => void;
messageAdded: (projectId: string, message: AIMessage) => void;
streamingUpdate: (projectId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
streamingUpdate: (projectId: string, content: string, reasoningContent?: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
loadingChanged: (projectId: string, isLoading: boolean) => void;
costUpdated: (projectId: string, totalCost: number) => void;
contextUsageUpdated: (projectId: string, inputTokens: number) => void;
@@ -219,6 +225,7 @@ export class SessionManager {
session.streamingMessage = {
role: 'assistant',
content: '',
reasoning_content: '',
tool_calls: undefined
};
@@ -245,6 +252,7 @@ export class SessionManager {
});
let accumulatedContent = '';
let accumulatedReasoningContent = '';
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
let finishReason: string | null = null;
@@ -260,7 +268,17 @@ export class SessionManager {
accumulatedContent += delta.content;
if (session.streamingMessage) {
session.streamingMessage.content += delta.content;
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.tool_calls);
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.reasoning_content, session.streamingMessage.tool_calls);
}
}
// Handle reasoning content if present (some providers may include this)
const deltaWithReasoning = delta as { reasoning_content?: string };
if (deltaWithReasoning?.reasoning_content) {
accumulatedReasoningContent += deltaWithReasoning.reasoning_content;
if (session.streamingMessage) {
session.streamingMessage.reasoning_content += deltaWithReasoning.reasoning_content;
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.reasoning_content, session.streamingMessage.tool_calls);
}
}
@@ -283,7 +301,7 @@ export class SessionManager {
if (session.streamingMessage) {
session.streamingMessage.tool_calls = accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined;
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.tool_calls);
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.reasoning_content, session.streamingMessage.tool_calls);
}
}
@@ -304,6 +322,7 @@ export class SessionManager {
const assistantMessage: AIMessage = {
role: 'assistant',
content: accumulatedContent,
...(accumulatedReasoningContent && { reasoning_content: accumulatedReasoningContent }),
...(accumulatedToolCalls.length > 0 && { tool_calls: accumulatedToolCalls })
};
+21
View File
@@ -44,6 +44,23 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
};
});
// node built-in modules
build.onResolve({ filter: /^node:/ }, (args) => {
const moduleName = args.path.slice(5);
switch (moduleName) {
case "buffer":
return {
path: `https://esm.sh/${moduleName}?target=${target ?? "esnext"}`,
namespace: "esm",
};
default:
return {
errors: [{ text: `Module not found: ${args.path}` }],
};
}
});
// Handle bare imports like "react"
build.onResolve({ filter: /^[^./].*/ }, (args) => {
const packageName = args.path.startsWith("@")
@@ -61,6 +78,10 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
// fallthrough
}
if (packageName.startsWith("@jsr/")) {
keys.push(`node_modules/@${packageName.slice(5).replace("__", "/")}`);
}
keys.push(`node_modules/${packageName}`);
const packageInfo = keys
-1
View File
@@ -73,7 +73,6 @@ async function tryFileVariants(
return indexFile;
}
}
throw new Error("Directory without index file");
}
// Try direct file with extensions
+901
View File
@@ -0,0 +1,901 @@
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
// Translation resources
const resources = {
en: {
translation: {
// Navigation and Layout
preferences: 'Preferences',
settings: 'Settings',
backToSettings: 'Back to Settings',
help: 'Help',
anonymous: 'Anonymous',
// Authentication
logIn: 'Log in',
signUp: 'Sign up',
// Preferences Page
preferencesDescription: 'Manage your general application preferences and appearance settings.',
// Theme Section
theme: 'Theme',
themeDescription: 'Choose between light, dark, or system theme preference.',
// Language Section
language: 'Language',
languageDescription: 'Select your preferred language for the interface.',
// Language Options
english: 'English',
portuguese: 'Portuguese',
chinese: 'Chinese',
systemLanguage: 'System',
// Theme Options
light: 'Light',
dark: 'Dark',
system: 'System',
// Common UI Elements
save: 'Save',
cancel: 'Cancel',
close: 'Close',
open: 'Open',
edit: 'Edit',
delete: 'Delete',
create: 'Create',
update: 'Update',
loading: 'Loading...',
error: 'Error',
success: 'Success',
warning: 'Warning',
info: 'Information',
add: 'Add',
remove: 'Remove',
retry: 'Retry',
// Shakespeare Main Page
buildNostrApps: 'Build Nostr apps with AI',
whatToBuild: 'What would you like to build?',
createProject: 'Create Project',
generating: 'Generating...',
creating: 'Creating...',
chooseModel: 'Choose a model...',
selectModelToDescribe: "Please select a model below, then describe what you'd like to build...",
examplePrompt: "e.g., Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies...",
// Settings Page
settingsDescription: 'Manage your application settings and preferences.',
aiSettings: 'AI Settings',
aiSettingsDescription: 'Configure AI providers and API keys',
gitSettings: 'Git Settings',
gitSettingsDescription: 'Configure Git credentials for HTTP authentication',
nostrSettings: 'Nostr Settings',
nostrSettingsDescription: 'Configure relay connections and Nostr preferences',
dataSettings: 'Data',
dataSettingsDescription: 'Export files and manage local data',
aboutShakespeareSettings: 'About Shakespeare',
aboutShakespeareSettingsDescription: 'Information about Shakespeare',
// Project Sidebar
newProject: 'New Project',
importRepository: 'Import Repository',
noProjectsYet: 'No projects yet',
createFirstProject: 'Create your first project to get started',
closeSidebar: 'Close sidebar',
collapseSidebar: 'Collapse sidebar',
// Chat Interface
welcomeToShakespeare: 'Welcome to Shakespeare',
aiAssistantReady: 'Your AI-powered development assistant is ready to help you build, edit, and enhance your project.',
askMeFeatures: '💡 Ask me to add new features',
requestEdits: '📝 Request file edits and improvements',
getHelp: '🔧 Get help with debugging and optimization',
buildDeploy: '🚀 Build and deploy your project',
aiNotConfigured: 'AI Assistant Not Configured',
configureAI: 'Please configure your AI settings to start building with AI assistance.',
useMenuForAI: 'Use the menu in the top bar to access AI Settings.',
askToAddFeatures: 'Ask me to add features, edit files, or build your project...',
selectModelFirst: 'Please select a model to start chatting...',
sendMessage: 'Send message',
stopGeneration: 'Stop generation',
running: 'Running',
// Project View Navigation
chat: 'Chat',
preview: 'Preview',
code: 'Code',
// Preview Pane
projectPreview: 'Project Preview',
buildProjectToSeePreview: 'Build your project to see the preview here',
fileExplorer: 'File Explorer',
fileEditor: 'File Editor',
selectFileFromExplorer: 'Select a file from the explorer to edit',
openFileExplorer: 'Open File Explorer',
// File Editor
unsavedChanges: 'Unsaved changes',
saving: 'Saving...',
languageLabel: 'Language',
// File Tree
searchFiles: 'Search files...',
noFilesFound: 'No files found',
noFilesFoundSearch: 'No files found matching your search',
// Git Dialog
gitRepositoryStatus: 'Git Repository Status',
repositoryStatusDescription: 'View repository status and sync with remote repositories',
repositoryInformation: 'Repository Information',
currentBranch: 'Current Branch',
totalCommits: 'Total Commits',
latestCommit: 'Latest Commit',
remotes: 'Remotes',
notGitRepository: 'Not a Git repository',
gitAuthentication: 'Authentication',
credentialsDescription: 'Credentials for push/pull operations',
configured: 'Configured',
noCredentials: 'No credentials',
noCredentialsWarning: 'No credentials configured for {{provider}}. Push/pull operations may fail for private repositories.',
configureCredentials: 'Configure credentials',
syncStatus: 'Sync Status',
pull: 'Pull',
push: 'Push',
pulling: 'Pulling...',
pushing: 'Pushing...',
upToDate: 'Up to date',
commitsAhead: '{{count}} commit ahead | {{count}} commits ahead',
commitsBehind: '{{count}} commit behind | {{count}} commits behind',
uncommittedChanges: '{{count}} uncommitted change | {{count}} uncommitted changes',
noRemoteConfigured: 'No remote configured',
workingDirectoryChanges: 'Working Directory Changes',
filesWithChanges: '{{count}} file with changes | {{count}} files with changes',
workingDirectoryClean: 'Working directory is clean',
noUncommittedChanges: 'No uncommitted changes',
cannotPush: 'Cannot push',
cannotPull: 'Cannot pull',
notGitRepoOrBranch: 'Not a git repository or no current branch',
noRemoteRepositories: 'No remote repositories configured',
nothingToPush: 'Nothing to push',
noCommitsAhead: 'No commits ahead of remote. Commit your changes first.',
pushSuccessful: 'Push successful',
pushFailed: 'Push failed',
pullSuccessful: 'Pull successful',
pullFailed: 'Pull failed',
// AI Settings
aiSettingsDescriptionLong: 'Configure AI providers by adding your API keys. Settings are automatically saved and stored locally in your browser.',
configuredProviders: 'Configured Providers',
addProvider: 'Add Provider',
getApiKey: 'Get API key',
getToken: 'Get token',
enterApiKey: 'Enter your API key',
enterToken: 'Enter your token',
enterCashuToken: 'Enter a Cashu token',
addCustomProvider: 'Add Custom Provider',
providerName: 'Provider Name',
baseUrl: 'Base URL',
apiKey: 'API Key',
authentication: 'Authentication',
addCustomProviderButton: 'Add Custom Provider',
providerExists: 'Provider with this name already exists',
custom: 'Custom',
connecting: 'Connecting...',
connectToGitHub: 'Connect to GitHub',
loginToNostrRequired: 'Log in to Nostr to use this provider',
goToNostrSettings: 'Go to Nostr Settings',
// Git Settings
gitSettingsDescriptionLong: 'Configure Git credentials for HTTP authentication. Settings are automatically saved and stored locally in your browser.',
configuredCredentials: 'Configured Credentials',
origin: 'Origin',
username: 'Username',
password: 'Password',
enterPassword: 'Enter your password/token',
credentialsExist: 'Credentials for this origin already exist',
corsProxy: 'CORS Proxy',
corsProxyDescription: 'CORS proxy server used for all Git operations with remote repositories. Required for browser-based Git operations.',
// About Settings
aboutShakespeare: 'About Shakespeare',
aboutShakespeareDescription: 'Information about Shakespeare',
sourceCode: 'Source Code',
viewOnGitLab: 'View on GitLab',
description: 'Description',
license: 'License',
loadingLicense: 'Loading license...',
failedToLoadLicense: 'Failed to load license',
// Data Settings
dataSettingsDescriptionLong: 'Export files and manage local data.',
exportFiles: 'Export Files',
exportFilesDescription: 'Download all your projects and files as a ZIP archive. This includes all project files, settings, and data stored locally.',
exportAllFiles: 'Export All Files',
exporting: 'Exporting...',
clearAllData: 'Clear All Data',
clearAllDataDescription: 'Permanently delete all local data including projects, settings, and cached information. This action cannot be undone.',
clearing: 'Clearing...',
areYouSure: 'Are you absolutely sure?',
clearDataWarning: 'This action will permanently delete all local data from this browser, including:',
allProjects: 'All projects and their files',
aiSettingsAndKeys: 'AI settings and API keys',
gitCredentialsSettings: 'Git credentials and settings',
userPreferences: 'User preferences and themes',
cachedData: 'Cached data and session information',
actionCannotBeUndone: 'This action cannot be undone. Consider exporting your files first.',
yesClearAllData: 'Yes, clear all data',
used: 'Used',
available: 'Available',
usagePercentage: '{{percentage}}% used',
usageUnavailable: 'Usage percentage unavailable',
loadingStorageInfo: 'Loading storage information...',
filesExportedSuccessfully: 'Files exported successfully',
filesExportedDescription: 'Your project files have been downloaded as a zip file.',
failedToExportFiles: 'Failed to export files',
dataClearedSuccessfully: 'Data cleared successfully',
dataClearedDescription: 'All local data has been removed. Redirecting to homepage...',
failedToClearData: 'Failed to clear data',
// 404 Page
pageNotFound: 'Oops! Page not found',
returnToHome: 'Return to Home',
// Model Selector
selectOrEnterModel: 'Select or enter a model...',
searchModels: 'Search models...',
enterCustomModel: 'Enter custom model...',
manageProviders: 'Manage providers...',
noModelsFound: 'No models found.',
tryCustomModel: 'Try using a custom model instead.',
recentlyUsed: 'Recently Used',
errorLoadingModels: 'Error Loading Models',
// Context and Cost
contextUsage: 'Context usage: {{tokens}} / {{total}} tokens ({{percentage}}%)',
totalCostSession: 'Total cost for this chat session',
// File Status
added: 'added',
deleted: 'deleted',
modified: 'modified',
staged: 'staged',
untracked: 'untracked',
// Settings Layout
toggleSidebar: 'Toggle sidebar',
openSidebar: 'Open sidebar',
// Nostr Settings
nostrSettingsDescriptionLong: 'Configure your Nostr connection settings and relay preferences.',
nostrAccounts: 'Nostr Accounts',
noAccountsLoggedIn: 'No accounts logged in. Add an account to get started.',
createAccount: 'Create Account',
addExistingAccount: 'Add Existing Account',
addAccount: 'Add Account',
relayConfiguration: 'Relay Configuration',
selectedRelay: 'Selected Relay',
// Clone Page
cloneGitRepository: 'Clone a Git repository into your Shakespeare workspace',
pleaseEnterRepositoryUrl: 'Please enter a repository URL',
pleaseEnterValidGitUrl: 'Please enter a valid Git repository URL or Nostr clone URI (e.g., nostr://npub.../repo-name)',
cloningRepository: 'Cloning Repository...',
nostrRepositoryImportedSuccessfully: 'Nostr repository imported successfully',
repositoryClonedFromNostr: '"{{repoName}}" has been cloned from Nostr and is ready for development.',
repositoryImportedSuccessfully: 'Repository imported successfully',
repositoryClonedReady: '"{{repoName}}" has been cloned and is ready for development.',
failedToImportRepository: 'Failed to import repository',
repositoryNotFoundOnNostr: 'Repository not found on Nostr network. Please check the URI and try again.',
noCloneUrlsFound: 'Repository announcement found but no clone URLs available.',
allCloneAttemptsFailed: 'Repository found but all clone URLs failed. The repository may be unavailable.',
repositoryNotFound: 'Repository not found. Please check the URL and try again.',
accessDenied: 'Access denied. The repository may be private or require authentication.',
networkError: 'Network error. Please check your connection and try again.',
}
},
pt: {
translation: {
// Navigation and Layout
preferences: 'Preferências',
settings: 'Configurações',
backToSettings: 'Voltar às Configurações',
help: 'Ajuda',
anonymous: 'Anônimo',
// Authentication
logIn: 'Entrar',
signUp: 'Cadastrar',
// Preferences Page
preferencesDescription: 'Gerencie suas preferências gerais da aplicação e configurações de aparência.',
// Theme Section
theme: 'Tema',
themeDescription: 'Escolha entre preferência de tema claro, escuro ou do sistema.',
// Language Section
language: 'Idioma',
languageDescription: 'Selecione seu idioma preferido para a interface.',
// Language Options
english: 'Inglês',
portuguese: 'Português',
chinese: 'Chinês',
systemLanguage: 'Sistema',
// Theme Options
light: 'Claro',
dark: 'Escuro',
system: 'Sistema',
// Common UI Elements
save: 'Salvar',
cancel: 'Cancelar',
close: 'Fechar',
open: 'Abrir',
edit: 'Editar',
delete: 'Excluir',
create: 'Criar',
update: 'Atualizar',
loading: 'Carregando...',
error: 'Erro',
success: 'Sucesso',
warning: 'Aviso',
info: 'Informação',
add: 'Adicionar',
remove: 'Remover',
retry: 'Tentar novamente',
// Shakespeare Main Page
buildNostrApps: 'Construa aplicativos Nostr com IA',
whatToBuild: 'O que você gostaria de construir?',
createProject: 'Criar Projeto',
generating: 'Gerando...',
creating: 'Criando...',
chooseModel: 'Escolha um modelo...',
selectModelToDescribe: "Por favor, selecione um modelo abaixo e depois descreva o que gostaria de construir...",
examplePrompt: "ex., Criar um marketplace de equipamentos agrícolas para fazendeiros locais comprarem e venderem tratores, ferramentas e suprimentos...",
// Settings Page
settingsDescription: 'Gerencie as configurações e preferências da aplicação.',
aiSettings: 'Configurações de IA',
aiSettingsDescription: 'Configure provedores de IA e chaves de API',
gitSettings: 'Configurações do Git',
gitSettingsDescription: 'Configure credenciais do Git para autenticação HTTP',
nostrSettings: 'Configurações do Nostr',
nostrSettingsDescription: 'Configure conexões de relay e preferências do Nostr',
dataSettings: 'Dados',
dataSettingsDescription: 'Exporte arquivos e gerencie dados locais',
aboutShakespeareSettings: 'Sobre o Shakespeare',
aboutShakespeareSettingsDescription: 'Informações sobre o Shakespeare',
// Project Sidebar
newProject: 'Novo Projeto',
importRepository: 'Importar Repositório',
noProjectsYet: 'Nenhum projeto ainda',
createFirstProject: 'Crie seu primeiro projeto para começar',
closeSidebar: 'Fechar barra lateral',
collapseSidebar: 'Recolher barra lateral',
// Chat Interface
welcomeToShakespeare: 'Bem-vindo ao Shakespeare',
aiAssistantReady: 'Seu assistente de desenvolvimento com IA está pronto para ajudá-lo a construir, editar e aprimorar seu projeto.',
askMeFeatures: '💡 Peça para adicionar novos recursos',
requestEdits: '📝 Solicite edições e melhorias de arquivos',
getHelp: '🔧 Obtenha ajuda com depuração e otimização',
buildDeploy: '🚀 Construa e implante seu projeto',
aiNotConfigured: 'Assistente de IA Não Configurado',
configureAI: 'Configure suas configurações de IA para começar a construir com assistência de IA.',
useMenuForAI: 'Use o menu na barra superior para acessar as Configurações de IA.',
askToAddFeatures: 'Peça para adicionar recursos, editar arquivos ou construir seu projeto...',
selectModelFirst: 'Selecione um modelo para começar a conversar...',
sendMessage: 'Enviar mensagem',
stopGeneration: 'Parar geração',
running: 'Executando',
// Project View Navigation
chat: 'Chat',
preview: 'Visualização',
code: 'Código',
// Preview Pane
projectPreview: 'Visualização do Projeto',
buildProjectToSeePreview: 'Construa seu projeto para ver a visualização aqui',
fileExplorer: 'Explorador de Arquivos',
fileEditor: 'Editor de Arquivos',
selectFileFromExplorer: 'Selecione um arquivo do explorador para editar',
openFileExplorer: 'Abrir Explorador de Arquivos',
// File Editor
unsavedChanges: 'Alterações não salvas',
saving: 'Salvando...',
languageLabel: 'Linguagem',
// File Tree
searchFiles: 'Buscar arquivos...',
noFilesFound: 'Nenhum arquivo encontrado',
noFilesFoundSearch: 'Nenhum arquivo encontrado correspondente à sua busca',
// Git Dialog
gitRepositoryStatus: 'Status do Repositório Git',
repositoryStatusDescription: 'Visualizar status do repositório e sincronizar com repositórios remotos',
repositoryInformation: 'Informações do Repositório',
currentBranch: 'Branch Atual',
totalCommits: 'Total de Commits',
latestCommit: 'Último Commit',
remotes: 'Remotos',
notGitRepository: 'Não é um repositório Git',
gitAuthentication: 'Autenticação',
credentialsDescription: 'Credenciais para operações de push/pull',
configured: 'Configurado',
noCredentials: 'Sem credenciais',
noCredentialsWarning: 'Nenhuma credencial configurada para {{provider}}. Operações de push/pull podem falhar para repositórios privados.',
configureCredentials: 'Configurar credenciais',
syncStatus: 'Status de Sincronização',
pull: 'Pull',
push: 'Push',
pulling: 'Fazendo pull...',
pushing: 'Fazendo push...',
upToDate: 'Atualizado',
commitsAhead: '{{count}} commit à frente | {{count}} commits à frente',
commitsBehind: '{{count}} commit atrás | {{count}} commits atrás',
uncommittedChanges: '{{count}} alteração não commitada | {{count}} alterações não commitadas',
noRemoteConfigured: 'Nenhum remoto configurado',
workingDirectoryChanges: 'Alterações do Diretório de Trabalho',
filesWithChanges: '{{count}} arquivo com alterações | {{count}} arquivos com alterações',
workingDirectoryClean: 'Diretório de trabalho limpo',
noUncommittedChanges: 'Nenhuma alteração não commitada',
cannotPush: 'Não é possível fazer push',
cannotPull: 'Não é possível fazer pull',
notGitRepoOrBranch: 'Não é um repositório git ou não há branch atual',
noRemoteRepositories: 'Nenhum repositório remoto configurado',
nothingToPush: 'Nada para fazer push',
noCommitsAhead: 'Nenhum commit à frente do remoto. Faça commit de suas alterações primeiro.',
pushSuccessful: 'Push realizado com sucesso',
pushFailed: 'Push falhou',
pullSuccessful: 'Pull realizado com sucesso',
pullFailed: 'Pull falhou',
// AI Settings
aiSettingsDescriptionLong: 'Configure provedores de IA adicionando suas chaves de API. As configurações são salvas automaticamente e armazenadas localmente em seu navegador.',
configuredProviders: 'Provedores Configurados',
addProvider: 'Adicionar Provedor',
getApiKey: 'Obter chave de API',
getToken: 'Obter token',
enterApiKey: 'Digite sua chave de API',
enterToken: 'Digite seu token',
enterCashuToken: 'Digite um token Cashu',
addCustomProvider: 'Adicionar Provedor Personalizado',
providerName: 'Nome do Provedor',
baseUrl: 'URL Base',
apiKey: 'Chave de API',
authentication: 'Autenticação',
addCustomProviderButton: 'Adicionar Provedor Personalizado',
providerExists: 'Provedor com este nome já existe',
custom: 'Personalizado',
connecting: 'Conectando...',
connectToGitHub: 'Conectar ao GitHub',
loginToNostrRequired: 'Faça login no Nostr para usar este provedor',
goToNostrSettings: 'Ir para Configurações do Nostr',
// Git Settings
gitSettingsDescriptionLong: 'Configure credenciais do Git para autenticação HTTP. As configurações são salvas automaticamente e armazenadas localmente em seu navegador.',
configuredCredentials: 'Credenciais Configuradas',
origin: 'Origem',
username: 'Nome de usuário',
password: 'Senha',
enterPassword: 'Digite sua senha/token',
credentialsExist: 'Credenciais para esta origem já existem',
corsProxy: 'Proxy CORS',
corsProxyDescription: 'Servidor proxy CORS usado para todas as operações Git com repositórios remotos. Necessário para operações Git baseadas no navegador.',
// Data Settings
dataSettingsDescriptionLong: 'Exporte arquivos e gerencie dados locais.',
exportFiles: 'Exportar Arquivos',
exportFilesDescription: 'Baixe todos os seus projetos e arquivos como um arquivo ZIP. Isso inclui todos os arquivos de projeto, configurações e dados armazenados localmente.',
exportAllFiles: 'Exportar Todos os Arquivos',
exporting: 'Exportando...',
clearAllData: 'Limpar Todos os Dados',
clearAllDataDescription: 'Exclua permanentemente todos os dados locais, incluindo projetos, configurações e informações em cache. Esta ação não pode ser desfeita.',
clearing: 'Limpando...',
areYouSure: 'Você tem certeza absoluta?',
clearDataWarning: 'Esta ação excluirá permanentemente todos os dados locais deste navegador, incluindo:',
allProjects: 'Todos os projetos e seus arquivos',
aiSettingsAndKeys: 'Configurações de IA e chaves de API',
gitCredentialsSettings: 'Credenciais e configurações do Git',
userPreferences: 'Preferências do usuário e temas',
cachedData: 'Dados em cache e informações de sessão',
actionCannotBeUndone: 'Esta ação não pode ser desfeita. Considere exportar seus arquivos primeiro.',
yesClearAllData: 'Sim, limpar todos os dados',
used: 'Usado',
available: 'Disponível',
usagePercentage: '{{percentage}}% usado',
usageUnavailable: 'Porcentagem de uso indisponível',
loadingStorageInfo: 'Carregando informações de armazenamento...',
filesExportedSuccessfully: 'Arquivos exportados com sucesso',
filesExportedDescription: 'Seus arquivos de projeto foram baixados como um arquivo zip.',
failedToExportFiles: 'Falha ao exportar arquivos',
dataClearedSuccessfully: 'Dados limpos com sucesso',
dataClearedDescription: 'Todos os dados locais foram removidos. Redirecionando para a página inicial...',
failedToClearData: 'Falha ao limpar dados',
// About Settings
aboutShakespeare: 'Sobre o Shakespeare',
aboutShakespeareDescription: 'Informações sobre o Shakespeare.',
sourceCode: 'Código-fonte',
viewOnGitLab: 'Ver no GitLab',
description: 'Descrição',
license: 'Licença',
loadingLicense: 'Carregando licença...',
failedToLoadLicense: 'Falha ao carregar licença',
// 404 Page
pageNotFound: 'Ops! Página não encontrada',
returnToHome: 'Voltar ao Início',
// Model Selector
selectOrEnterModel: 'Selecione ou digite um modelo...',
searchModels: 'Buscar modelos...',
enterCustomModel: 'Digite modelo personalizado...',
manageProviders: 'Gerenciar provedores...',
noModelsFound: 'Nenhum modelo encontrado.',
tryCustomModel: 'Tente usar um modelo personalizado.',
recentlyUsed: 'Usados Recentemente',
errorLoadingModels: 'Erro ao Carregar Modelos',
// Context and Cost
contextUsage: 'Uso de contexto: {{tokens}} / {{total}} tokens ({{percentage}}%)',
totalCostSession: 'Custo total para esta sessão de chat',
// File Status
added: 'adicionado',
deleted: 'excluído',
modified: 'modificado',
staged: 'preparado',
untracked: 'não rastreado',
// Settings Layout
toggleSidebar: 'Alternar barra lateral',
openSidebar: 'Abrir barra lateral',
// Nostr Settings
nostrSettingsDescriptionLong: 'Configure suas configurações de conexão Nostr e preferências de relay.',
nostrAccounts: 'Contas Nostr',
noAccountsLoggedIn: 'Nenhuma conta logada. Adicione uma conta para começar.',
createAccount: 'Criar Conta',
addExistingAccount: 'Adicionar Conta Existente',
addAccount: 'Adicionar Conta',
relayConfiguration: 'Configuração de Relay',
selectedRelay: 'Relay Selecionado',
// Clone Page
cloneGitRepository: 'Clone um repositório Git para seu workspace Shakespeare',
pleaseEnterRepositoryUrl: 'Por favor, digite uma URL do repositório',
pleaseEnterValidGitUrl: 'Por favor, digite uma URL válida de repositório Git ou URI de clone Nostr (ex: nostr://npub.../nome-repo)',
cloningRepository: 'Clonando Repositório...',
nostrRepositoryImportedSuccessfully: 'Repositório Nostr importado com sucesso',
repositoryClonedFromNostr: '"{{repoName}}" foi clonado do Nostr e está pronto para desenvolvimento.',
repositoryImportedSuccessfully: 'Repositório importado com sucesso',
repositoryClonedReady: '"{{repoName}}" foi clonado e está pronto para desenvolvimento.',
failedToImportRepository: 'Falha ao importar repositório',
repositoryNotFoundOnNostr: 'Repositório não encontrado na rede Nostr. Verifique a URI e tente novamente.',
noCloneUrlsFound: 'Anúncio do repositório encontrado, mas nenhuma URL de clone disponível.',
allCloneAttemptsFailed: 'Repositório encontrado, mas todas as URLs de clone falharam. O repositório pode estar indisponível.',
repositoryNotFound: 'Repositório não encontrado. Verifique a URL e tente novamente.',
accessDenied: 'Acesso negado. O repositório pode ser privado ou requer autenticação.',
networkError: 'Erro de rede. Verifique sua conexão e tente novamente.',
}
},
zh: {
translation: {
// Navigation and Layout
preferences: '偏好设置',
settings: '设置',
backToSettings: '返回设置',
help: '帮助',
anonymous: '匿名',
// Authentication
logIn: '登录',
signUp: '注册',
// Preferences Page
preferencesDescription: '管理您的应用程序偏好设置和外观设置。',
// Theme Section
theme: '主题',
themeDescription: '选择浅色、深色或系统主题偏好。',
// Language Section
language: '语言',
languageDescription: '选择您的界面首选语言。',
// Language Options
english: 'English',
portuguese: 'Português',
chinese: '中文',
systemLanguage: '系统',
// Theme Options
light: '浅色',
dark: '深色',
system: '系统',
// Common UI Elements
save: '保存',
cancel: '取消',
close: '关闭',
open: '打开',
edit: '编辑',
delete: '删除',
create: '创建',
update: '更新',
loading: '加载中...',
error: '错误',
success: '成功',
warning: '警告',
info: '信息',
add: '添加',
remove: '移除',
retry: '重试',
// Shakespeare Main Page
buildNostrApps: '使用AI构建Nostr应用',
whatToBuild: '您想构建什么?',
createProject: '创建项目',
generating: '生成中...',
creating: '创建中...',
chooseModel: '选择模型...',
selectModelToDescribe: "请在下方选择一个模型,然后描述您想要构建的内容...",
examplePrompt: "例如:为当地农民创建一个农业设备市场,用于买卖拖拉机、工具和用品...",
// Settings Page
settingsDescription: '管理您的应用程序设置和偏好。',
aiSettings: 'AI设置',
aiSettingsDescription: '配置AI提供商和API密钥',
gitSettings: 'Git设置',
gitSettingsDescription: '配置HTTP身份验证的Git凭据',
nostrSettings: 'Nostr设置',
nostrSettingsDescription: '配置中继连接和Nostr偏好',
dataSettings: '数据',
dataSettingsDescription: '导出文件和管理本地数据',
aboutShakespeareSettings: '关于Shakespeare',
aboutShakespeareSettingsDescription: '关于Shakespeare的信息',
// Project Sidebar
newProject: '新项目',
importRepository: '导入仓库',
noProjectsYet: '还没有项目',
createFirstProject: '创建您的第一个项目开始使用',
closeSidebar: '关闭侧边栏',
collapseSidebar: '折叠侧边栏',
// Chat Interface
welcomeToShakespeare: '欢迎使用Shakespeare',
aiAssistantReady: '您的AI驱动开发助手已准备好帮助您构建、编辑和增强您的项目。',
askMeFeatures: '💡 请我添加新功能',
requestEdits: '📝 请求文件编辑和改进',
getHelp: '🔧 获得调试和优化帮助',
buildDeploy: '🚀 构建和部署您的项目',
aiNotConfigured: 'AI助手未配置',
configureAI: '请配置您的AI设置以开始使用AI助手构建。',
useMenuForAI: '使用顶部栏中的菜单访问AI设置。',
askToAddFeatures: '请我添加功能、编辑文件或构建您的项目...',
selectModelFirst: '请先选择一个模型开始聊天...',
sendMessage: '发送消息',
stopGeneration: '停止生成',
running: '运行中',
// Project View Navigation
chat: '聊天',
preview: '预览',
code: '代码',
// Preview Pane
projectPreview: '项目预览',
buildProjectToSeePreview: '构建您的项目以在此处查看预览',
fileExplorer: '文件浏览器',
fileEditor: '文件编辑器',
selectFileFromExplorer: '从浏览器中选择一个文件进行编辑',
openFileExplorer: '打开文件浏览器',
// File Editor
unsavedChanges: '未保存的更改',
saving: '保存中...',
languageLabel: '语言',
// File Tree
searchFiles: '搜索文件...',
noFilesFound: '未找到文件',
noFilesFoundSearch: '未找到与您搜索匹配的文件',
// Git Dialog
gitRepositoryStatus: 'Git仓库状态',
repositoryStatusDescription: '查看仓库状态并与远程仓库同步',
repositoryInformation: '仓库信息',
currentBranch: '当前分支',
totalCommits: '总提交数',
latestCommit: '最新提交',
remotes: '远程仓库',
notGitRepository: '不是Git仓库',
gitAuthentication: '身份验证',
credentialsDescription: '推送/拉取操作的凭据',
configured: '已配置',
noCredentials: '无凭据',
noCredentialsWarning: '未为{{provider}}配置凭据。私有仓库的推送/拉取操作可能失败。',
configureCredentials: '配置凭据',
syncStatus: '同步状态',
pull: '拉取',
push: '推送',
pulling: '拉取中...',
pushing: '推送中...',
upToDate: '已是最新',
commitsAhead: '领先{{count}}个提交',
commitsBehind: '落后{{count}}个提交',
uncommittedChanges: '{{count}}个未提交的更改',
noRemoteConfigured: '未配置远程仓库',
workingDirectoryChanges: '工作目录更改',
filesWithChanges: '{{count}}个文件有更改',
workingDirectoryClean: '工作目录干净',
noUncommittedChanges: '无未提交的更改',
cannotPush: '无法推送',
cannotPull: '无法拉取',
notGitRepoOrBranch: '不是git仓库或无当前分支',
noRemoteRepositories: '未配置远程仓库',
nothingToPush: '无内容可推送',
noCommitsAhead: '没有领先远程的提交。请先提交您的更改。',
pushSuccessful: '推送成功',
pushFailed: '推送失败',
pullSuccessful: '拉取成功',
pullFailed: '拉取失败',
// AI Settings
aiSettingsDescriptionLong: '通过添加您的API密钥来配置AI提供商。设置会自动保存并存储在您的浏览器本地。',
configuredProviders: '已配置的提供商',
addProvider: '添加提供商',
getApiKey: '获取API密钥',
getToken: '获取令牌',
enterApiKey: '输入您的API密钥',
enterToken: '输入您的令牌',
enterCashuToken: '输入Cashu令牌',
addCustomProvider: '添加自定义提供商',
providerName: '提供商名称',
baseUrl: '基础URL',
apiKey: 'API密钥',
authentication: '身份验证',
addCustomProviderButton: '添加自定义提供商',
providerExists: '此名称的提供商已存在',
custom: '自定义',
connecting: '连接中...',
connectToGitHub: '连接到GitHub',
loginToNostrRequired: '登录Nostr以使用此提供商',
goToNostrSettings: '前往Nostr设置',
// Git Settings
gitSettingsDescriptionLong: '配置HTTP身份验证的Git凭据。设置会自动保存并存储在您的浏览器本地。',
configuredCredentials: '已配置的凭据',
origin: '源',
username: '用户名',
password: '密码',
enterPassword: '输入您的密码/令牌',
credentialsExist: '此源的凭据已存在',
corsProxy: 'CORS代理',
corsProxyDescription: '用于所有与远程仓库的Git操作的CORS代理服务器。浏览器基于的Git操作必需。',
// Data Settings
dataSettingsDescriptionLong: '导出文件和管理本地数据。',
exportFiles: '导出文件',
exportFilesDescription: '将您的所有项目和文件下载为ZIP存档。这包括所有项目文件、设置和本地存储的数据。',
exportAllFiles: '导出所有文件',
exporting: '导出中...',
clearAllData: '清除所有数据',
clearAllDataDescription: '永久删除所有本地数据,包括项目、设置和缓存信息。此操作无法撤销。',
clearing: '清除中...',
areYouSure: '您确定吗?',
clearDataWarning: '此操作将永久删除此浏览器的所有本地数据,包括:',
allProjects: '所有项目及其文件',
aiSettingsAndKeys: 'AI设置和API密钥',
gitCredentialsSettings: 'Git凭据和设置',
userPreferences: '用户偏好和主题',
cachedData: '缓存数据和会话信息',
actionCannotBeUndone: '此操作无法撤销。请考虑先导出您的文件。',
yesClearAllData: '是的,清除所有数据',
used: '已使用',
available: '可用',
usagePercentage: '已使用{{percentage}}%',
usageUnavailable: '使用百分比不可用',
loadingStorageInfo: '加载存储信息...',
filesExportedSuccessfully: '文件导出成功',
filesExportedDescription: '您的项目文件已下载为zip文件。',
failedToExportFiles: '导出文件失败',
dataClearedSuccessfully: '数据清除成功',
dataClearedDescription: '所有本地数据已删除。正在重定向到主页...',
failedToClearData: '清除数据失败',
// About Settings
aboutShakespeare: '关于Shakespeare',
aboutShakespeareDescription: '关于Shakespeare的信息。',
sourceCode: '源代码',
viewOnGitLab: '在GitLab上查看',
description: '描述',
license: '许可证',
loadingLicense: '加载许可证中...',
failedToLoadLicense: '加载许可证失败',
// 404 Page
pageNotFound: '哎呀!页面未找到',
returnToHome: '返回首页',
// Model Selector
selectOrEnterModel: '选择或输入模型...',
searchModels: '搜索模型...',
enterCustomModel: '输入自定义模型...',
manageProviders: '管理提供商...',
noModelsFound: '未找到模型。',
tryCustomModel: '尝试使用自定义模型。',
recentlyUsed: '最近使用',
errorLoadingModels: '加载模型时出错',
// Context and Cost
contextUsage: '上下文使用:{{tokens}} / {{total}} 令牌 ({{percentage}}%)',
totalCostSession: '此聊天会话的总费用',
// File Status
added: '已添加',
deleted: '已删除',
modified: '已修改',
staged: '已暂存',
untracked: '未跟踪',
// Settings Layout
toggleSidebar: '切换侧边栏',
openSidebar: '打开侧边栏',
// Nostr Settings
nostrSettingsDescriptionLong: '配置您的Nostr连接设置和中继偏好。',
nostrAccounts: 'Nostr账户',
noAccountsLoggedIn: '没有账户登录。添加账户开始使用。',
createAccount: '创建账户',
addExistingAccount: '添加现有账户',
addAccount: '添加账户',
relayConfiguration: '中继配置',
selectedRelay: '选定的中继',
// Clone Page
cloneGitRepository: '将Git仓库克隆到您的Shakespeare工作空间',
pleaseEnterRepositoryUrl: '请输入仓库URL',
pleaseEnterValidGitUrl: '请输入有效的Git仓库URL或Nostr克隆URI(例如:nostr://npub.../仓库名)',
cloningRepository: '正在克隆仓库...',
nostrRepositoryImportedSuccessfully: 'Nostr仓库导入成功',
repositoryClonedFromNostr: '"{{repoName}}"已从Nostr克隆并准备好进行开发。',
repositoryImportedSuccessfully: '仓库导入成功',
repositoryClonedReady: '"{{repoName}}"已克隆并准备好进行开发。',
failedToImportRepository: '导入仓库失败',
repositoryNotFoundOnNostr: '在Nostr网络上未找到仓库。请检查URI并重试。',
noCloneUrlsFound: '找到仓库公告但没有可用的克隆URL。',
allCloneAttemptsFailed: '找到仓库但所有克隆URL都失败了。仓库可能不可用。',
repositoryNotFound: '未找到仓库。请检查URL并重试。',
accessDenied: '访问被拒绝。仓库可能是私有的或需要身份验证。',
networkError: '网络错误。请检查您的连接并重试。',
}
}
};
// Initialize i18next
i18n
.use(initReactI18next)
.init({
resources,
fallbackLng: 'en',
interpolation: {
escapeValue: false, // React already escapes values
},
react: {
useSuspense: false, // Disable suspense for better compatibility
}
});
export default i18n;
+3
View File
@@ -3,6 +3,9 @@ import { createRoot } from 'react-dom/client';
// Import polyfills first
import './lib/polyfills.ts';
// Import i18n configuration
import './lib/i18n';
import App from './App.tsx';
import './index.css';
+99
View File
@@ -0,0 +1,99 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import type React from 'react';
import { TestApp } from '@/test/TestApp';
import { AISettings } from './AISettings';
// Mock the hooks
vi.mock('@/hooks/useCurrentUser', () => ({
useCurrentUser: vi.fn(),
}));
vi.mock('@/hooks/useAISettings', () => ({
useAISettings: vi.fn(() => ({
settings: { providers: {} },
addProvider: vi.fn(),
removeProvider: vi.fn(),
updateProvider: vi.fn(),
})),
}));
vi.mock('@/hooks/useIsMobile', () => ({
useIsMobile: vi.fn(() => false),
}));
vi.mock('react-router-dom', async () => {
const actual = await vi.importActual('react-router-dom');
return {
...actual,
useNavigate: vi.fn(() => vi.fn()),
Link: ({ children, to, ...props }: { children: React.ReactNode; to: string; [key: string]: unknown }) => (
<a href={to} {...props}>
{children}
</a>
),
};
});
describe('AISettings', () => {
it('shows Nostr login requirement for Nostr presets when user is not logged in', async () => {
const { useCurrentUser } = await import('@/hooks/useCurrentUser');
vi.mocked(useCurrentUser).mockReturnValue({
user: undefined,
users: [],
});
render(
<TestApp>
<AISettings />
</TestApp>
);
// Should show login requirement for Shakespeare AI (Nostr preset)
expect(screen.getByText('Log in to Nostr to use this provider')).toBeInTheDocument();
expect(screen.getByText('Go to Nostr Settings')).toBeInTheDocument();
});
it('shows Add button for Nostr presets when user is logged in', async () => {
const { useCurrentUser } = await import('@/hooks/useCurrentUser');
vi.mocked(useCurrentUser).mockReturnValue({
user: { pubkey: 'test-pubkey' } as NonNullable<ReturnType<typeof useCurrentUser>['user']>,
users: [],
});
render(
<TestApp>
<AISettings />
</TestApp>
);
// Should show Add button for Shakespeare AI (Nostr preset)
const addButtons = screen.getAllByText('Add');
expect(addButtons.length).toBeGreaterThan(0);
// Should not show login requirement
expect(screen.queryByText('Log in to Nostr to use this provider')).not.toBeInTheDocument();
});
it('shows normal input and Add button for non-Nostr presets regardless of login status', async () => {
const { useCurrentUser } = await import('@/hooks/useCurrentUser');
vi.mocked(useCurrentUser).mockReturnValue({
user: undefined,
users: [],
});
render(
<TestApp>
<AISettings />
</TestApp>
);
// Should show API key inputs for non-Nostr presets like OpenAI
expect(screen.getByText('OpenAI')).toBeInTheDocument();
expect(screen.getByText('OpenRouter')).toBeInTheDocument();
// Should show Add buttons for non-Nostr presets
const addButtons = screen.getAllByText('Add');
expect(addButtons.length).toBeGreaterThan(0);
});
});
+138 -85
View File
@@ -1,15 +1,19 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Check, Bot, ArrowLeft, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { PasswordInput } from '@/components/ui/password-input';
import { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';
import { Badge } from '@/components/ui/badge';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { CreditsBadge } from '@/components/CreditsBadge';
import { CreditsDialog } from '@/components/CreditsDialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useAISettings } from '@/hooks/useAISettings';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useNavigate } from 'react-router-dom';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNavigate, Link } from 'react-router-dom';
import type { AIConnection } from '@/contexts/AISettingsContext';
interface PresetProvider {
@@ -22,9 +26,9 @@ interface PresetProvider {
const PRESET_PROVIDERS: PresetProvider[] = [
{
id: "lemon",
name: "Lemon",
baseURL: "https://internal-lucienne-nublar-6932a6f0.koyeb.app/v1",
id: "shakespeare",
name: "Shakespeare AI",
baseURL: "https://ai.shakespeare.diy/v1",
nostr: true,
},
{
@@ -78,14 +82,17 @@ const PRESET_PROVIDERS: PresetProvider[] = [
];
export function AISettings() {
const { t } = useTranslation();
const { settings, addProvider, removeProvider, updateProvider } = useAISettings();
const isMobile = useIsMobile();
const navigate = useNavigate();
const { user } = useCurrentUser();
const [customProviderName, setCustomProviderName] = useState('');
const [customBaseURL, setCustomBaseURL] = useState('');
const [customApiKey, setCustomApiKey] = useState('');
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr'>('api-key');
const [presetApiKeys, setPresetApiKeys] = useState<Record<string, string>>({});
const [activeCreditsDialog, setActiveCreditsDialog] = useState<string | null>(null);
const handleAddPresetProvider = (preset: PresetProvider) => {
const apiKey = presetApiKeys[preset.id] as string | undefined;
@@ -139,6 +146,14 @@ export function AISettings() {
updateProvider(name, connection);
};
const handleOpenCreditsDialog = (providerId: string) => {
setActiveCreditsDialog(providerId);
};
const handleCloseCreditsDialog = () => {
setActiveCreditsDialog(null);
};
const configuredProviderIds = Object.keys(settings.providers);
const availablePresets = PRESET_PROVIDERS.filter(preset => !configuredProviderIds.includes(preset.id));
@@ -153,15 +168,15 @@ export function AISettings() {
className="h-8 w-auto px-2 -ml-2"
>
<ArrowLeft className="h-4 w-4 mr-2" />
Back to Settings
{t('backToSettings')}
</Button>
<div className="space-y-2">
<h1 className="text-2xl font-bold flex items-center gap-3">
<Bot className="h-6 w-6 text-primary" />
AI Settings
{t('aiSettings')}
</h1>
<p className="text-muted-foreground">
Configure AI providers by adding your API keys. Settings are automatically saved and stored locally in your browser.
{t('aiSettingsDescriptionLong')}
</p>
</div>
</div>
@@ -171,10 +186,10 @@ export function AISettings() {
<div className="space-y-2">
<h1 className="text-2xl font-bold flex items-center gap-3">
<Bot className="h-6 w-6 text-primary" />
AI Settings
{t('aiSettings')}
</h1>
<p className="text-muted-foreground">
Configure AI providers by adding your API keys. Settings are automatically saved and stored locally in your browser.
{t('aiSettingsDescriptionLong')}
</p>
</div>
)}
@@ -183,12 +198,11 @@ export function AISettings() {
{/* Configured Providers */}
{configuredProviderIds.length > 0 && (
<div className="space-y-3">
<h4 className="text-sm font-medium">Configured Providers</h4>
<h4 className="text-sm font-medium">{t('configuredProviders')}</h4>
<Accordion type="multiple" className="w-full space-y-2">
{configuredProviderIds.map((providerId) => {
const preset = PRESET_PROVIDERS.find(p => p.id === providerId);
const provider = settings.providers[providerId];
const isCustom = !preset;
return (
<AccordionItem key={providerId} value={providerId} className="border rounded-lg">
@@ -198,25 +212,31 @@ export function AISettings() {
<span className="font-medium">
{preset?.name || providerId}
</span>
{isCustom && <Badge variant="outline">Custom</Badge>}
</div>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
handleRemoveProvider(providerId);
}}
className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive hover:bg-transparent"
>
<Trash2 className="h-4 w-4" />
</Button>
<div className="flex items-center gap-2">
<CreditsBadge
providerId={providerId}
connection={provider}
onOpenDialog={() => handleOpenCreditsDialog(providerId)}
/>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
handleRemoveProvider(providerId);
}}
className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive hover:bg-transparent"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor={`${providerId}-baseURL`}>Base URL</Label>
<Label htmlFor={`${providerId}-baseURL`}>{t('baseUrl')}</Label>
<Input
id={`${providerId}-baseURL`}
placeholder="https://api.example.com/v1"
@@ -225,7 +245,7 @@ export function AISettings() {
/>
</div>
<div className="grid gap-2">
<Label htmlFor={`${providerId}-auth`}>Authentication</Label>
<Label htmlFor={`${providerId}-auth`}>{t('authentication')}</Label>
<Select
value={provider?.nostr ? 'nostr' : 'api-key'}
onValueChange={(value: 'api-key' | 'nostr') => handleUpdateProvider(providerId, {
@@ -237,18 +257,17 @@ export function AISettings() {
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="api-key">API Key</SelectItem>
<SelectItem value="api-key">{t('apiKey')}</SelectItem>
<SelectItem value="nostr">Nostr</SelectItem>
</SelectContent>
</Select>
</div>
{!provider?.nostr && (
<div className="grid gap-2">
<Label htmlFor={`${providerId}-apiKey`}>API Key</Label>
<Input
<Label htmlFor={`${providerId}-apiKey`}>{t('apiKey')}</Label>
<PasswordInput
id={`${providerId}-apiKey`}
type="password"
placeholder="Enter your API key"
placeholder={t('enterApiKey')}
value={provider?.apiKey || ''}
onChange={(e) => handleUpdateProvider(providerId, { apiKey: e.target.value })}
/>
@@ -268,50 +287,72 @@ export function AISettings() {
{/* Available Preset Providers */}
{availablePresets.length > 0 && (
<div className="space-y-3">
<h4 className="text-sm font-medium">Add Provider</h4>
<h4 className="text-sm font-medium">{t('addProvider')}</h4>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{availablePresets.map((preset) => (
<div key={preset.id} className="border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between">
<h5 className="font-medium">{preset.name}</h5>
{(preset.apiKeysURL && preset.id !== "routstr") && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.apiKeysURL, '_blank')}
>
Get API key
</button>
{availablePresets.map((preset) => {
const isNostrPreset = preset.nostr;
const isLoggedIntoNostr = !!user;
const showNostrLoginRequired = isNostrPreset && !isLoggedIntoNostr;
return (
<div key={preset.id} className="border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between">
<h5 className="font-medium">{preset.name}</h5>
{(preset.apiKeysURL && preset.id !== "routstr") && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.apiKeysURL, '_blank')}
>
{t('getApiKey')}
</button>
)}
</div>
{showNostrLoginRequired ? (
<div className="space-y-2">
<p className="text-sm text-muted-foreground">
{t('loginToNostrRequired')}
</p>
<Button
asChild
className="w-full"
>
<Link to="/settings/nostr">
{t('goToNostrSettings')}
</Link>
</Button>
</div>
) : (
<div className="flex gap-2">
{!preset.nostr && (
<PasswordInput
placeholder={preset.id === "routstr" ? t('enterCashuToken') : t('enterApiKey')}
className="flex-1"
value={presetApiKeys[preset.id] || ''}
onChange={(e) => setPresetApiKeys(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim()) {
handleAddPresetProvider(preset);
}
}}
/>
)}
<Button
onClick={() => handleAddPresetProvider(preset)}
disabled={!!preset.apiKeysURL && !presetApiKeys[preset.id]?.trim()}
className={preset.nostr ? "w-full" : "h-10 px-4 ml-auto"}
>
{t('add')}
</Button>
</div>
)}
</div>
<div className="flex gap-2">
{!preset.nostr && (
<Input
placeholder={preset.id === "routstr" ? "Enter a Cashu token" : "Enter your API key"}
type="password"
className="flex-1"
value={presetApiKeys[preset.id] || ''}
onChange={(e) => setPresetApiKeys(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim()) {
handleAddPresetProvider(preset);
}
}}
/>
)}
<Button
onClick={() => handleAddPresetProvider(preset)}
disabled={!!preset.apiKeysURL && !presetApiKeys[preset.id]?.trim()}
size="sm"
>
Add
</Button>
</div>
</div>
))}
);
})}
</div>
</div>
)}
@@ -323,12 +364,12 @@ export function AISettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="custom-provider" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">Add Custom Provider</h4>
<h4 className="text-sm font-medium">{t('addCustomProvider')}</h4>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor="custom-name">Provider Name</Label>
<Label htmlFor="custom-name">{t('providerName')}</Label>
<Input
id="custom-name"
placeholder="e.g., my-custom-api"
@@ -337,7 +378,7 @@ export function AISettings() {
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-baseurl">Base URL</Label>
<Label htmlFor="custom-baseurl">{t('baseUrl')}</Label>
<Input
id="custom-baseurl"
placeholder="https://api.example.com/v1"
@@ -346,7 +387,7 @@ export function AISettings() {
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-auth">Authentication</Label>
<Label htmlFor="custom-auth">{t('authentication')}</Label>
<Select
value={customAuthMethod}
onValueChange={(value: 'api-key' | 'nostr') => {
@@ -360,18 +401,17 @@ export function AISettings() {
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="api-key">API Key</SelectItem>
<SelectItem value="api-key">{t('apiKey')}</SelectItem>
<SelectItem value="nostr">Nostr</SelectItem>
</SelectContent>
</Select>
</div>
{customAuthMethod === 'api-key' && (
<div className="grid gap-2">
<Label htmlFor="custom-apikey">API Key</Label>
<Input
<Label htmlFor="custom-apikey">{t('apiKey')}</Label>
<PasswordInput
id="custom-apikey"
type="password"
placeholder="Enter your API key (optional)"
placeholder={t('enterApiKey') + ' (optional)'}
value={customApiKey}
onChange={(e) => setCustomApiKey(e.target.value)}
/>
@@ -384,15 +424,14 @@ export function AISettings() {
!customBaseURL.trim() ||
customProviderName.trim() in settings.providers
}
size="sm"
className="gap-2"
className="gap-2 ml-auto"
>
<Check className="h-4 w-4" />
Add Custom Provider
{t('addCustomProviderButton')}
</Button>
{customProviderName.trim() in settings.providers && (
<p className="text-sm text-destructive">
Provider with this name already exists
{t('providerExists')}
</p>
)}
</div>
@@ -401,6 +440,20 @@ export function AISettings() {
</Accordion>
</div>
</div>
{/* Render credits dialog outside of accordion structure */}
{activeCreditsDialog && (
<CreditsDialog
open={true}
onOpenChange={(open) => {
if (!open) {
handleCloseCreditsDialog();
}
}}
providerId={activeCreditsDialog}
connection={settings.providers[activeCreditsDialog]}
/>
)}
</div>
);
}
+69
View File
@@ -0,0 +1,69 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { AboutSettings } from './AboutSettings';
// Mock fetch
global.fetch = vi.fn();
describe('AboutSettings', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('renders about settings page with project information', () => {
render(
<TestApp>
<AboutSettings />
</TestApp>
);
expect(screen.getByText('About Shakespeare')).toBeInTheDocument();
expect(screen.getByText(/Information about Shakespeare/)).toBeInTheDocument();
expect(screen.getByText('Source Code')).toBeInTheDocument();
expect(screen.getByText('View on GitLab')).toBeInTheDocument();
});
it('fetches and displays license text', async () => {
const mockLicense = 'MIT License\n\nCopyright (c) 2024 Shakespeare';
const mockFetch = global.fetch as ReturnType<typeof vi.fn>;
mockFetch.mockResolvedValueOnce({
ok: true,
text: () => Promise.resolve(mockLicense),
} as Response);
render(
<TestApp>
<AboutSettings />
</TestApp>
);
// Initially shows loading
expect(screen.getByText('Loading license...')).toBeInTheDocument();
// Wait for license to load
await waitFor(() => {
expect(screen.getByText(/MIT License/)).toBeInTheDocument();
expect(screen.getByText(/Copyright \(c\) 2024 Shakespeare/)).toBeInTheDocument();
});
// Verify fetch was called with correct URL
expect(global.fetch).toHaveBeenCalledWith('/LICENSE.txt');
});
it('shows error when license fetch fails', async () => {
const mockFetch = global.fetch as ReturnType<typeof vi.fn>;
mockFetch.mockRejectedValueOnce(new Error('Network error'));
render(
<TestApp>
<AboutSettings />
</TestApp>
);
// Wait for error to appear
await waitFor(() => {
expect(screen.getByText(/Failed to load license/)).toBeInTheDocument();
});
});
});
+117
View File
@@ -0,0 +1,117 @@
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Info, ExternalLink, Loader2, AlertTriangle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Alert, AlertDescription } from '@/components/ui/alert';
export function AboutSettings() {
const { t } = useTranslation();
const [license, setLicense] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const fetchLicense = async () => {
try {
setIsLoading(true);
setError(null);
const response = await fetch('/LICENSE.txt');
if (!response.ok) {
throw new Error(`Failed to fetch license: ${response.status} ${response.statusText}`);
}
const licenseText = await response.text();
setLicense(licenseText);
} catch (err) {
console.error('Failed to fetch license:', err);
setError(err instanceof Error ? err.message : 'Failed to fetch license');
} finally {
setIsLoading(false);
}
};
fetchLicense();
}, []);
return (
<div className="p-6 space-y-6">
<div className="space-y-2">
<h1 className="text-2xl font-bold flex items-center gap-3">
<Info className="h-6 w-6 text-primary" />
{t('aboutShakespeare')}
</h1>
<p className="text-muted-foreground">
{t('aboutShakespeareDescription')}
</p>
</div>
<div className="space-y-4">
{/* Project Information */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Info className="h-5 w-5" />
{t('sourceCode')}
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div>
<Button
variant="outline"
asChild
className="w-full sm:w-auto"
>
<a
href="https://gitlab.com/soapbox-pub/act2"
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-2"
>
<ExternalLink className="h-4 w-4" />
{t('viewOnGitLab')}
</a>
</Button>
</div>
</CardContent>
</Card>
{/* License */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Info className="h-5 w-5" />
{t('license')}
</CardTitle>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="flex items-center gap-2 text-muted-foreground py-4">
<Loader2 className="h-4 w-4 animate-spin" />
<span className="text-sm">{t('loadingLicense')}</span>
</div>
) : error ? (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
{t('failedToLoadLicense')}: {error}
</AlertDescription>
</Alert>
) : license ? (
<ScrollArea className="h-96 w-full rounded-md border p-4">
<pre className="text-xs font-mono whitespace-pre-wrap break-words">
{license}
</pre>
</ScrollArea>
) : null}
</CardContent>
</Card>
</div>
</div>
);
}
export default AboutSettings;
+61 -67
View File
@@ -1,10 +1,9 @@
import { useState, useEffect, useCallback } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { AppLayout } from '@/components/AppLayout';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { GitBranch, Loader2, AlertCircle } from 'lucide-react';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useToast } from '@/hooks/useToast';
@@ -22,6 +21,7 @@ interface NostrCloneUri {
}
export default function Clone() {
const { t } = useTranslation();
const [repoUrl, setRepoUrl] = useState('');
const [isCloning, setIsCloning] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -32,8 +32,8 @@ export default function Clone() {
const { nostr } = useNostr();
useSeoMeta({
title: 'Import Repository - Shakespeare',
description: 'Import a Git repository into your Shakespeare workspace',
title: `${t('importRepository')} - Shakespeare`,
description: t('cloneGitRepository'),
});
const extractRepoName = (url: string): string => {
@@ -203,14 +203,14 @@ export default function Clone() {
const handleClone = useCallback(async (url?: string) => {
const targetUrl = url || repoUrl;
if (!targetUrl.trim()) {
setError('Please enter a repository URL');
setError(t('pleaseEnterRepositoryUrl'));
return;
}
if (!validateGitUrl(targetUrl)) {
setError('Please enter a valid Git repository URL or Nostr clone URI (e.g., nostr://npub.../repo-name)');
setError(t('pleaseEnterValidGitUrl'));
return;
}
@@ -238,8 +238,8 @@ export default function Clone() {
const project = await tryCloneUrls(cloneUrls, repoName);
toast({
title: "Nostr repository imported successfully",
description: `"${repoName}" has been cloned from Nostr and is ready for development.`,
title: t('nostrRepositoryImportedSuccessfully'),
description: t('repositoryClonedFromNostr', { repoName }),
});
// Navigate to the new project
@@ -250,8 +250,8 @@ export default function Clone() {
const project = await projectsManager.cloneProject(repoName, targetUrl.trim());
toast({
title: "Repository imported successfully",
description: `"${repoName}" has been cloned and is ready for development.`,
title: t('repositoryImportedSuccessfully'),
description: t('repositoryClonedReady', { repoName }),
});
// Navigate to the new project
@@ -260,20 +260,20 @@ export default function Clone() {
} catch (error) {
console.error('Failed to clone repository:', error);
let errorMessage = 'Failed to clone repository';
let errorMessage = t('failedToImportRepository');
if (error instanceof Error) {
if (error.message.includes('Repository not found on Nostr network')) {
errorMessage = 'Repository not found on Nostr network. Please check the URI and try again.';
errorMessage = t('repositoryNotFoundOnNostr');
} else if (error.message.includes('No clone URLs found')) {
errorMessage = 'Repository announcement found but no clone URLs available.';
errorMessage = t('noCloneUrlsFound');
} else if (error.message.includes('All clone attempts failed')) {
errorMessage = 'Repository found but all clone URLs failed. The repository may be unavailable.';
errorMessage = t('allCloneAttemptsFailed');
} else if (error.message.includes('404') || error.message.includes('not found')) {
errorMessage = 'Repository not found. Please check the URL and try again.';
errorMessage = t('repositoryNotFound');
} else if (error.message.includes('403') || error.message.includes('forbidden')) {
errorMessage = 'Access denied. The repository may be private or require authentication.';
errorMessage = t('accessDenied');
} else if (error.message.includes('network') || error.message.includes('fetch')) {
errorMessage = 'Network error. Please check your connection and try again.';
errorMessage = t('networkError');
} else {
errorMessage = error.message;
}
@@ -282,14 +282,14 @@ export default function Clone() {
setError(errorMessage);
toast({
title: "Failed to import repository",
title: t('failedToImportRepository'),
description: errorMessage,
variant: "destructive",
});
} finally {
setIsCloning(false);
}
}, [fetchNostrRepository, navigate, projectsManager, repoUrl, toast, tryCloneUrls, validateGitUrl]);
}, [fetchNostrRepository, navigate, projectsManager, repoUrl, t, toast, tryCloneUrls, validateGitUrl]);
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !isCloning) {
@@ -303,73 +303,67 @@ export default function Clone() {
if (urlParam) {
const decodedUrl = decodeURIComponent(urlParam);
setRepoUrl(decodedUrl);
// Automatically start the clone process with the URL directly
handleClone(decodedUrl);
}
}, [handleClone, searchParams]);
return (
<AppLayout title="Import Repository">
<AppLayout title={t('importRepository')}>
<div className="max-w-2xl mx-auto">
<div className="text-center mb-8">
<div className="text-4xl mb-4">
<GitBranch className="h-12 w-12 mx-auto text-primary" />
</div>
<h1 className="text-3xl font-bold mb-3 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Import Repository
{t('importRepository')}
</h1>
<p className="text-lg text-muted-foreground">
Clone a Git repository into your Shakespeare workspace
{t('cloneGitRepository')}
</p>
</div>
<Card className="bg-gradient-to-br from-card to-card/50 border-primary/20 shadow-lg">
<CardContent className="space-y-4 p-6">
<div className="space-y-2">
<Label htmlFor="repo-url">Repository URL</Label>
<Input
id="repo-url"
type="text"
placeholder="https://github.com/username/repository.git"
value={repoUrl}
onChange={(e) => {
setRepoUrl(e.target.value);
setError(null); // Clear error when user types
}}
onKeyDown={handleKeyDown}
disabled={isCloning}
className="text-base"
/>
<div className="space-y-2">
<Input
id="repo-url"
type="text"
placeholder="https://github.com/username/repository.git"
value={repoUrl}
onChange={(e) => {
setRepoUrl(e.target.value);
setError(null); // Clear error when user types
}}
onKeyDown={handleKeyDown}
disabled={isCloning}
/>
{error && (
<div className="flex items-center gap-2 p-3 bg-destructive/10 border border-destructive/20 rounded-md">
<AlertCircle className="h-4 w-4 text-destructive flex-shrink-0" />
<p className="text-sm text-destructive">{error}</p>
</div>
)}
{error && (
<div className="flex items-center gap-2 p-3 bg-destructive/10 border border-destructive/20 rounded-md">
<AlertCircle className="h-4 w-4 text-destructive flex-shrink-0" />
<p className="text-sm text-destructive">{error}</p>
</div>
<Button
onClick={() => handleClone()}
disabled={!repoUrl.trim() || isCloning}
className="w-full focus-ring bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg"
size="lg"
>
{isCloning ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
{t('cloningRepository')}
</>
) : (
<>
<GitBranch className="mr-2 h-4 w-4" />
{t('importRepository')}
</>
)}
<Button
onClick={() => handleClone()}
disabled={!repoUrl.trim() || isCloning}
className="w-full focus-ring bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg"
size="lg"
>
{isCloning ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Cloning Repository...
</>
) : (
<>
<GitBranch className="mr-2 h-4 w-4" />
Import Repository
</>
)}
</Button>
</CardContent>
</Card>
</Button>
</div>
</div>
</AppLayout>
);
+35 -33
View File
@@ -1,5 +1,6 @@
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Download, Trash2, AlertTriangle, Loader2, Database, Info } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
@@ -23,6 +24,7 @@ interface StorageInfo {
}
export function DataSettings() {
const { t } = useTranslation();
const [isExporting, setIsExporting] = useState(false);
const [isClearing, setIsClearing] = useState(false);
const [storageInfo, setStorageInfo] = useState<StorageInfo | null>(null);
@@ -130,14 +132,14 @@ export function DataSettings() {
await exportFilesAsZip();
toast({
title: "Files exported successfully",
description: "Your project files have been downloaded as a zip file.",
title: t('filesExportedSuccessfully'),
description: t('filesExportedDescription'),
});
} catch (error) {
console.error('Failed to export files:', error);
toast({
title: "Failed to export files",
description: error instanceof Error ? error.message : "An unexpected error occurred",
title: t('failedToExportFiles'),
description: error instanceof Error ? error.message : t('error'),
variant: "destructive",
});
} finally {
@@ -172,8 +174,8 @@ export function DataSettings() {
await Promise.all(deletePromises);
toast({
title: "Data cleared successfully",
description: "All local data has been removed. Redirecting to homepage...",
title: t('dataClearedSuccessfully'),
description: t('dataClearedDescription'),
});
// Small delay to show the toast, then redirect
@@ -183,8 +185,8 @@ export function DataSettings() {
} catch (error) {
console.error('Failed to clear data:', error);
toast({
title: "Failed to clear data",
description: error instanceof Error ? error.message : "An unexpected error occurred",
title: t('failedToClearData'),
description: error instanceof Error ? error.message : t('error'),
variant: "destructive",
});
} finally {
@@ -197,10 +199,10 @@ export function DataSettings() {
<div className="space-y-2">
<h1 className="text-2xl font-bold flex items-center gap-3">
<Database className="h-6 w-6 text-primary" />
Data
{t('dataSettings')}
</h1>
<p className="text-muted-foreground">
Export files and manage local data.
{t('dataSettingsDescriptionLong')}
</p>
</div>
@@ -216,8 +218,8 @@ export function DataSettings() {
{/* Usage Progress */}
<div className="space-y-2">
<div className="flex justify-between items-center text-sm">
<span>Used: {formatBytes(storageInfo.usage)}</span>
<span>Available: {formatBytes(storageInfo.quota)}</span>
<span>{t('used')}: {formatBytes(storageInfo.usage)}</span>
<span>{t('available')}: {formatBytes(storageInfo.quota)}</span>
</div>
<Progress
value={storageInfo.quota > 0 ? (storageInfo.usage / storageInfo.quota) * 100 : 0}
@@ -225,8 +227,8 @@ export function DataSettings() {
/>
<div className="text-xs text-muted-foreground text-center">
{storageInfo.quota > 0
? `${((storageInfo.usage / storageInfo.quota) * 100).toFixed(1)}% used`
: 'Usage percentage unavailable'
? t('usagePercentage', { percentage: ((storageInfo.usage / storageInfo.quota) * 100).toFixed(1) })
: t('usageUnavailable')
}
</div>
</div>
@@ -235,7 +237,7 @@ export function DataSettings() {
) : (
<div className="flex items-center gap-2 text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
<span className="text-sm">Loading storage information...</span>
<span className="text-sm">{t('loadingStorageInfo')}</span>
</div>
)}
@@ -244,10 +246,10 @@ export function DataSettings() {
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Download className="h-5 w-5" />
Export Files
{t('exportFiles')}
</CardTitle>
<CardDescription>
Download all your projects and files as a ZIP archive. This includes all project files, settings, and data stored locally.
{t('exportFilesDescription')}
</CardDescription>
</CardHeader>
<CardContent>
@@ -259,12 +261,12 @@ export function DataSettings() {
{isExporting ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Exporting...
{t('exporting')}
</>
) : (
<>
<Download className="h-4 w-4 mr-2" />
Export All Files
{t('exportAllFiles')}
</>
)}
</Button>
@@ -276,10 +278,10 @@ export function DataSettings() {
<CardHeader>
<CardTitle className="flex items-center gap-2 text-destructive">
<Trash2 className="h-5 w-5" />
Clear All Data
{t('clearAllData')}
</CardTitle>
<CardDescription>
Permanently delete all local data including projects, settings, and cached information. This action cannot be undone.
{t('clearAllDataDescription')}
</CardDescription>
</CardHeader>
<CardContent>
@@ -293,12 +295,12 @@ export function DataSettings() {
{isClearing ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Clearing...
{t('clearing')}
</>
) : (
<>
<Trash2 className="h-4 w-4 mr-2" />
Clear All Data
{t('clearAllData')}
</>
)}
</Button>
@@ -307,31 +309,31 @@ export function DataSettings() {
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-destructive" />
Are you absolutely sure?
{t('areYouSure')}
</AlertDialogTitle>
<AlertDialogDescription className="space-y-2">
<p>
This action will permanently delete all local data from this browser, including:
{t('clearDataWarning')}
</p>
<ul className="list-disc list-inside space-y-1 text-sm">
<li>All projects and their files</li>
<li>AI settings and API keys</li>
<li>Git credentials and settings</li>
<li>User preferences and themes</li>
<li>Cached data and session information</li>
<li>{t('allProjects')}</li>
<li>{t('aiSettingsAndKeys')}</li>
<li>{t('gitCredentialsSettings')}</li>
<li>{t('userPreferences')}</li>
<li>{t('cachedData')}</li>
</ul>
<p className="font-medium text-destructive">
This action cannot be undone. Consider exporting your files first.
{t('actionCannotBeUndone')}
</p>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogCancel>{t('cancel')}</AlertDialogCancel>
<AlertDialogAction
onClick={handleClearAllData}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Yes, clear all data
{t('yesClearAllData')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
+90
View File
@@ -0,0 +1,90 @@
import { useEffect } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { useGitHubOAuth } from '@/hooks/useGitHubOAuth';
import { useToast } from '@/hooks/useToast';
import { Card, CardContent } from '@/components/ui/card';
import { Github } from 'lucide-react';
export default function GitHubOAuth() {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const { handleCallback } = useGitHubOAuth();
const { toast } = useToast();
useEffect(() => {
const code = searchParams.get('code');
const state = searchParams.get('state');
const error = searchParams.get('error');
const errorDescription = searchParams.get('error_description');
const storedState = localStorage.getItem('github_oauth_state');
const storedCodeVerifier = localStorage.getItem('github_oauth_code_verifier');
// Handle OAuth errors
if (error) {
toast({
title: "GitHub OAuth Error",
description: errorDescription || error,
variant: "destructive",
});
navigate('/settings/git');
return;
}
// Handle successful OAuth callback
if (code && state && storedState && storedCodeVerifier) {
handleCallback(code, state).then((success) => {
if (success) {
toast({
title: "GitHub Connected",
description: "Successfully connected to GitHub. You can now push and pull from GitHub repositories.",
});
} else {
toast({
title: "Connection Failed",
description: "Failed to connect to GitHub. Please try again.",
variant: "destructive",
});
}
// Always redirect to Git settings after handling the callback
navigate('/settings/git');
});
} else if (code && state && storedState && !storedCodeVerifier) {
// Missing code verifier - likely an incomplete PKCE flow
toast({
title: "Authentication Error",
description: "OAuth flow is incomplete. Please try connecting to GitHub again.",
variant: "destructive",
});
// Clean up any remaining OAuth data
localStorage.removeItem('github_oauth_state');
localStorage.removeItem('github_oauth_code_verifier');
navigate('/settings/git');
} else {
// No code or state parameters - redirect to Git settings
navigate('/settings/git');
}
}, [searchParams, handleCallback, toast, navigate]);
return (
<div className="min-h-screen flex items-center justify-center p-4">
<Card className="w-full max-w-md">
<CardContent className="py-12 px-8 text-center">
<div className="space-y-6">
<div className="flex justify-center">
<Github className="h-12 w-12 text-primary" />
</div>
<div className="space-y-2">
<h1 className="text-xl font-semibold">Connecting to GitHub</h1>
<p className="text-muted-foreground">
Processing your GitHub authentication...
</p>
</div>
<div className="flex justify-center">
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
</div>
</div>
</CardContent>
</Card>
</div>
);
}
+32 -28
View File
@@ -1,4 +1,5 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Check, GitBranch, ArrowLeft, Github, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -38,6 +39,7 @@ const PRESET_PROVIDERS: PresetProvider[] = [
];
export function GitSettings() {
const { t } = useTranslation();
const { settings, addCredential, removeCredential, updateCredential, updateSettings } = useGitSettings();
const { initiateOAuth, isLoading: isOAuthLoading, error: oauthError, isOAuthConfigured } = useGitHubOAuth();
const isMobile = useIsMobile();
@@ -107,15 +109,15 @@ export function GitSettings() {
className="h-8 w-auto px-2 -ml-2"
>
<ArrowLeft className="h-4 w-4 mr-2" />
Back to Settings
{t('backToSettings')}
</Button>
<div className="space-y-2">
<h1 className="text-2xl font-bold flex items-center gap-3">
<GitBranch className="h-6 w-6 text-primary" />
Git Settings
{t('gitSettings')}
</h1>
<p className="text-muted-foreground">
Configure Git credentials for HTTP authentication. Settings are automatically saved and stored locally in your browser.
{t('gitSettingsDescriptionLong')}
</p>
</div>
</div>
@@ -125,10 +127,10 @@ export function GitSettings() {
<div className="space-y-2">
<h1 className="text-2xl font-bold flex items-center gap-3">
<GitBranch className="h-6 w-6 text-primary" />
Git Settings
{t('gitSettings')}
</h1>
<p className="text-muted-foreground">
Configure Git credentials for HTTP authentication. Settings are automatically saved and stored locally in your browser.
{t('gitSettingsDescriptionLong')}
</p>
</div>
)}
@@ -137,7 +139,7 @@ export function GitSettings() {
{/* Configured Credentials */}
{configuredOrigins.length > 0 && (
<div className="space-y-3">
<h4 className="text-sm font-medium">Configured Credentials</h4>
<h4 className="text-sm font-medium">{t('configuredCredentials')}</h4>
<Accordion type="multiple" className="w-full space-y-2">
{configuredOrigins.map((origin) => {
const preset = PRESET_PROVIDERS.find(p => p.origin === origin);
@@ -152,7 +154,7 @@ export function GitSettings() {
<span className="font-medium">
{preset?.name || new URL(origin).hostname}
</span>
{isCustom && <Badge variant="outline">Custom</Badge>}
{isCustom && <Badge variant="outline">{t('custom')}</Badge>}
</div>
<Button
variant="ghost"
@@ -170,7 +172,7 @@ export function GitSettings() {
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor={`${origin}-origin`}>Origin</Label>
<Label htmlFor={`${origin}-origin`}>{t('origin')}</Label>
<Input
id={`${origin}-origin`}
placeholder="https://github.com"
@@ -180,7 +182,7 @@ export function GitSettings() {
/>
</div>
<div className="grid gap-2">
<Label htmlFor={`${origin}-username`}>Username</Label>
<Label htmlFor={`${origin}-username`}>{t('username')}</Label>
<Input
id={`${origin}-username`}
placeholder="git"
@@ -189,11 +191,11 @@ export function GitSettings() {
/>
</div>
<div className="grid gap-2">
<Label htmlFor={`${origin}-password`}>Password</Label>
<Label htmlFor={`${origin}-password`}>{t('password')}</Label>
<Input
id={`${origin}-password`}
type="password"
placeholder="Enter your password/token"
placeholder={t('enterPassword')}
value={credential?.password || ''}
onChange={(e) => handleUpdateCredential(origin, { password: e.target.value })}
/>
@@ -212,7 +214,7 @@ export function GitSettings() {
{/* Available Preset Providers */}
{availablePresets.length > 0 && (
<div className="space-y-3">
<h4 className="text-sm font-medium">Add Provider</h4>
<h4 className="text-sm font-medium">{t('addProvider')}</h4>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{availablePresets.map((preset) => (
<div key={preset.id} className="border rounded-lg p-4 space-y-3">
@@ -224,7 +226,7 @@ export function GitSettings() {
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.tokenURL, '_blank')}
>
Get token
{t('getToken')}
</button>
)}
</div>
@@ -236,7 +238,7 @@ export function GitSettings() {
<Button
onClick={initiateOAuth}
disabled={isOAuthLoading}
className="w-full gap-2"
className="w-full max-w-full gap-2"
variant="default"
>
{isOAuthLoading ? (
@@ -247,7 +249,9 @@ export function GitSettings() {
) : (
<>
<Github className="h-4 w-4" />
Connect to GitHub
<span className="truncate text-ellipsis overflow-hidden">
Connect to GitHub
</span>
</>
)}
</Button>
@@ -260,7 +264,7 @@ export function GitSettings() {
) : (
<div className="flex gap-2">
<Input
placeholder="Enter your token"
placeholder={t('enterToken')}
type="password"
className="flex-1"
value={presetTokens[preset.id] || ''}
@@ -279,7 +283,7 @@ export function GitSettings() {
disabled={!presetTokens[preset.id]?.trim()}
size="sm"
>
Add
{t('add')}
</Button>
</div>
)
@@ -287,7 +291,7 @@ export function GitSettings() {
// Standard rendering for other providers
<div className="flex gap-2">
<Input
placeholder="Enter your token"
placeholder={t('enterToken')}
type="password"
className="flex-1"
value={presetTokens[preset.id] || ''}
@@ -306,7 +310,7 @@ export function GitSettings() {
disabled={!presetTokens[preset.id]?.trim()}
size="sm"
>
Add
{t('add')}
</Button>
</div>
)}
@@ -323,12 +327,12 @@ export function GitSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="custom-provider" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">Add Custom Provider</h4>
<h4 className="text-sm font-medium">{t('addCustomProvider')}</h4>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor="custom-origin">Origin</Label>
<Label htmlFor="custom-origin">{t('origin')}</Label>
<Input
id="custom-origin"
placeholder="https://git.example.com"
@@ -337,7 +341,7 @@ export function GitSettings() {
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-username">Username</Label>
<Label htmlFor="custom-username">{t('username')}</Label>
<Input
id="custom-username"
placeholder="git"
@@ -346,11 +350,11 @@ export function GitSettings() {
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-password">Password</Label>
<Label htmlFor="custom-password">{t('password')}</Label>
<Input
id="custom-password"
type="password"
placeholder="Enter your password/token"
placeholder={t('enterPassword')}
value={customPassword}
onChange={(e) => setCustomPassword(e.target.value)}
/>
@@ -367,11 +371,11 @@ export function GitSettings() {
className="gap-2"
>
<Check className="h-4 w-4" />
Add Custom Provider
{t('addCustomProviderButton')}
</Button>
{customOrigin.trim() in settings.credentials && (
<p className="text-sm text-destructive">
Credentials for this origin already exist
{t('credentialsExist')}
</p>
)}
</div>
@@ -383,7 +387,7 @@ export function GitSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="cors-proxy" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">CORS Proxy</h4>
<h4 className="text-sm font-medium">{t('corsProxy')}</h4>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
@@ -395,7 +399,7 @@ export function GitSettings() {
onChange={(e) => updateSettings({ corsProxy: e.target.value })}
/>
<p className="text-xs text-muted-foreground">
CORS proxy server used for all Git operations with remote repositories. Required for browser-based Git operations.
{t('corsProxyDescription')}
</p>
</div>
</div>
+10 -34
View File
@@ -1,13 +1,12 @@
import { useState, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useAIProjectId } from '@/hooks/useAIProjectId';
import { useFS } from '@/hooks/useFS';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useAISettings } from '@/hooks/useAISettings';
import { useGitHubOAuth } from '@/hooks/useGitHubOAuth';
import { useToast } from '@/hooks/useToast';
import { AppLayout } from '@/components/AppLayout';
import { DotAI } from '@/lib/DotAI';
import type { AIMessage } from '@/lib/SessionManager';
@@ -19,17 +18,15 @@ import { Plus } from 'lucide-react';
import { useSeoMeta } from '@unhead/react';
export default function Index() {
const { t } = useTranslation();
const [prompt, setPrompt] = useState('');
const [isCreating, setIsCreating] = useState(false);
const [storedPrompt, setStoredPrompt] = useLocalStorage('shakespeare-draft-prompt', '');
const [searchParams, setSearchParams] = useSearchParams();
const navigate = useNavigate();
const projectsManager = useProjectsManager();
const { fs } = useFS();
const { generateProjectId, isLoading: isGeneratingId, isConfigured: isAIConfigured } = useAIProjectId();
const { settings, addRecentlyUsedModel } = useAISettings();
const { handleCallback: handleGitHubCallback } = useGitHubOAuth();
const { toast } = useToast();
const [providerModel, setProviderModel] = useState(() => {
// Initialize with first recently used model if available, otherwise empty
return settings.recentlyUsedModels?.[0] || '';
@@ -47,27 +44,6 @@ export default function Index() {
description: 'Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment.',
});
// Handle GitHub OAuth callback
useEffect(() => {
const code = searchParams.get('code');
const state = searchParams.get('state');
if (code && state) {
// Handle GitHub OAuth callback
handleGitHubCallback(code, state).then((success) => {
if (success) {
// Clean up URL parameters
setSearchParams({});
// Show success toast
toast({
title: "GitHub Connected",
description: "Successfully connected to GitHub. You can now push and pull from GitHub repositories.",
});
}
});
}
}, [searchParams, setSearchParams, handleGitHubCallback, toast]);
// Restore prompt from local storage on mount
useEffect(() => {
if (storedPrompt) {
@@ -153,10 +129,10 @@ export default function Index() {
<div className="text-center mb-8 md:mb-12">
<div className="text-4xl md:text-6xl mb-4 md:mb-6">🎭</div>
<h1 className="text-3xl md:text-4xl font-bold mb-3 md:mb-4 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Build Nostr apps with AI
{t('buildNostrApps')}
</h1>
<p className="text-lg md:text-xl text-muted-foreground">
What would you like to build?
{t('whatToBuild')}
</p>
</div>
@@ -166,8 +142,8 @@ export default function Index() {
<Textarea
placeholder={
!providerModel.trim()
? "Please select a model below, then describe what you'd like to build..."
: "e.g., Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies..."
? t('selectModelToDescribe')
: t('examplePrompt')
}
value={prompt}
onChange={handlePromptChange}
@@ -195,7 +171,7 @@ export default function Index() {
onChange={setProviderModel}
className="w-full"
disabled={isCreating || isGeneratingId}
placeholder="Choose a model..."
placeholder={t('chooseModel')}
/>
</div>
@@ -214,12 +190,12 @@ export default function Index() {
{isCreating || isGeneratingId ? (
<>
<div className="animate-spin rounded-full h-3 w-3 border-b-2 border-white mr-2"></div>
{isGeneratingId ? 'Generating...' : 'Creating...'}
{isGeneratingId ? t('generating') : t('creating')}
</>
) : (
<>
<Plus className="mr-2 h-3 w-3" />
Create Project
{t('createProject')}
</>
)}
</Button>
+230
View File
@@ -0,0 +1,230 @@
import { ArrowLeft, Wifi, Users, UserPlus, LogOut, Trash2, User, Plus } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton';
import { RelaySelector } from '@/components/RelaySelector';
import LoginDialog from '@/components/auth/LoginDialog';
import SignupDialog from '@/components/auth/SignupDialog';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useNavigate } from 'react-router-dom';
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
import { genUserName } from '@/lib/genUserName';
import { useState } from 'react';
export function NostrSettings() {
const { t } = useTranslation();
const isMobile = useIsMobile();
const navigate = useNavigate();
const { authors, currentUser, setLogin, removeLogin, isLoading } = useLoggedInAccounts();
const [showLoginDialog, setShowLoginDialog] = useState(false);
const [showSignupDialog, setShowSignupDialog] = useState(false);
const handleSwitchAccount = (accountId: string) => {
setLogin(accountId);
};
const handleRemoveAccount = (accountId: string) => {
removeLogin(accountId);
};
const handleLoginSuccess = () => {
setShowLoginDialog(false);
};
const handleSignupComplete = () => {
setShowSignupDialog(false);
};
const getDisplayName = (account: Account) => {
return account.metadata?.name ?? genUserName(account.pubkey);
};
return (
<div className="p-6 space-y-6">
{isMobile && (
<div className="space-y-3">
<Button
variant="ghost"
size="sm"
onClick={() => navigate('/settings')}
className="h-8 w-auto px-2 -ml-2"
>
<ArrowLeft className="h-4 w-4 mr-2" />
{t('backToSettings')}
</Button>
<div className="space-y-2">
<h1 className="text-2xl font-bold flex items-center gap-3">
<Wifi className="h-6 w-6 text-primary" />
{t('nostrSettings')}
</h1>
<p className="text-muted-foreground">
{t('nostrSettingsDescriptionLong')}
</p>
</div>
</div>
)}
{!isMobile && (
<div className="space-y-2">
<h1 className="text-2xl font-bold flex items-center gap-3">
<Wifi className="h-6 w-6 text-primary" />
{t('nostrSettings')}
</h1>
<p className="text-muted-foreground">
{t('nostrSettingsDescriptionLong')}
</p>
</div>
)}
<div className="space-y-6">
{/* Account Management */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Users className="h-5 w-5" />
{t('nostrAccounts')}
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{isLoading ? (
<div className="border rounded-lg overflow-hidden">
{/* Loading skeleton for accounts */}
{[...Array(2)].map((_, i) => (
<div key={i} className="flex items-center gap-3 p-3 border-b last:border-b-0">
<Skeleton className="h-10 w-10 rounded-full" />
<div className="flex-1 space-y-1">
<Skeleton className="h-4 w-32" />
</div>
<Skeleton className="h-8 w-8 rounded" />
</div>
))}
{/* Add account button skeleton */}
<div className="flex items-center gap-3 p-3">
<Skeleton className="h-10 w-10 rounded-full" />
<div className="flex-1 space-y-1">
<Skeleton className="h-4 w-24" />
</div>
</div>
</div>
) : authors.length === 0 ? (
<div className="text-center py-8">
<User className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
<p className="text-muted-foreground mb-4">
{t('noAccountsLoggedIn')}
</p>
<div className="flex flex-col sm:flex-row gap-2 justify-center">
<Button onClick={() => setShowSignupDialog(true)} className="gap-2">
<UserPlus className="h-4 w-4" />
{t('createAccount')}
</Button>
<Button variant="outline" onClick={() => setShowLoginDialog(true)} className="gap-2">
<LogOut className="h-4 w-4 rotate-180" />
{t('addExistingAccount')}
</Button>
</div>
</div>
) : (
<>
{/* Account List - Joined Together */}
<div className="border rounded-lg overflow-hidden">
{authors.map((account) => (
<div
key={account.id}
className={`flex items-center gap-3 p-3 transition-colors relative border-b ${
currentUser?.id === account.id
? 'bg-primary/5 border-primary/20'
: 'hover:bg-muted/50 cursor-pointer'
}`}
onClick={() => currentUser?.id !== account.id && handleSwitchAccount(account.id)}
>
<Avatar className="h-10 w-10">
<AvatarImage src={account.metadata?.picture} alt={getDisplayName(account)} />
<AvatarFallback>
{getDisplayName(account).charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
<p className="font-medium truncate">
{getDisplayName(account)}
</p>
</div>
<div className="flex items-center gap-2 z-10">
<Button
variant="ghost"
size="icon"
onClick={(e) => {
e.stopPropagation();
handleRemoveAccount(account.id);
}}
className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive hover:bg-transparent"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
))}
{/* Add Account Button - Integrated into the list */}
<div
className="flex items-center gap-3 p-3 transition-colors hover:bg-muted/50 cursor-pointer"
onClick={() => setShowLoginDialog(true)}
>
<div className="h-10 w-10 rounded-full border-2 border-dashed border-muted-foreground/30 flex items-center justify-center">
<Plus className="h-4 w-4 text-muted-foreground" />
</div>
<div className="flex-1 min-w-0">
<p className="font-medium text-muted-foreground">
{t('addAccount')}
</p>
</div>
</div>
</div>
</>
)}
</CardContent>
</Card>
{/* Relay Configuration */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Wifi className="h-5 w-5" />
{t('relayConfiguration')}
</CardTitle>
</CardHeader>
<CardContent>
<div className="grid gap-2">
<Label htmlFor="relay-selector">{t('selectedRelay')}</Label>
<RelaySelector className="w-full max-w-md" />
</div>
</CardContent>
</Card>
</div>
{/* Login Dialog */}
<LoginDialog
isOpen={showLoginDialog}
onClose={() => setShowLoginDialog(false)}
onLogin={handleLoginSuccess}
onSignup={() => {
setShowLoginDialog(false);
setShowSignupDialog(true);
}}
/>
{/* Signup Dialog */}
<SignupDialog
isOpen={showSignupDialog}
onClose={() => setShowSignupDialog(false)}
onComplete={handleSignupComplete}
/>
</div>
);
}
export default NostrSettings;
+7 -5
View File
@@ -1,8 +1,10 @@
import { useSeoMeta } from "@unhead/react";
import { useLocation } from "react-router-dom";
import { useTranslation } from 'react-i18next';
import { useEffect } from "react";
const NotFound = () => {
const { t } = useTranslation();
const location = useLocation();
useSeoMeta({
@@ -18,12 +20,12 @@ const NotFound = () => {
}, [location.pathname]);
return (
<div className="min-h-screen flex items-center justify-center bg-gray-100 dark:bg-gray-900">
<div className="min-h-screen flex items-center justify-center bg-background">
<div className="text-center">
<h1 className="text-4xl font-bold mb-4 text-gray-900 dark:text-gray-100">404</h1>
<p className="text-xl text-gray-600 dark:text-gray-400 mb-4">Oops! Page not found</p>
<a href="/" className="text-blue-500 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 underline">
Return to Home
<h1 className="text-4xl font-bold mb-4 text-foreground">404</h1>
<p className="text-xl text-muted-foreground mb-4">{t('pageNotFound')}</p>
<a href="/" className="text-primary hover:text-primary/80 underline">
{t('returnToHome')}
</a>
</div>
</div>
+36
View File
@@ -0,0 +1,36 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { Preferences } from './Preferences';
describe('Preferences', () => {
it('renders preferences page with language and theme sections', () => {
render(
<TestApp>
<Preferences />
</TestApp>
);
// Should show the preferences title
expect(screen.getByText('Preferences')).toBeInTheDocument();
// Should show theme and language labels at top level
expect(screen.getByText('Theme')).toBeInTheDocument();
expect(screen.getByText('Language')).toBeInTheDocument();
// Should show language picker
expect(screen.getByRole('combobox')).toBeInTheDocument();
});
it('displays translated content correctly', () => {
render(
<TestApp>
<Preferences />
</TestApp>
);
// Check for key translated strings
expect(screen.getByText('Manage your general application preferences and appearance settings.')).toBeInTheDocument();
expect(screen.getByText('Select your preferred language for the interface.')).toBeInTheDocument();
});
});
+78
View File
@@ -0,0 +1,78 @@
import { Settings2, ArrowLeft } from "lucide-react";
import { useTranslation } from 'react-i18next';
import { Button } from "@/components/ui/button";
import { ThemePicker } from "@/components/ThemePicker";
import { LanguagePicker } from "@/components/LanguagePicker";
import { Label } from "@/components/ui/label";
import { useIsMobile } from "@/hooks/useIsMobile";
import { useNavigate } from "react-router-dom";
export function Preferences() {
const { t } = useTranslation();
const isMobile = useIsMobile();
const navigate = useNavigate();
return (
<div className="p-6 space-y-6">
{isMobile && (
<div className="space-y-3">
<Button
variant="ghost"
size="sm"
onClick={() => navigate('/settings')}
className="h-8 w-auto px-2 -ml-2"
>
<ArrowLeft className="h-4 w-4 mr-2" />
{t('backToSettings')}
</Button>
<div className="space-y-2">
<h1 className="text-2xl font-bold flex items-center gap-3">
<Settings2 className="h-6 w-6 text-primary" />
{t('preferences')}
</h1>
<p className="text-muted-foreground">
{t('preferencesDescription')}
</p>
</div>
</div>
)}
{!isMobile && (
<div className="space-y-2">
<h1 className="text-2xl font-bold flex items-center gap-3">
<Settings2 className="h-6 w-6 text-primary" />
{t('preferences')}
</h1>
<p className="text-muted-foreground">
{t('preferencesDescription')}
</p>
</div>
)}
<div className="space-y-6">
<div className="space-y-2">
<Label htmlFor="theme-picker">{t('theme')}</Label>
<div className="w-full max-w-xs">
<ThemePicker />
</div>
<p className="text-sm text-muted-foreground">
{t('themeDescription')}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="language-picker">{t('language')}</Label>
<div className="w-full max-w-xs">
<LanguagePicker />
</div>
<p className="text-sm text-muted-foreground">
{t('languageDescription')}
</p>
</div>
</div>
</div>
);
}
export default Preferences;
+33 -27
View File
@@ -1,5 +1,6 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { type Project } from '@/lib/ProjectsManager';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { ChatPane, type ChatPaneRef } from '@/components/Shakespeare/ChatPane';
@@ -9,7 +10,7 @@ import { ProjectInfoDialog } from '@/components/ProjectInfoDialog';
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { ArrowLeft, MessageSquare, Eye, Code, Menu, Columns2 } from 'lucide-react';
import { ArrowLeft, MessageSquare, Eye, Code, Menu } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { ActionsMenu } from '@/components/ActionsMenu';
@@ -27,6 +28,7 @@ import { useToast } from "@/hooks/useToast";
export function ProjectView() {
const { projectId } = useParams<{ projectId: string }>();
const { t } = useTranslation();
const [project, setProject] = useState<Project | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [activeTab, setActiveTab] = useState<'preview' | 'code'>('preview');
@@ -263,6 +265,7 @@ export function ProjectView() {
navigate('/');
}
}}
onClose={() => setIsSidebarVisible(false)}
/>
</div>
</div>
@@ -317,7 +320,7 @@ export function ProjectView() {
disabled={!project}
>
<MessageSquare className="h-4 w-4 mr-1" />
Chat
{t('chat')}
</Button>
<Button
variant={mobileView === 'preview' ? 'default' : 'ghost'}
@@ -327,7 +330,7 @@ export function ProjectView() {
disabled={!project}
>
<Eye className="h-4 w-4 mr-1" />
Preview
{t('preview')}
</Button>
<Button
variant={mobileView === 'code' ? 'default' : 'ghost'}
@@ -337,7 +340,7 @@ export function ProjectView() {
disabled={!project}
>
<Code className="h-4 w-4 mr-1" />
Code
{t('code')}
{mobileView !== 'code' && project && (
<GitStatusIndicator projectId={project.id} className="ml-1" />
)}
@@ -371,6 +374,7 @@ export function ProjectView() {
navigate('/');
}
}}
onToggleSidebar={() => setIsSidebarVisible(!isSidebarVisible)}
className="h-full"
/>
</div>
@@ -385,32 +389,34 @@ export function ProjectView() {
{/* Chat Header */}
<div className="h-12 px-4 border-b flex-shrink-0">
<div className="flex items-center justify-between h-12">
{/* Left side - Sidebar toggle */}
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
className="h-8 w-8 p-0"
aria-label="Toggle sidebar"
>
<Columns2 className="h-4 w-4" />
</Button>
</div>
{/* Center - Project title */}
<div className="flex flex-1 min-w-0 px-4 truncate">
{project ? (
{/* Left side - Sidebar toggle (when collapsed) */}
<div className="flex items-center gap-3 overflow-hidden">
{!isSidebarVisible && (
<Button
variant="ghost"
className="block p-0 h-auto font-semibold text-lg truncate hover:bg-transparent hover:text-primary"
onClick={() => setIsProjectInfoOpen(true)}
size="sm"
onClick={() => setIsSidebarVisible(true)}
className="h-8 w-8 p-0"
aria-label="Open sidebar"
>
{project.name}
<Menu className="h-4 w-4" />
</Button>
) : (
<Skeleton className="h-6 w-40" />
)}
{/* Project title */}
<div className="flex flex-1 min-w-0 truncate">
{project ? (
<Button
variant="ghost"
className="block p-0 h-auto font-semibold text-lg truncate hover:bg-transparent hover:text-primary"
onClick={() => setIsProjectInfoOpen(true)}
>
{project.name}
</Button>
) : (
<Skeleton className="h-6 w-40" />
)}
</div>
</div>
{/* Right side - Star and Actions Menu */}
@@ -488,7 +494,7 @@ export function ProjectView() {
onClick={() => setActiveTab('preview')}
disabled={!project}
>
Preview
{t('preview')}
</Button>
<Button
variant={activeTab === 'code' ? 'default' : 'ghost'}
@@ -497,7 +503,7 @@ export function ProjectView() {
className="gap-2"
disabled={!project}
>
Code
{t('code')}
{activeTab !== 'code' && project && (
<GitStatusIndicator projectId={project.id} />
)}
+36 -10
View File
@@ -1,5 +1,6 @@
import { useNavigate } from 'react-router-dom';
import { Bot, GitBranch, Database } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
interface SettingsItem {
@@ -10,41 +11,66 @@ interface SettingsItem {
href: string;
}
const settingsItems: SettingsItem[] = [
// Define settings items as a function to get fresh translations
const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [
{
id: 'preferences',
title: t('preferences'),
description: t('preferencesDescription'),
icon: Settings2,
href: '/settings/preferences',
},
{
id: 'ai',
title: 'AI Settings',
description: 'Configure AI providers and API keys',
title: t('aiSettings'),
description: t('aiSettingsDescription'),
icon: Bot,
href: '/settings/ai',
},
{
id: 'git',
title: 'Git Settings',
description: 'Configure Git credentials for HTTP authentication',
title: t('gitSettings'),
description: t('gitSettingsDescription'),
icon: GitBranch,
href: '/settings/git',
},
{
id: 'nostr',
title: t('nostrSettings'),
description: t('nostrSettingsDescription'),
icon: Wifi,
href: '/settings/nostr',
},
{
id: 'data',
title: 'Data',
description: 'Export files and manage local data',
title: t('dataSettings'),
description: t('dataSettingsDescription'),
icon: Database,
href: '/settings/data',
},
{
id: 'about',
title: t('aboutShakespeare'),
description: t('aboutShakespeareDescription'),
icon: Info,
href: '/settings/about',
},
];
export function Settings() {
const { t } = useTranslation();
const navigate = useNavigate();
const isMobile = useIsMobile();
const settingsItems = getSettingsItems(t);
if (isMobile) {
return (
<div className="p-6 space-y-4">
<div className="space-y-2">
<h2 className="text-xl font-bold">Settings</h2>
<h2 className="text-xl font-bold">{t('settings')}</h2>
<p className="text-muted-foreground">
Manage your application settings and preferences.
{t('settingsDescription')}
</p>
</div>
<div className="space-y-3">
+2
View File
@@ -11,6 +11,7 @@ import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
import { AISettingsProvider } from '@/components/AISettingsProvider';
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
import '@/lib/i18n';
interface TestAppProps {
children: React.ReactNode;
@@ -30,6 +31,7 @@ export function TestApp({ children }: TestAppProps) {
theme: 'light',
relayUrl: 'wss://relay.nostr.band',
deployServer: 'shakespeare.wtf',
language: 'en',
};
// Initialize LightningFS for testing
+30
View File
@@ -0,0 +1,30 @@
declare global {
interface Window {
webln?: {
enable(): Promise<void>;
sendPayment(paymentRequest: string): Promise<{
preimage: string;
}>;
makeInvoice(args: {
amount?: number;
defaultMemo?: string;
}): Promise<{
paymentRequest: string;
}>;
signMessage(message: string): Promise<{
message: string;
signature: string;
}>;
verifyMessage(signature: string, message: string): Promise<void>;
getInfo(): Promise<{
node: {
alias: string;
pubkey: string;
color?: string;
};
}>;
};
}
}
export {};