Compare commits

..
Author SHA1 Message Date
Chad Curtis f09f1436ae further changes 2025-09-25 19:28:38 +00:00
152 changed files with 3458 additions and 11972 deletions

No files matched your search

-3
View File
@@ -12,8 +12,6 @@ dist
dist-ssr dist-ssr
*.local *.local
.ai-history/ .ai-history/
*.apk
*.aab
# Editor directories and files # Editor directories and files
.idea .idea
@@ -32,4 +30,3 @@ dist-ssr
.env.* .env.*
!.env.example !.env.example
.ai/ .ai/
*.keystore
+2 -3
View File
@@ -1,4 +1,3 @@
{ {
"editor.tabSize": 2, "editor.tabSize": 2
"editor.insertSpaces": true }
}
+76 -29
View File
@@ -1,38 +1,85 @@
# Shakespeare 🎭 # Shakespeare - AI-Powered Nostr Website Builder
[![Edit with Shakespeare](https://shakespeare.diy/badge.svg)](https://shakespeare.diy/clone?url=https://gitlab.com/soapbox-pub/shakespeare.git) Shakespeare is an AI chat application that allows users to build custom Nostr websites through natural language conversation. Simply describe what you want to build, and AI will help you create it.
AI-powered Nostr website builder. Describe what you want to build, and AI helps you create it.
https://shakespeare.diy
## Features ## Features
- **AI Chat**: Build websites through natural conversation - **AI-Powered Development**: Chat with an AI assistant to build your Nostr website
- **File Attachments**: Drag & drop files or paste images - **File Attachments**: Attach files directly to chat messages with structured text parts, visual badges, and deduplication. Supports both file selection and clipboard image pasting
- **Live Preview**: See changes in real-time - **Project Management**: Create and manage multiple projects with sidebar navigation
- **Code Editor**: Edit files with syntax highlighting - **Real-time Editing**: Edit files directly in the browser with syntax highlighting
- **Git Integration**: Full version control with credential management - **File Explorer**: Browse and manage your project files
- **Nostr Ready**: Built-in Nostr protocol support - **Project Preview**: Preview your website as you build it
- **Template Cloning**: Start from a pre-configured Nostr template
## Quick Start
1. **Describe** your project in the textarea
2. **Chat** with AI to build features
3. **Preview** your website instantly
4. **Deploy** with one click
## Tech Stack
- React 18 + TypeScript
- Vite + TailwindCSS
- shadcn/ui + Nostrify
- LightningFS + isomorphic-git
## Getting Started ## Getting Started
Visit the homepage, enter your project idea, and start building with AI assistance. 1. **Create a Project**: Enter a description of what you want to build in the prompt textarea
2. **Chat with AI**: Use the AI assistant to add features, edit files, and build your website
3. **Attach Files**: Click the paperclip icon to attach files or paste images directly from your clipboard - they'll show as "Added file: /path/filename"
4. **Edit Code**: Switch to the code view to manually edit files if needed
5. **Preview**: View your website in the preview pane
## License ## Project Structure
AGPLv3 Each project includes:
- React 18 with TypeScript
- Vite for building
- TailwindCSS for styling
- Nostrify for Nostr integration
- shadcn/ui components
## AI Capabilities
The AI assistant can:
- Read and write project files
- Add new components and pages
- Configure Nostr functionality
- Build the project
- Search through files
- Provide project structure overview
- Add and remove npm packages
- Install dependencies and dev dependencies
## Usage
1. **Homepage**: Enter a project description in the textarea to create new projects, with existing projects listed in the sidebar
2. **Project View**: Split-pane interface with AI chat on the left and preview/code on the right
3. **File Explorer**: Navigate your project files in the code view
4. **File Editor**: Edit files with syntax highlighting and save changes
## Git Integration
Shakespeare includes full Git functionality with credential management:
### Features
- **Version Control**: Full Git repository support with commit history and branch management
- **Global Credentials**: Configure Git credentials once and use them across all projects
- **Automatic Matching**: Credentials are automatically matched to repository origins
- **Popular Providers**: Built-in support for GitHub, GitLab, and custom Git providers
- **Secure Storage**: Credentials are stored locally in your browser using IndexedDB
### Setting Up Git Credentials
1. **Access Git Settings**: Click the gear icon in any Git dialog or use the Git Settings option
2. **Add Provider**: Choose from GitHub, GitLab, or add a custom Git provider
3. **Enter Token**: Use your username and personal access token for authentication
4. **Automatic Usage**: Credentials are automatically used for push/pull operations in matching repositories
### Repository Operations
- **Push/Pull**: Sync changes with remote repositories using configured credentials
- **Status Monitoring**: Real-time Git status with file changes and sync information
- **Commit History**: View commit history and repository information
- **Branch Management**: Work with different branches and track remote changes
## Development
Built with:
- React 18
- TypeScript
- Vite
- TailwindCSS
- shadcn/ui
- LightningFS for filesystem
- isomorphic-git for template cloning
-7
View File
@@ -40,18 +40,11 @@ export default tseslint.config(
"ignoreRestSiblings": true, "ignoreRestSiblings": true,
}, },
], ],
"indent": [
"warn",
2,
{ SwitchCase: 1 },
],
"no-tabs": "warn",
"custom/no-placeholder-comments": "error", "custom/no-placeholder-comments": "error",
"no-warning-comments": [ "no-warning-comments": [
"error", "error",
{ terms: ["fixme"] }, { terms: ["fixme"] },
], ],
"no-control-regex": "off", // Allow ANSI escape sequences in regex
}, },
}, },
{ {
+3 -5
View File
@@ -2,16 +2,14 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<title>Shakespeare - AI-Powered Nostr Development</title> <title>Shakespeare - AI-Powered Nostr Development</title>
<meta name="description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment"> <meta name="description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment">
<meta property="og:type" content="website"> <meta property="og:type" content="website">
<meta property="og:title" content="Shakespeare - AI-Powered Nostr Development"> <meta property="og:title" content="Shakespeare - AI-Powered Nostr Development">
<meta property="og:description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment"> <meta property="og:description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment">
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:"> <!-- <meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:"> -->
<link rel="icon" type="image/png" href="/shakespeare.png"> <link rel="icon" type="image/png" href="/favicon.png">
<link rel="manifest" href="/manifest.webmanifest"> <link rel="manifest" href="/manifest.webmanifest">
</head> </head>
<body> <body>
+3 -19
View File
@@ -79,7 +79,6 @@
"streamdown": "~1.0.0", "streamdown": "~1.0.0",
"tailwind-merge": "^2.5.2", "tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7", "tailwindcss-animate": "^1.0.7",
"tailwindcss-safe-area": "^0.8.0",
"turndown": "^7.2.1", "turndown": "^7.2.1",
"uri-templates": "^0.2.0", "uri-templates": "^0.2.0",
"use-stick-to-bottom": "^1.1.1", "use-stick-to-bottom": "^1.1.1",
@@ -4669,9 +4668,9 @@
} }
}, },
"node_modules/caniuse-lite": { "node_modules/caniuse-lite": {
"version": "1.0.30001746", "version": "1.0.30001716",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001746.tgz", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001716.tgz",
"integrity": "sha512-eA7Ys/DGw+pnkWWSE/id29f2IcPHVoE8wxtvE5JdvD2V28VTDPy1yEeo11Guz0sJ4ZeGRcm3uaTcAqK1LXaphA==", "integrity": "sha512-49/c1+x3Kwz7ZIWt+4DvK3aMJy9oYXXG6/97JKsnjdCk/6n9vVyWL8NAwVt95Lwt9eigI10Hl782kDfZUUlRXw==",
"dev": true, "dev": true,
"funding": [ "funding": [
{ {
@@ -10093,21 +10092,6 @@
"tailwindcss": ">=3.0.0 || insiders" "tailwindcss": ">=3.0.0 || insiders"
} }
}, },
"node_modules/tailwindcss-safe-area": {
"version": "0.8.0",
"resolved": "https://registry.npmjs.org/tailwindcss-safe-area/-/tailwindcss-safe-area-0.8.0.tgz",
"integrity": "sha512-OIKZfSvinI9kZ3hduoSxqP8EfW2rXoKvHnNyTDY2zwem06IIRtLcKdMe0nF98o+Xluk5Fy7mmesr1rSXg/wkhA==",
"license": "MIT",
"engines": {
"node": ">=16"
},
"funding": {
"url": "https://github.com/sponsors/mvllow"
},
"peerDependencies": {
"tailwindcss": "^2.0.0 || >=3.0.0"
}
},
"node_modules/tailwindcss/node_modules/postcss-selector-parser": { "node_modules/tailwindcss/node_modules/postcss-selector-parser": {
"version": "6.1.2", "version": "6.1.2",
"resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz", "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz",
-1
View File
@@ -82,7 +82,6 @@
"streamdown": "~1.0.0", "streamdown": "~1.0.0",
"tailwind-merge": "^2.5.2", "tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7", "tailwindcss-animate": "^1.0.7",
"tailwindcss-safe-area": "^0.8.0",
"turndown": "^7.2.1", "turndown": "^7.2.1",
"uri-templates": "^0.2.0", "uri-templates": "^0.2.0",
"use-stick-to-bottom": "^1.1.1", "use-stick-to-bottom": "^1.1.1",
+234 -261
View File
@@ -1,45 +1,35 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> GNU AFFERO GENERAL PUBLIC LICENSE
<!-- saved from url=(0053)https://www.gnu.org/licenses/agpl-3.0-standalone.html --> Version 3, 19 November 2007
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>GNU Affero General Public License - GNU Project - Free Software Foundation (FSF)</title>
<link rel="alternate" type="application/rdf+xml" href="http://www.gnu.org/licenses/agpl-3.0.rdf">
</head>
<body>
<h3 style="text-align: center;">GNU AFFERO GENERAL PUBLIC LICENSE</h3>
<p style="text-align: center;">Version 3, 19 November 2007</p>
<p>Copyright © 2007 Free Software Foundation, Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Inc. &lt;<a href="https://fsf.org/">https://fsf.org/</a>&gt;
<br>
Everyone is permitted to copy and distribute verbatim copies Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.</p> of this license document, but changing it is not allowed.
<h4 id="preamble">Preamble</h4> Preamble
<p>The GNU Affero General Public License is a free, copyleft license The GNU Affero General Public License is a free, copyleft license for
for software and other kinds of works, specifically designed to ensure software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.</p> cooperation with the community in the case of network server software.
<p>The licenses for most software and other practical works are The licenses for most software and other practical works are designed
designed to take away your freedom to share and change the works. By to take away your freedom to share and change the works. By contrast,
contrast, our General Public Licenses are intended to guarantee your our General Public Licenses are intended to guarantee your freedom to
freedom to share and change all versions of a program--to make sure it share and change all versions of a program--to make sure it remains free
remains free software for all its users.</p> software for all its users.
<p>When we speak of free software, we are referring to freedom, not When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.</p> free programs, and that you know you can do these things.
<p>Developers that use our General Public Licenses protect your rights Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute you this License which gives you legal permission to copy, distribute
and/or modify the software.</p> and/or modify the software.
<p>A secondary benefit of defending all users' freedom is that A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and incorporate. Many developers of free software are heartened and
@@ -47,79 +37,78 @@ encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about. software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its letting the public access it on a server without ever releasing its
source code to the public.</p> source code to the public.
<p>The GNU Affero General Public License is designed specifically to The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source a publicly accessible server, gives the public access to the source
code of the modified version.</p> code of the modified version.
<p>An older license, called the Affero General Public License and An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under released a new version of the Affero GPL which permits relicensing under
this license.</p> this license.
<p>The precise terms and conditions for copying, distribution and The precise terms and conditions for copying, distribution and
modification follow.</p> modification follow.
<h4 id="terms">TERMS AND CONDITIONS</h4> TERMS AND CONDITIONS
<h4 id="section0">0. Definitions.</h4> 0. Definitions.
<p>"This License" refers to version 3 of the GNU Affero General Public "This License" refers to version 3 of the GNU Affero General Public License.
License.</p>
<p>"Copyright" also means copyright-like laws that apply to other kinds "Copyright" also means copyright-like laws that apply to other kinds of
of works, such as semiconductor masks.</p> works, such as semiconductor masks.
<p>"The Program" refers to any copyrightable work licensed under this "The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.</p> "recipients" may be individuals or organizations.
<p>To "modify" a work means to copy from or adapt all or part of the work To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.</p> earlier work or a work "based on" the earlier work.
<p>A "covered work" means either the unmodified Program or a work based A "covered work" means either the unmodified Program or a work based
on the Program.</p> on the Program.
<p>To "propagate" a work means to do anything with it that, without To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying, computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the distribution (with or without modification), making available to the
public, and in some countries other activities as well.</p> public, and in some countries other activities as well.
<p>To "convey" a work means any kind of propagation that enables other To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.</p> a computer network, with no transfer of a copy, is not conveying.
<p>An interactive user interface displays "Appropriate Legal Notices" An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2) feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.</p> menu, a prominent item in the list meets this criterion.
<h4 id="section1">1. Source Code.</h4> 1. Source Code.
<p>The "source code" for a work means the preferred form of the work The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source for making modifications to it. "Object code" means any non-source
form of a work.</p> form of a work.
<p>A "Standard Interface" means an interface that either is an official A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that interfaces specified for a particular programming language, one that
is widely used among developers working in that language.</p> is widely used among developers working in that language.
<p>The "System Libraries" of an executable work include anything, other The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that Component, and (b) serves only to enable use of the work with that
@@ -128,9 +117,9 @@ implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component "Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system (kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to (if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.</p> produce the work, or an object code interpreter used to run it.
<p>The "Corresponding Source" for a work in object code form means all The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's control those activities. However, it does not include the work's
@@ -141,26 +130,26 @@ includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require, linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those such as by intimate data communication or control flow between those
subprograms and other parts of the work.</p> subprograms and other parts of the work.
<p>The Corresponding Source need not include anything that users The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding can regenerate automatically from other parts of the Corresponding
Source.</p> Source.
<p>The Corresponding Source for a work in source code form is that The Corresponding Source for a work in source code form is that
same work.</p> same work.
<h4 id="section2">2. Basic Permissions.</h4> 2. Basic Permissions.
<p>All rights granted under this License are granted for the term of All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.</p> rights of fair use or other equivalent, as provided by copyright law.
<p>You may make, run and propagate covered works that you do not You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you of having them make modifications exclusively for you, or provide you
@@ -169,73 +158,69 @@ the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.</p> your copyrighted material outside their relationship with you.
<p>Conveying under any other circumstances is permitted solely under Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10 the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.</p> makes it unnecessary.
<h4 id="section3">3. Protecting Users' Legal Rights From Anti-Circumvention Law.</h4> 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
<p>No covered work shall be deemed part of an effective technological No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or 11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such similar laws prohibiting or restricting circumvention of such
measures.</p> measures.
<p>When you convey a covered work, you waive any legal power to forbid When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of users, your or third parties' legal rights to forbid circumvention of
technological measures.</p> technological measures.
<h4 id="section4">4. Conveying Verbatim Copies.</h4> 4. Conveying Verbatim Copies.
<p>You may convey verbatim copies of the Program's source code as you You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice; appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code; non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.</p> recipients a copy of this License along with the Program.
<p>You may charge any price or no price for each copy that you convey, You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.</p> and you may offer support or warranty protection for a fee.
<h4 id="section5">5. Conveying Modified Source Versions.</h4> 5. Conveying Modified Source Versions.
<p>You may convey a work based on the Program, or the modifications to You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:</p> terms of section 4, provided that you also meet all of these conditions:
<ul> a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
<li>a) The work must carry prominent notices stating that you modified b) The work must carry prominent notices stating that it is
it, and giving a relevant date.</li>
<li>b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to 7. This requirement modifies the requirement in section 4 to
"keep intact all notices".</li> "keep intact all notices".
<li>c) You must license the entire work, as a whole, under this c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7 License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts, additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.</li> invalidate such permission if you have separately received it.
<li>d) If the work has interactive user interfaces, each must display d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.</li> work need not make them do so.
</ul> A compilation of a covered work with other separate and independent
<p>A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work, works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program, and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an in or on a volume of a storage or distribution medium, is called an
@@ -243,23 +228,21 @@ in or on a volume of a storage or distribution medium, is called an
used to limit the access or legal rights of the compilation's users used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other in an aggregate does not cause this License to apply to the other
parts of the aggregate.</p> parts of the aggregate.
<h4 id="section6">6. Conveying Non-Source Forms.</h4> 6. Conveying Non-Source Forms.
<p>You may convey a covered work in object code form under the terms You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License, machine-readable Corresponding Source under the terms of this License,
in one of these ways:</p> in one of these ways:
<ul> a) Convey the object code in, or embodied in, a physical product
<li>a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the (including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium Corresponding Source fixed on a durable physical medium
customarily used for software interchange.</li> customarily used for software interchange.
<li>b) Convey the object code in, or embodied in, a physical product b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a (including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product long as you offer spare parts or customer support for that product
@@ -269,15 +252,15 @@ in one of these ways:</p>
medium customarily used for software interchange, for a price no medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.</li> Corresponding Source from a network server at no charge.
<li>c) Convey individual copies of the object code with a copy of the c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord only if you received the object code with such an offer, in accord
with subsection 6b.</li> with subsection 6b.
<li>d) Convey the object code by offering access from a designated d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the further charge. You need not require recipients to copy the
@@ -288,20 +271,18 @@ in one of these ways:</p>
clear directions next to the object code saying where to find the clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.</li> available for as long as needed to satisfy these requirements.
<li>e) Convey the object code using peer-to-peer transmission, provided e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no Source of the work are being offered to the general public at no
charge under subsection 6d.</li> charge under subsection 6d.
</ul> A separable portion of the object code, whose source code is excluded
<p>A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be from the Corresponding Source as a System Library, need not be
included in conveying the object code work.</p> included in conveying the object code work.
<p>A "User Product" is either (1) a "consumer product", which means any A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family, tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product, into a dwelling. In determining whether a product is a consumer product,
@@ -312,17 +293,17 @@ of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.</p> the only significant mode of use of the product.
<p>"Installation Information" for a User Product means any methods, "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because code is in no case prevented or interfered with solely because
modification has been made.</p> modification has been made.
<p>If you convey an object code work under this section in, or with, or If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a User Product is transferred to the recipient in perpetuity or for a
@@ -331,137 +312,133 @@ Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has modified object code on the User Product (for example, the work has
been installed in ROM).</p> been installed in ROM).
<p>The requirement to provide Installation Information does not include a The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and adversely affects the operation of the network or violates the rules and
protocols for communication across the network.</p> protocols for communication across the network.
<p>Corresponding Source conveyed, and Installation Information provided, Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in documented (and with an implementation available to the public in
source code form), and must require no special password or key for source code form), and must require no special password or key for
unpacking, reading or copying.</p> unpacking, reading or copying.
<h4 id="section7">7. Additional Terms.</h4> 7. Additional Terms.
<p>"Additional permissions" are terms that supplement the terms of this "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions. License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.</p> this License without regard to the additional permissions.
<p>When you convey a copy of a covered work, you may at your option When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work, additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.</p> for which you have or can give appropriate copyright permission.
<p>Notwithstanding any other provision of this License, for material you Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:</p> that material) supplement the terms of this License with terms:
<ul> a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
<li>a) Disclaiming warranty or limiting liability differently from the b) Requiring preservation of specified reasonable legal notices or
terms of sections 15 and 16 of this License; or</li>
<li>b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or</li> Notices displayed by works containing it; or
<li>c) Prohibiting misrepresentation of the origin of that material, or c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or</li> reasonable ways as different from the original version; or
<li>d) Limiting the use for publicity purposes of names of licensors or d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or</li> authors of the material; or
<li>e) Declining to grant rights under trademark law for use of some e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or</li> trade names, trademarks, or service marks; or
<li>f) Requiring indemnification of licensors and authors of that f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on any liability that these contractual assumptions directly impose on
those licensors and authors.</li> those licensors and authors.
</ul> All other non-permissive additional terms are considered "further
<p>All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further restriction, governed by this License along with a term that is a further
you may remove that term. If a license document contains a further restriction, you may remove that term. If a license document contains
restriction but permits relicensing or conveying under this License, you a further restriction but permits relicensing or conveying under this
may add to a covered work material governed by the terms of that license License, you may add to a covered work material governed by the terms
document, provided that the further restriction does not survive such of that license document, provided that the further restriction does
relicensing or conveying.</p> not survive such relicensing or conveying.
<p>If you add terms to a covered work in accord with this section, you If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating additional terms that apply to those files, or a notice indicating
where to find the applicable terms.</p> where to find the applicable terms.
<p>Additional terms, permissive or non-permissive, may be stated in the Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions; form of a separately written license, or stated as exceptions;
the above requirements apply either way.</p> the above requirements apply either way.
<h4 id="section8">8. Termination.</h4> 8. Termination.
<p>You may not propagate or modify a covered work except as expressly You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third this License (including any patent licenses granted under the third
paragraph of section 11).</p> paragraph of section 11).
<p>However, if you cease all violation of this License, then your However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a) license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.</p> prior to 60 days after the cessation.
<p>Moreover, your license from a particular copyright holder is Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.</p> your receipt of the notice.
<p>Termination of your rights under this section does not terminate the Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same reinstated, you do not qualify to receive new licenses for the same
material under section 10.</p> material under section 10.
<h4 id="section9">9. Acceptance Not Required for Having Copies.</h4> 9. Acceptance Not Required for Having Copies.
<p>You are not required to accept this License in order to receive or You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However, to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.</p> covered work, you indicate your acceptance of this License to do so.
<h4 id="section10">10. Automatic Licensing of Downstream Recipients.</h4> 10. Automatic Licensing of Downstream Recipients.
<p>Each time you convey a covered work, the recipient automatically Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.</p> for enforcing compliance by third parties with this License.
<p>An "entity transaction" is a transaction transferring control of an An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that work results from an entity transaction, each party to that
@@ -469,23 +446,23 @@ transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.</p> the predecessor has it or can get it with reasonable efforts.
<p>You may not impose any further restrictions on the exercise of the You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that (including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.</p> sale, or importing the Program or any portion of it.
<h4 id="section11">11. Patents.</h4> 11. Patents.
<p>A "contributor" is a copyright holder who authorizes use under this A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".</p> work thus licensed is called the contributor's "contributor version".
<p>A contributor's "essential patent claims" are all patent claims A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version, by this License, of making, using, or selling its contributor version,
@@ -493,21 +470,21 @@ but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of patent sublicenses in a manner consistent with the requirements of
this License.</p> this License.
<p>Each contributor grants you a non-exclusive, worldwide, royalty-free Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.</p> propagate the contents of its contributor version.
<p>In the following three paragraphs, a "patent license" is any express In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to (such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a party means to make such an agreement or commitment not to enforce a
patent against the party.</p> patent against the party.
<p>If you convey a covered work, knowingly relying on a patent license, If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means, publicly available network server or other readily accessible means,
@@ -519,17 +496,17 @@ license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.</p> country that you have reason to believe are valid.
<p>If, pursuant to or in connection with a single transaction or If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered you grant is automatically extended to all recipients of the covered
work and works based on it.</p> work and works based on it.
<p>A patent license is "discriminatory" if it does not include within A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered specifically granted under this License. You may not convey a covered
@@ -542,15 +519,15 @@ patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement, contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.</p> or that patent license was granted, prior to 28 March 2007.
<p>Nothing in this License shall be construed as excluding or limiting Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.</p> otherwise be available to you under applicable patent law.
<h4 id="section12">12. No Surrender of Others' Freedom.</h4> 12. No Surrender of Others' Freedom.
<p>If conditions are imposed on you (whether by court order, agreement or If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this covered work so as to satisfy simultaneously your obligations under this
@@ -558,11 +535,11 @@ License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.</p> License would be to refrain entirely from conveying the Program.
<h4 id="section13">13. Remote Network Interaction; Use with the GNU General Public License.</h4> 13. Remote Network Interaction; Use with the GNU General Public License.
<p>Notwithstanding any other provision of this License, if you modify the Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding supports such interaction) an opportunity to receive the Corresponding
@@ -571,56 +548,56 @@ from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3 shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the of the GNU General Public License that is incorporated pursuant to the
following paragraph.</p> following paragraph.
<p>Notwithstanding any other provision of this License, you have permission Notwithstanding any other provision of this License, you have
to link or combine any covered work with a work licensed under version 3 permission to link or combine any covered work with a work licensed
of the GNU General Public License into a single combined work, and to under version 3 of the GNU General Public License into a single
convey the resulting work. The terms of this License will continue to combined work, and to convey the resulting work. The terms of this
apply to the part which is the covered work, but the work with which it is License will continue to apply to the part which is the covered work,
combined will remain governed by version 3 of the GNU General Public but the work with which it is combined will remain governed by version
License.</p> 3 of the GNU General Public License.
<h4 id="section14">14. Revised Versions of this License.</h4> 14. Revised Versions of this License.
<p>The Free Software Foundation may publish revised and/or new versions of The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new the GNU Affero General Public License from time to time. Such new versions
versions will be similar in spirit to the present version, but may differ will be similar in spirit to the present version, but may differ in detail to
in detail to address new problems or concerns.</p> address new problems or concerns.
<p>Each version is given a distinguishing version number. If the Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero Program specifies that a certain numbered version of the GNU Affero General
General Public License "or any later version" applies to it, you have Public License "or any later version" applies to it, you have the
the option of following the terms and conditions either of that option of following the terms and conditions either of that numbered
numbered version or of any later version published by the Free version or of any later version published by the Free Software
Software Foundation. If the Program does not specify a version number Foundation. If the Program does not specify a version number of the
of the GNU Affero General Public License, you may choose any version GNU Affero General Public License, you may choose any version ever published
ever published by the Free Software Foundation.</p> by the Free Software Foundation.
<p>If the Program specifies that a proxy can decide which future If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that versions of the GNU Affero General Public License can be used, that proxy's
proxy's public statement of acceptance of a version permanently public statement of acceptance of a version permanently authorizes you
authorizes you to choose that version for the Program.</p> to choose that version for the Program.
<p>Later license versions may give you additional or different Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a author or copyright holder as a result of your choosing to follow a
later version.</p> later version.
<h4 id="section15">15. Disclaimer of Warranty.</h4> 15. Disclaimer of Warranty.
<p>THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.</p> ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
<h4 id="section16">16. Limitation of Liability.</h4> 16. Limitation of Liability.
<p>IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
@@ -628,37 +605,37 @@ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.</p> SUCH DAMAGES.
<h4 id="section17">17. Interpretation of Sections 15 and 16.</h4> 17. Interpretation of Sections 15 and 16.
<p>If the disclaimer of warranty and limitation of liability provided If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms, above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.</p> copy of the Program in return for a fee.
<p>END OF TERMS AND CONDITIONS</p> END OF TERMS AND CONDITIONS
<h4 id="howto">How to Apply These Terms to Your New Programs</h4> How to Apply These Terms to Your New Programs
<p>If you develop a new program, and you want it to be of the greatest If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.</p> free software which everyone can redistribute and change under these terms.
<p>To do so, attach the following notices to the program. It is safest To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.</p> the "copyright" line and a pointer to where the full notice is found.
<pre> &lt;one line to give the program's name and a brief idea of what it does.&gt; <one line to give the program's name and a brief idea of what it does.>
Copyright (C) &lt;year&gt; &lt;name of author&gt; Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as it under the terms of the GNU Affero General Public License as published by
published by the Free Software Foundation, either version 3 of the the Free Software Foundation, either version 3 of the License, or
License, or (at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -666,23 +643,19 @@ the "copyright" line and a pointer to where the full notice is found.</p>
GNU Affero General Public License for more details. GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License You should have received a copy of the GNU Affero General Public License
along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;. along with this program. If not, see <https://www.gnu.org/licenses/>.
</pre>
<p>Also add information on how to contact you by electronic and paper mail.</p> Also add information on how to contact you by electronic and paper mail.
<p>If your software can interact with users remotely through a computer If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the solutions will be better for different programs; see section 13 for the
specific requirements.</p> specific requirements.
<p>You should also get your employer (if you work as a programmer) or school, You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary. if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see For more information on this, and how to apply and follow the GNU AGPL, see
&lt;<a href="https://www.gnu.org/licenses/">https://www.gnu.org/licenses/</a>&gt;.</p> <https://www.gnu.org/licenses/>.
</body></html>
File renamed without changes.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 18 KiB

+2 -2
View File
@@ -8,12 +8,12 @@
"theme_color": "#000000", "theme_color": "#000000",
"icons": [ "icons": [
{ {
"src": "/shakespeare.png", "src": "/favicon.png",
"sizes": "192x192", "sizes": "192x192",
"type": "image/png" "type": "image/png"
}, },
{ {
"src": "/shakespeare.png", "src": "/favicon.png",
"sizes": "512x512", "sizes": "512x512",
"type": "image/png" "type": "image/png"
} }
-63
View File
@@ -1,63 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 25.2.3, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="レイヤー_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px"
y="0px" viewBox="0 0 128 128" style="enable-background:new 0 0 128 128;" xml:space="preserve">
<g>
<g>
<path style="fill:#F45125;" d="M110.28,61.32l2.63,8.84c0,0,7.24-1.6,7.62,3.2c0.38,4.8-6.77,8-6.77,8l2.26,10.63
c0,0,7.9-6.4,8-15.61c0,0,0.66-11.29-6.11-13.92C113.67,60.85,110.28,61.32,110.28,61.32z"/>
<path style="fill:#F45125;" d="M68.71,94.99c0,0-11.1-4.7-16.46,1.98c-0.75,0.94-1.41,1.88-2.16,2.82
c-0.56,0.75-1.13,1.5-1.69,2.16c-0.47,0.56-1.03,1.13-1.69,1.5c-0.66,0.38-1.32,0.66-2.07,0.85c-0.94,0.19-1.88,0.19-2.82,0.09
c-1.32-0.09-2.63-0.38-3.95-0.66c-0.47-0.09-0.85-0.19-1.22-0.28c-0.09,0-0.19-0.09-0.28-0.09s-0.19-0.09-0.28-0.09
c-0.38,0.09,0.19,0.75,0.38,0.94c0.28,0.28,0.56,0.66,0.85,0.94c0.85,0.75,1.69,1.5,2.73,1.98c1.32,0.66,2.73,1.03,4.14,1.13
c0.09,0,0.38,0,0.47,0.09c0.19,0.19-0.28,0.47-0.47,0.56c-0.28,0.19-0.47,0.28-0.75,0.38c-0.85,0.38-1.79,0.56-2.63,0.75
c-0.85,0.19-1.69,0.28-2.45,0.28c-0.47,0-0.85,0.09-1.22,0.09c-0.28,0-0.56-0.09-0.85,0s0.09,0.47,0.28,0.56
c0.38,0.19,0.75,0.47,1.13,0.66c1.13,0.56,2.26,1.03,3.39,1.32c1.5,0.38,3.1,0.56,4.61,0.38c1.32-0.19,2.63-0.56,3.86-1.03
c6.77-3.1,6.21-9.59,12.42-10.16c4.61-0.38,11.1,2.07,11.1,2.07L68.71,94.99z"/>
<path style="fill:#F45125;" d="M19.79,38.28c0,0-12.13,1.98-15.24,12.79C0.61,64.9,20.26,69.5,20.26,69.5l1.22-9.41
c0,0-13.07-1.32-12.32-6.3c0.94-6.21,11.85-5.64,11.85-5.64L19.79,38.28z"/>
<path style="fill:#F45125;" d="M20.73,70.92c0,0-1.88,0.56-4.61,2.54c-1.88,1.32-4.42,3.01-6.87,5.93
c-1.22,1.41-2.16,3.1-2.82,4.89c-0.47,1.22-0.66,2.45-0.66,3.76c0,0.28,0,0.56,0,0.85c0,0.09,0,0.85,0.28,0.66
c0.09-0.09,0.19-0.38,0.28-0.47c0.19-0.47,0.47-0.85,0.75-1.22c0.85-1.13,1.88-2.16,3.01-3.01c0.38-0.28,0.75-0.47,1.13-0.66
c0.28-0.28,0.75-0.66,0.94-0.28c0.09,0.19-0.09,0.47-0.19,0.66c-0.09,0.28-0.19,0.66-0.19,0.94c-0.38,1.5-0.56,3.01-0.75,4.51
c-0.09,0.85-0.09,1.69,0,2.45c0,0.38,0.09,0.85,0.09,1.22c0,0.19,0.09,0.38,0.09,0.56c0,0.19,0.19,0.47,0.38,0.19
c0.09-0.09,0.09-0.19,0.19-0.38c0.19-0.28,0.28-0.66,0.47-0.94c0.47-0.85,0.94-1.69,1.5-2.63c0.66-1.13,1.41-2.16,2.16-3.1
c0.85-1.13,1.88-2.26,2.92-3.2c1.13-1.03,2.35-2.07,3.67-2.92c0.75-0.47,1.6-0.94,2.45-1.32L20.73,70.92z"/>
<g>
<path style="fill:#FCC21B;" d="M116.4,79.29c-1.13-5.55-2.73-11.01-4.51-16.46c-1.5-4.61-3.1-9.31-5.83-13.36
c-1.22-1.79-3.01-3.01-5.27-3.86c-4.33-1.69-9.97-1.98-13.73-1.98c-5.64,0-11.48,1.22-16.74,3.67
c-1.88,5.64-7.05,19.94-14.86,26.34c0.47,2.63,1.03,5.36,1.79,8c1.32,4.61,3.01,9.22,4.61,13.83c1.5,4.42,3.29,8.84,6.58,12.23
c0.85,0.94,1.88,1.69,2.82,2.45c2.26,1.88,4.99,3.01,7.71,3.95c2.54,0.85,5.17,1.5,7.81,2.07c4.7,1.03,11.48,2.82,16.08,0.66
c2.54-1.13,4.61-2.92,6.3-5.08c1.79-2.26,3.2-4.8,4.42-7.43c1.88-3.95,3.86-8.37,4.14-12.89
C117.99,87.38,117.24,83.24,116.4,79.29z"/>
<path style="fill:#429ADF;" d="M77.64,33.57c-0.28-1.03-1.03-2.07-1.6-3.01c-6.3-11.01-20.04-16.27-32.26-15.52
c-3.76,0.28-9.31,0.85-13.54,2.73c-2.07,0.94-3.86,2.35-4.99,4.14c-2.54,4.23-3.76,8.94-5.08,13.64
C18.67,41,17.35,46.55,16.5,52.2c-0.75,4.89-1.41,10.25-0.09,15.14c1.03,3.86,3.29,9.22,5.74,12.32
c2.73,3.39,6.58,7.34,10.72,8.84c0.75,0.28,1.6,0.47,2.45,0.66c1.6,0.28,3.29,0.47,4.89,0.19c0.94-0.19,1.98-0.28,2.92-0.56
c1.88-0.47,3.67-1.13,5.46-1.79c7.52-3.01,13.64-7.43,17.68-14.58c1.69-3.1,3.1-6.4,4.42-9.69c0.09-0.19,0.19-0.38,0.19-0.56
c1.98-5.46,3.29-11.19,4.61-16.84c0.66-2.73,1.41-5.55,1.79-8.37C77.55,35.92,77.92,34.7,77.64,33.57z"/>
</g>
</g>
<path style="fill:#193D51;" d="M23.09,40.53c1.69-3.1,5.74-5.55,9.31-5.08c0.56,0.09,1.22,0.19,1.79,0.47
c3.57,1.5,5.74,4.99,4.89,8.56c-0.19,0.75-0.66,0.85-1.22,0.38c-1.98-1.69-3.57-3.01-6.21-3.67c-2.16-0.56-4.61-0.28-6.68,0.28
c-0.47,0.09-1.22,0.56-1.69,0.38C22.61,41.57,22.9,40.91,23.09,40.53z"/>
<path style="fill:#193D51;" d="M62.21,64.9c-1.03,1.6-2.45,3.01-3.86,4.33c-0.38,0.28-0.66,0.66-1.03,0.94
c-5.64,4.7-13.26,7.05-20.51,5.27c-1.98-0.47-4.14-1.5-5.74-2.73c-1.22-0.94-2.45-2.16-3.48-3.39c-1.88-2.26-3.29-4.89-4.23-7.62
c-0.47-1.41-0.75-2.73-0.94-4.23c0-0.47-0.66-5.46,0.85-4.8c0.38,0.19,0.66,0.47,0.94,0.75c0.28,0.38,0.47,0.75,0.75,1.03
c0.66,0.85,1.32,1.69,2.07,2.45c2.35,2.73,5.27,4.89,8.56,6.4c2.26,1.03,4.7,1.6,7.15,1.79c1.41,0.09,2.73,0.19,4.14,0.09
c5.08-0.28,10.25-1.79,14.86-3.76c0.38-0.19,0.85-0.47,1.32-0.47C64.66,61.04,62.5,64.52,62.21,64.9z"/>
<path style="fill:#193D51;" d="M67.58,51.16c0,0.47-0.19,1.13-0.75,1.03c-0.47-0.09-0.85-0.94-1.13-1.22
c-1.32-1.69-3.86-3.57-6.4-4.14c-3.01-0.75-5.27,0.56-8.28,0.85c-0.85,0.09-1.32-0.28-0.94-1.03c1.6-3.48,5.83-6.21,10.25-5.46
c0.75,0.09,1.41,0.28,2.07,0.56C66.26,43.36,67.86,47.59,67.58,51.16z"/>
<path style="fill:#9B7515;" d="M91.84,63.86c4.23,2.73,9.69,3.48,14.58,3.2c1.41-0.09,2.26,0.09,1.88,1.69
c-0.75,3.29-3.86,5.17-6.87,5.83c-0.75,0.19-1.5,0.19-2.26,0.19c-1.41-0.09-2.82-0.66-4.04-1.5c-2.63-1.79-4.61-4.89-5.17-8
C89.68,63.67,90.25,62.83,91.84,63.86z"/>
<path style="fill:#9B7515;" d="M65.22,80.79C64,79.57,64.66,79,65.98,78.25c4.51-2.35,9.03-5.93,11.38-10.63
c0.85-1.79,1.79-1.41,2.45,0.28c1.13,3.1,1.03,6.87-0.38,9.88c-0.66,1.41-1.6,2.63-2.82,3.57c-0.66,0.47-1.32,0.75-2.07,1.03
C71.43,83.33,67.58,83.24,65.22,80.79z"/>
<path style="fill:#9B7515;" d="M110,96.41c-0.38,0-0.94-0.38-1.41-0.66c-0.47-0.28-0.94-0.66-1.22-0.85
c-1.13-0.56-2.45-1.13-3.67-1.5c-3.76-1.22-7.9-1.22-11.57,0c-2.63,0.85-5.17,2.45-7.24,4.33c-2.26,2.16-3.95,4.8-6.11,7.05
c-0.28,0.28-0.56,0.56-0.85,0.75c-0.56,0.28-1.13-0.09-1.32-0.66c-0.94-3.95,1.69-9.5,3.67-12.89c2.26-3.76,5.55-6.77,9.78-8
c2.07-0.66,4.33-0.66,6.49-0.38c6.3,0.94,12.79,5.93,14.02,11.66C110.56,95.75,110.47,96.5,110,96.41z"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 5.8 KiB

+11 -13
View File
@@ -16,10 +16,9 @@ import { AISettingsProvider } from '@/components/AISettingsProvider';
import { GitSettingsProvider } from '@/components/GitSettingsProvider'; import { GitSettingsProvider } from '@/components/GitSettingsProvider';
import { SessionManagerProvider } from '@/components/SessionManagerProvider'; import { SessionManagerProvider } from '@/components/SessionManagerProvider';
import { FSProvider } from '@/components/FSProvider'; import { FSProvider } from '@/components/FSProvider';
import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider'; import { ConsoleProvider } from '@/contexts/ConsoleContext';
import { LightningFSAdapter } from '@/lib/LightningFSAdapter'; import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
import { cleanupTmpDirectory } from '@/lib/tmpCleanup'; import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
import { DynamicFavicon } from '@/components/DynamicFavicon';
import AppRouter from './AppRouter'; import AppRouter from './AppRouter';
@@ -40,7 +39,7 @@ const queryClient = new QueryClient({
}); });
const defaultConfig: AppConfig = { const defaultConfig: AppConfig = {
theme: "system", theme: "light",
relayUrl: "wss://relay.primal.net", relayUrl: "wss://relay.primal.net",
deployServer: "shakespeare.wtf", deployServer: "shakespeare.wtf",
}; };
@@ -75,25 +74,24 @@ export function App() {
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}> <AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
<FSProvider fs={fs}> <FSProvider fs={fs}>
<FSCleanupHandler /> <FSCleanupHandler />
<ConsoleErrorProvider> <ConsoleProvider>
<NostrLoginProvider storageKey='nostr:login'> <NostrLoginProvider storageKey='nostr:login'>
<NostrProvider> <NostrProvider>
<AISettingsProvider> <AISettingsProvider>
<GitSettingsProvider> <GitSettingsProvider>
<SessionManagerProvider> <SessionManagerProvider>
<TooltipProvider> <TooltipProvider>
<Toaster /> <Toaster />
<DynamicFavicon /> <Suspense>
<Suspense> <AppRouter />
<AppRouter /> </Suspense>
</Suspense> </TooltipProvider>
</TooltipProvider> </SessionManagerProvider>
</SessionManagerProvider>
</GitSettingsProvider> </GitSettingsProvider>
</AISettingsProvider> </AISettingsProvider>
</NostrProvider> </NostrProvider>
</NostrLoginProvider> </NostrLoginProvider>
</ConsoleErrorProvider> </ConsoleProvider>
</FSProvider> </FSProvider>
</AppProvider> </AppProvider>
</QueryClientProvider> </QueryClientProvider>
+2 -3
View File
@@ -11,12 +11,11 @@ import AISettings from "./pages/AISettings";
import GitSettings from "./pages/GitSettings"; import GitSettings from "./pages/GitSettings";
import DataSettings from "./pages/DataSettings"; import DataSettings from "./pages/DataSettings";
import AboutSettings from "./pages/AboutSettings"; import AboutSettings from "./pages/AboutSettings";
import EmailSettings from "./pages/EmailSettings";
import GitHubOAuth from "./pages/GitHubOAuth"; import GitHubOAuth from "./pages/GitHubOAuth";
import { NIP19Page } from "./pages/NIP19Page"; import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound"; import NotFound from "./pages/NotFound";
import { ProjectView } from "./pages/ProjectView"; import { ProjectView } from "./pages/ProjectView";
import { TextChatView } from "./pages/TextChatView";
import { SettingsLayout } from "./components/SettingsLayout"; import { SettingsLayout } from "./components/SettingsLayout";
export function AppRouter() { export function AppRouter() {
@@ -35,10 +34,10 @@ export function AppRouter() {
<Route path="ai" element={<AISettings />} /> <Route path="ai" element={<AISettings />} />
<Route path="git" element={<GitSettings />} /> <Route path="git" element={<GitSettings />} />
<Route path="data" element={<DataSettings />} /> <Route path="data" element={<DataSettings />} />
<Route path="email" element={<EmailSettings />} />
<Route path="about" element={<AboutSettings />} /> <Route path="about" element={<AboutSettings />} />
</Route> </Route>
<Route path="/project/:projectId" element={<ProjectView />} /> <Route path="/project/:projectId" element={<ProjectView />} />
<Route path="/chat/:chatId" element={<TextChatView />} />
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */} {/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
<Route path="/:nip19" element={<NIP19Page />} /> <Route path="/:nip19" element={<NIP19Page />} />
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */} {/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
+3 -8
View File
@@ -1,6 +1,6 @@
import { memo, useState } from 'react'; import { memo, useState } from 'react';
import { Streamdown } from 'streamdown'; import { Streamdown } from 'streamdown';
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2, Logs } 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 type { AIMessage } from '@/lib/SessionManager';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { UserMessage } from '@/components/UserMessage'; import { UserMessage } from '@/components/UserMessage';
@@ -69,8 +69,8 @@ export const AIMessageItem = memo(({
case 'text_editor_view': { case 'text_editor_view': {
const title = args.path const title = args.path
? (args.start_line || args.end_line ? (args.start_line || args.end_line
? `Viewed ${args.path} (lines ${args.start_line || 1}-${args.end_line || 'end'})` ? `Viewed ${args.path} (lines ${args.start_line || 1}-${args.end_line || 'end'})`
: `Viewed ${args.path}`) : `Viewed ${args.path}`)
: 'Viewed File'; : 'Viewed File';
return { icon: Eye, title }; return { icon: Eye, title };
} }
@@ -150,11 +150,6 @@ export const AIMessageItem = memo(({
icon: CheckCircle, icon: CheckCircle,
title: 'TypeScript' title: 'TypeScript'
}; };
case 'read_console_messages':
return {
icon: Logs,
title: 'Read Console'
};
default: default:
return { return {
icon: Wrench, icon: Wrench,
-4
View File
@@ -57,7 +57,6 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
// If providers are being updated, invalidate the provider-models query // If providers are being updated, invalidate the provider-models query
if ('providers' in newSettings) { if ('providers' in newSettings) {
queryClient.invalidateQueries({ queryKey: ['provider-models'] }); queryClient.invalidateQueries({ queryKey: ['provider-models'] });
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
} }
}; };
@@ -81,7 +80,6 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
} }
}); });
queryClient.invalidateQueries({ queryKey: ['provider-models'] }); queryClient.invalidateQueries({ queryKey: ['provider-models'] });
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
}; };
const removeProvider = (id: string) => { const removeProvider = (id: string) => {
@@ -90,7 +88,6 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
providers: prev.providers.filter(provider => provider.id !== id), providers: prev.providers.filter(provider => provider.id !== id),
})); }));
queryClient.invalidateQueries({ queryKey: ['provider-models'] }); queryClient.invalidateQueries({ queryKey: ['provider-models'] });
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
}; };
const setProviders = (providers: AIProvider[]) => { const setProviders = (providers: AIProvider[]) => {
@@ -99,7 +96,6 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
providers, providers,
})); }));
queryClient.invalidateQueries({ queryKey: ['provider-models'] }); queryClient.invalidateQueries({ queryKey: ['provider-models'] });
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
}; };
const addRecentlyUsedModel = (modelId: string) => { const addRecentlyUsedModel = (modelId: string) => {
-350
View File
@@ -1,350 +0,0 @@
import { useState, useEffect } from 'react';
import { ArrowRight, ArrowLeft, Download, Upload, ExternalLink, Sparkles } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
// import { useAISettings } from '@/hooks/useAISettings';
import { useAICredits } from '@/hooks/useAICredits';
// import { useLocalStorage } from '@/hooks/useLocalStorage';
interface Act1DialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
type DialogStep = 'welcome' | 'migration' | 'credits' | 'conclusion';
const SHAKESPEARE_PROVIDER = {
id: "shakespeare",
baseURL: "https://ai.shakespeare.diy/v1",
nostr: true,
};
// const MKSTACK_NSP_ADDR = '31999:4bcaa7b5606e3c14df05cd497e588f5d3fe559b4e9a425e8b418a43af1ffb015:mkstack';
export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
const [step, setStep] = useState<DialogStep>('welcome');
// const { setProvider, updateSettings } = useAISettings();
// // Get the selectedNSPAddr from localStorage
// const [selectedNSPAddr] = useLocalStorage<string | null>('selectedNSPAddr', null);
// Get user's credits
const { data: creditsData } = useAICredits(SHAKESPEARE_PROVIDER);
const handleGetStarted = async () => {
try {
// // Add Shakespeare provider to their config
// setProvider(SHAKESPEARE_PROVIDER);
// // Configure recently used models based on credits or NSP
// const hasCredits = creditsData?.amount && creditsData.amount > 0;
// const hasMKStackNSP = selectedNSPAddr === MKSTACK_NSP_ADDR;
// if (hasCredits || hasMKStackNSP) {
// // User has credits or MKStack NSP - set to shakespeare model
// updateSettings({ recentlyUsedModels: ['shakespeare/shakespeare'] });
// } else {
// // No credits - set to tybalt model (free)
// updateSettings({ recentlyUsedModels: ['shakespeare/tybalt'] });
// }
// Move to migration step
setStep('migration');
} catch (error) {
console.error('Failed to configure Shakespeare provider:', error);
}
};
const handleContinue = () => {
setStep('credits');
};
const handleCreditsNext = () => {
setStep('conclusion');
};
const handleFinish = () => {
// Mark that the user is a previous Act 1 user
localStorage.setItem('act1', 'true');
// Remove the selectedNSPAddr from localStorage
localStorage.removeItem('selectedNSPAddr');
onOpenChange(false);
};
const handleVisitAct1 = () => {
window.open('https://act1.shakespeare.diy', '_blank');
};
// Reset state when dialog opens/closes
useEffect(() => {
if (open) {
setStep('welcome');
}
}, [open]);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-hidden">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
{step === 'migration' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('welcome')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{step === 'credits' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('migration')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{step === 'conclusion' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('credits')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
</DialogTitle>
</DialogHeader>
<div className="overflow-y-auto max-h-[calc(90vh-120px)] pr-2">
<div className="space-y-6 py-4">
{step === 'welcome' && (
<div className="text-center space-y-6">
<div className="text-6xl mb-4">🎭✨</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Welcome to Act 2!
</h2>
<p className="text-lg text-muted-foreground max-w-lg mx-auto">
We're excited to see you again! Shakespeare has been completely rebuilt
with new features, improved performance, and a better development experience.
</p>
</div>
<Card className="max-w-lg mx-auto text-left">
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<span className="text-2xl">🔄</span>
What's Changed
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="flex items-start gap-3">
<Badge variant="secondary" className="mt-0.5">New</Badge>
<div>
<p className="font-medium">Use any AI Provider</p>
<p className="text-sm text-muted-foreground">Your browser connects to AI providers directly</p>
</div>
</div>
<div className="flex items-start gap-3">
<Badge variant="secondary" className="mt-0.5">New</Badge>
<div>
<p className="font-medium">Git Integration</p>
<p className="text-sm text-muted-foreground">Push to GitHub, Nostr relays, and more</p>
</div>
</div>
<div className="flex items-start gap-3">
<Badge variant="secondary" className="mt-0.5">New</Badge>
<div>
<p className="font-medium">Your Files</p>
<p className="text-sm text-muted-foreground">Files are stored on your device directly in your browser</p>
</div>
</div>
</CardContent>
</Card>
<div className="bg-amber-50 dark:bg-amber-950/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4 max-w-lg mx-auto">
<div className="flex items-start gap-3">
<span className="text-amber-600 dark:text-amber-400 text-lg">⚠️</span>
<div className="text-left">
<p className="font-medium text-amber-800 dark:text-amber-200">Act 2 is in Development</p>
<p className="text-sm text-amber-700 dark:text-amber-300">
While we're working hard to make Act 2 stable, you may encounter bugs.
Your Act 1 projects remain safe and accessible.
</p>
</div>
</div>
</div>
<Button
onClick={handleGetStarted}
size="lg"
className="gap-2"
>
Next
</Button>
</div>
)}
{step === 'migration' && (
<div className="space-y-6">
<div className="text-center space-y-3">
<h2 className="text-xl font-bold">Your Act 1 Projects & Credits</h2>
<p className="text-muted-foreground max-w-lg mx-auto">
All your Act 1 projects and credits are safe and still accessible.
Here's how to work with them in Act 2.
</p>
</div>
<div className="text-center">
<Button
variant="outline"
onClick={handleVisitAct1}
className="gap-2"
>
<ExternalLink className="h-4 w-4" />
Visit Act 1
</Button>
</div>
<div className="grid gap-4">
<Card>
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<Download className="h-5 w-5 text-green-500" />
Export from Act 1
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-sm text-muted-foreground">
In Act 1, you can export your projects as ZIP files using the project menu.
</p>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<Upload className="h-5 w-5 text-purple-500" />
Import to Act 2
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-sm text-muted-foreground">
In Act 2, use the "Import Project" option in the sidebar to upload your exported ZIP files.
</p>
</CardContent>
</Card>
</div>
<div className="flex justify-end pt-4">
<Button
onClick={handleContinue}
className="gap-2"
>
Continue
<ArrowRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
{step === 'credits' && (
<div className="text-center space-y-6">
<div className="text-6xl mb-4">💳</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold">Your Credits</h2>
<p className="text-lg text-muted-foreground max-w-md mx-auto">
Your Act 1 credits are still available through the Shakespeare AI provider.
</p>
</div>
<Card className="max-w-md mx-auto">
<CardContent className="pt-6">
{creditsData?.amount && creditsData.amount > 0 ? (
<div className="text-center space-y-4">
<div className="space-y-2">
<div className="text-3xl font-bold text-green-600 dark:text-green-400">
${creditsData.amount.toFixed(2)}
</div>
<p className="text-sm text-muted-foreground">
Available credits
</p>
</div>
<div className="bg-green-50 dark:bg-green-950/20 border border-green-200 dark:border-green-800 rounded-lg p-3">
<p className="text-sm text-green-800 dark:text-green-200">
✅ You're all set! We've configured the premium Shakespeare model for you.
</p>
</div>
</div>
) : (
<div className="text-center space-y-4">
<div className="space-y-2">
<div className="text-2xl">🆓</div>
<p className="font-medium">Free Access</p>
</div>
<div className="bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800 rounded-lg p-3">
<p className="text-sm text-blue-800 dark:text-blue-200">
You can continue using Shakespeare for free with the Tybalt model.
It's perfect for learning and building amazing projects!
</p>
</div>
</div>
)}
</CardContent>
</Card>
<div className="flex justify-end pt-4">
<Button
onClick={handleCreditsNext}
className="gap-2"
>
Continue
<ArrowRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
{step === 'conclusion' && (
<div className="text-center space-y-6">
<div className="text-5xl mb-4">🎉</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold">Welcome to the Future!</h2>
<p className="text-lg text-muted-foreground max-w-md mx-auto">
You're all up to speed with Act 2! Get ready to build amazing Nostr applications.
</p>
</div>
<div className="space-y-3">
<Button onClick={handleFinish} size="lg" className="gap-2">
<Sparkles className="h-4 w-4" />
Start Building in Act 2
</Button>
<div className="text-xs text-muted-foreground">
Remember: You can always access Act 1 at{' '}
<button
onClick={handleVisitAct1}
className="text-primary hover:underline"
>
act1.shakespeare.diy
</button>
</div>
</div>
</div>
)}
</div>
</div>
</DialogContent>
</Dialog>
);
}
+29 -31
View File
@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback } from 'react'; import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { type ChatItem } from '@/lib/ProjectsManager'; import { type Project } from '@/lib/ProjectsManager';
import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useProjectsManager } from '@/hooks/useProjectsManager';
import { ProjectSidebar } from '@/components/ProjectSidebar'; import { ProjectSidebar } from '@/components/ProjectSidebar';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
@@ -9,7 +9,7 @@ import { useIsMobile } from '@/hooks/useIsMobile';
interface AppLayoutProps { interface AppLayoutProps {
children: React.ReactNode; children: React.ReactNode;
selectedProject?: ChatItem | null; selectedProject?: Project | null;
title?: string; title?: string;
showSidebar?: boolean; showSidebar?: boolean;
headerContent?: React.ReactNode; headerContent?: React.ReactNode;
@@ -18,10 +18,11 @@ interface AppLayoutProps {
export function AppLayout({ export function AppLayout({
children, children,
selectedProject = null, selectedProject = null,
title = "Shakespeare",
showSidebar = true, showSidebar = true,
headerContent headerContent
}: AppLayoutProps) { }: AppLayoutProps) {
const [_projects, setProjects] = useState<ChatItem[]>([]); const [_projects, setProjects] = useState<Project[]>([]);
const projectsManager = useProjectsManager(); const projectsManager = useProjectsManager();
const navigate = useNavigate(); const navigate = useNavigate();
const isMobile = useIsMobile(); const isMobile = useIsMobile();
@@ -34,7 +35,7 @@ export function AppLayout({
const loadProjects = useCallback(async () => { const loadProjects = useCallback(async () => {
try { try {
await projectsManager.init(); await projectsManager.init();
const projectList = await projectsManager.getAllChatItems(); const projectList = await projectsManager.getProjects();
setProjects(projectList); setProjects(projectList);
// Set initial sidebar state based on projects and device type // Set initial sidebar state based on projects and device type
@@ -59,14 +60,10 @@ export function AppLayout({
loadProjects(); loadProjects();
}, [loadProjects]); }, [loadProjects]);
const handleProjectSelect = (item: ChatItem | null) => { const handleProjectSelect = (project: Project | null) => {
if (item) { if (project) {
setIsSidebarVisible(false); // Collapse sidebar on mobile navigation setIsSidebarVisible(false); // Collapse sidebar on mobile navigation
if (item.type === 'project') { navigate(`/project/${project.id}`);
navigate(`/project/${item.id}`);
} else {
navigate(`/chat/${item.id}`);
}
} else { } else {
navigate('/'); navigate('/');
} }
@@ -76,22 +73,23 @@ export function AppLayout({
return ( return (
<div className="min-h-dvh bg-gradient-to-br from-primary/5 to-accent/5"> <div className="min-h-dvh bg-gradient-to-br from-primary/5 to-accent/5">
{/* Mobile Header */} {/* Mobile Header */}
<header className="bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur pt-safe"> <header className="h-12 border-b bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur px-4 py-3 flex items-center justify-between">
<div className="h-12 px-4 py-3 flex items-center justify-between border-b"> <div className="flex items-center space-x-2">
<div className="flex items-center space-x-2"> {showSidebar && (
{showSidebar && ( <Button
<Button variant="ghost"
variant="ghost" size="sm"
size="sm" onClick={() => setIsSidebarVisible(!isSidebarVisible)}
onClick={() => setIsSidebarVisible(!isSidebarVisible)} aria-label="Toggle sidebar"
aria-label="Toggle sidebar" >
> <Menu className="h-4 w-4" />
<Menu className="h-4 w-4" /> </Button>
</Button> )}
)} <h1 className="text-lg font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
</div> {title}
{headerContent} </h1>
</div> </div>
{headerContent}
</header> </header>
{/* Mobile Sidebar Overlay - show if showSidebar is true and sidebar is visible */} {/* Mobile Sidebar Overlay - show if showSidebar is true and sidebar is visible */}
@@ -105,10 +103,10 @@ export function AppLayout({
{/* Sidebar - positioned above the backdrop */} {/* Sidebar - positioned above the backdrop */}
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10"> <div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
<ProjectSidebar <ProjectSidebar
selectedItem={selectedProject} selectedProject={selectedProject}
onSelectItem={(item) => { onSelectProject={(project) => {
setIsSidebarVisible(false); // Always collapse sidebar on mobile navigation setIsSidebarVisible(false); // Always collapse sidebar on mobile navigation
handleProjectSelect(item); handleProjectSelect(project);
}} }}
onClose={() => setIsSidebarVisible(false)} onClose={() => setIsSidebarVisible(false)}
/> />
@@ -129,8 +127,8 @@ export function AppLayout({
{showSidebar && isSidebarVisible && ( {showSidebar && isSidebarVisible && (
<div className="w-80 border-r bg-sidebar transition-all duration-300"> <div className="w-80 border-r bg-sidebar transition-all duration-300">
<ProjectSidebar <ProjectSidebar
selectedItem={selectedProject} selectedProject={selectedProject}
onSelectItem={handleProjectSelect} onSelectProject={handleProjectSelect}
className="h-screen sticky top-0" className="h-screen sticky top-0"
onToggleSidebar={() => setIsSidebarVisible(false)} onToggleSidebar={() => setIsSidebarVisible(false)}
/> />
@@ -1,152 +0,0 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { ReactNode } from 'react';
import { ConsoleErrorProvider } from './ConsoleErrorProvider';
import { useConsoleError } from '@/hooks/useConsoleError';
import { addConsoleMessage, clearConsoleMessages, ProjectPreviewConsoleError } from '@/lib/consoleMessages';
// Wrapper component for testing
function TestWrapper({ children }: { children: ReactNode }) {
return (
<ConsoleErrorProvider>
{children}
</ConsoleErrorProvider>
);
}
describe('ConsoleErrorProvider', () => {
beforeEach(() => {
clearConsoleMessages();
});
it('should provide initial state with no errors', () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
expect(result.current.hasErrors).toBe(false);
expect(result.current.consoleError).toBeNull();
});
it('should update hasErrors when console error is added', async () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
expect(result.current.hasErrors).toBe(false);
// Add an error message
act(() => {
addConsoleMessage('error', 'Test error message');
});
expect(result.current.hasErrors).toBe(true);
expect(result.current.consoleError).toBeInstanceOf(ProjectPreviewConsoleError);
expect(result.current.consoleError?.message).toBe('Console error detected: Test error message');
});
it('should not update hasErrors for non-error messages', async () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
// Add non-error messages
act(() => {
addConsoleMessage('log', 'Test log message');
addConsoleMessage('warn', 'Test warning message');
addConsoleMessage('info', 'Test info message');
});
expect(result.current.hasErrors).toBe(false);
expect(result.current.consoleError).toBeNull();
});
it('should update consoleError with latest error message', () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
// Add first error
act(() => {
addConsoleMessage('error', 'First error');
});
expect(result.current.consoleError?.message).toBe('Console error detected: First error');
// Add second error - should update to show latest error
act(() => {
addConsoleMessage('error', 'Second error');
});
expect(result.current.consoleError?.message).toBe('Console error detected: Second error');
expect(result.current.consoleError?.logs).toHaveLength(2);
});
it('should clear errors when clearErrors is called', async () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
// Add error to set state
act(() => {
addConsoleMessage('error', 'Test error message');
});
expect(result.current.hasErrors).toBe(true);
expect(result.current.consoleError).not.toBeNull();
// Clear errors
act(() => {
result.current.clearErrors();
});
expect(result.current.hasErrors).toBe(false);
expect(result.current.consoleError).toBeNull();
});
it('should dismiss console error when dismissConsoleError is called', async () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
// Add error to create console error
act(() => {
addConsoleMessage('error', 'Test error message');
});
expect(result.current.consoleError).not.toBeNull();
// Dismiss console error (this only clears the Quilly error, not the global state)
act(() => {
result.current.dismissConsoleError();
});
expect(result.current.consoleError).toBeNull();
// hasErrors should still be true since we only dismissed the Quilly display
expect(result.current.hasErrors).toBe(true);
});
it('should include all error messages in console error logs', () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
// Add multiple errors and non-errors
act(() => {
addConsoleMessage('log', 'Log message');
addConsoleMessage('error', 'First error');
addConsoleMessage('warn', 'Warning message');
addConsoleMessage('error', 'Second error');
addConsoleMessage('info', 'Info message');
addConsoleMessage('error', 'Third error');
});
expect(result.current.consoleError?.message).toBe('Console error detected: Third error');
expect(result.current.consoleError?.logs).toHaveLength(3);
expect(result.current.consoleError?.logs.map(log => log.message)).toEqual([
'First error',
'Second error',
'Third error'
]);
});
});
-63
View File
@@ -1,63 +0,0 @@
import { useState, useEffect, useCallback, ReactNode } from 'react';
import {
addConsoleMessageListener,
removeConsoleMessageListener,
getHasConsoleErrors,
getConsoleMessages,
clearConsoleMessages,
ProjectPreviewConsoleError
} from '@/lib/consoleMessages';
import { ConsoleErrorContext } from '@/contexts/ConsoleErrorContext';
interface ConsoleErrorProviderProps {
children: ReactNode;
}
export function ConsoleErrorProvider({ children }: ConsoleErrorProviderProps) {
const [hasErrors, setHasErrors] = useState(() => getHasConsoleErrors());
const [consoleError, setConsoleError] = useState<ProjectPreviewConsoleError | null>(null);
const updateState = useCallback(() => {
const hasConsoleErrors = getHasConsoleErrors();
setHasErrors(hasConsoleErrors);
if (hasConsoleErrors) {
const errorMessages = getConsoleMessages().filter(msg => msg.level === 'error');
const latestError = errorMessages[errorMessages.length - 1];
setConsoleError(new ProjectPreviewConsoleError(
`Console error detected: ${latestError.message}`,
errorMessages
));
} else {
setConsoleError(null);
}
}, []);
useEffect(() => {
addConsoleMessageListener(updateState);
updateState(); // Initial sync
return () => removeConsoleMessageListener(updateState);
}, [updateState]);
const clearErrors = useCallback(() => {
clearConsoleMessages();
}, []);
const dismissConsoleError = useCallback(() => {
setConsoleError(null);
}, []);
const value = {
hasErrors,
consoleError,
clearErrors,
dismissConsoleError,
};
return (
<ConsoleErrorContext.Provider value={value}>
{children}
</ConsoleErrorContext.Provider>
);
}
+123 -112
View File
@@ -9,7 +9,7 @@ import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator'; import { Separator } from '@/components/ui/separator';
import { Skeleton } from '@/components/ui/skeleton'; import { Skeleton } from '@/components/ui/skeleton';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useToast } from '@/hooks/useToast'; import { useToast } from '@/hooks/useToast';
import { createAIClient } from '@/lib/ai-client'; import { createAIClient } from '@/lib/ai-client';
import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useCurrentUser } from '@/hooks/useCurrentUser';
@@ -399,7 +399,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
return ( return (
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent onOpenAutoFocus={(e) => e.preventDefault()} className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-dvh-safe max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none"> <DialogContent className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-full max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none">
<DialogHeader className="flex-shrink-0"> <DialogHeader className="flex-shrink-0">
<DialogTitle className="flex items-center gap-2 text-lg"> <DialogTitle className="flex items-center gap-2 text-lg">
{lightningInvoice ? ( {lightningInvoice ? (
@@ -434,61 +434,68 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
<div className="flex-1 flex flex-col min-h-0"> <div className="flex-1 flex flex-col min-h-0">
{/* Add Credits Form - Fixed size section */} {/* Add Credits Form - Fixed size section */}
<div className="flex-shrink-0 space-y-4 px-1 -mx-1"> <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"> <div className="space-y-3">
<Label htmlFor="amount" className="text-sm font-medium">Amount (USD)</Label> <Input
<div className="space-y-3"> id="amount"
<Input type="number"
id="amount" step="0.01"
type="number" value={amount}
step="0.01" onChange={(e) => setAmount(Number(e.target.value))}
value={amount} placeholder="Enter amount"
onChange={(e) => setAmount(Number(e.target.value))} className="text-center text-lg font-medium"
placeholder="Enter amount" />
className="text-center text-lg font-medium" <div className="grid grid-cols-5 gap-2">
/> {PRESET_AMOUNTS.map((preset) => (
<div className="grid grid-cols-5 gap-2"> <Button
{PRESET_AMOUNTS.map((preset) => ( key={preset}
<Button variant={amount === preset ? "default" : "outline"}
key={preset} size="sm"
variant={amount === preset ? "default" : "outline"} onClick={() => setAmount(preset)}
size="sm" className="text-xs"
onClick={() => setAmount(preset)} >
className="text-xs"
>
${preset} ${preset}
</Button> </Button>
))} ))}
</div>
</div> </div>
</div>
<div className="space-y-3"> </div>
<Label className="text-sm font-medium">Payment Method</Label> </div>
<Tabs value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)} className="w-full">
<TabsList className="grid w-full grid-cols-2"> <div className="space-y-3">
<TabsTrigger value="stripe" className="flex items-center gap-2"> <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" /> <CreditCard className="h-4 w-4" />
Credit Card Credit Card
</TabsTrigger> </div>
<TabsTrigger value="lightning" className="flex items-center gap-2"> </SelectItem>
<SelectItem value="lightning">
<div className="flex items-center gap-2">
<Zap className="h-4 w-4" /> <Zap className="h-4 w-4" />
Lightning Lightning
</TabsTrigger> </div>
</TabsList> </SelectItem>
</Tabs> </SelectContent>
</div> </Select>
</div>
<Button <Button
onClick={handleAddCredits} onClick={handleAddCredits}
disabled={amount <= 0 || addCreditsMutation.isPending} disabled={amount <= 0 || addCreditsMutation.isPending}
className="w-full h-12 text-base font-medium" className="w-full h-12 text-base font-medium"
size="lg" size="lg"
> >
{addCreditsMutation.isPending && <RefreshCw className="h-4 w-4 mr-2 animate-spin" />} {addCreditsMutation.isPending && <RefreshCw className="h-4 w-4 mr-2 animate-spin" />}
{paymentMethod === 'stripe' ? 'Pay with Card' : 'Generate Invoice'} {paymentMethod === 'stripe' ? 'Pay with Card' : 'Generate Invoice'}
{amount > 0 && ` - ${formatCurrency(amount)}`} {amount > 0 && ` - ${formatCurrency(amount)}`}
</Button> </Button>
</div> </div>
<div className="flex-shrink-0 px-1 -mx-1 py-4"> <div className="flex-shrink-0 px-1 -mx-1 py-4">
@@ -502,13 +509,17 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
</div> </div>
<div className="flex-1 min-h-0 overflow-y-auto"> <div className="flex-1 min-h-0 overflow-y-auto">
{isLoadingPayments ? ( {isLoadingPayments ? (
<div className="p-3 border rounded-lg space-y-2"> <div className="space-y-3">
<div className="flex items-center gap-2"> {Array.from({ length: 3 }).map((_, i) => (
<Skeleton className="h-4 w-4 rounded" /> <div key={i} className="p-3 border rounded-lg space-y-2">
<Skeleton className="h-4 w-24" /> <div className="flex items-center gap-2">
<Skeleton className="h-4 w-16 ml-auto" /> <Skeleton className="h-4 w-4 rounded" />
</div> <Skeleton className="h-4 w-24" />
<Skeleton className="h-3 w-32" /> <Skeleton className="h-4 w-16 ml-auto" />
</div>
<Skeleton className="h-3 w-32" />
</div>
))}
</div> </div>
) : !payments || payments.length === 0 ? ( ) : !payments || payments.length === 0 ? (
<div className="flex-1 flex items-center justify-center"> <div className="flex-1 flex items-center justify-center">
@@ -521,65 +532,65 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
) : ( ) : (
<div className="space-y-2 pb-2"> <div className="space-y-2 pb-2">
{payments.map((payment) => ( {payments.map((payment) => (
<div <div
key={payment.id} key={payment.id}
className="p-3 border rounded-lg space-y-2 hover:bg-muted/30 transition-colors" 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 justify-between">
<div className="flex items-center gap-2 min-w-0 flex-1"> <div className="flex items-center gap-2 min-w-0 flex-1">
{getStatusIcon(payment.status)} {getStatusIcon(payment.status)}
<span className="text-sm font-medium truncate"> <span className="text-sm font-medium truncate">
{payment.method === 'stripe' ? 'Credit Card' : 'Lightning'} {payment.method === 'stripe' ? 'Credit Card' : 'Lightning'}
</span> </span>
<Badge variant={getStatusVariant(payment.status)} className="text-xs flex-shrink-0"> <Badge variant={getStatusVariant(payment.status)} className="text-xs flex-shrink-0">
{payment.status} {payment.status}
</Badge> </Badge>
</div> </div>
<div className="text-right flex-shrink-0"> <div className="text-right flex-shrink-0">
<p className="text-sm font-medium">{formatCurrency(payment.amount)}</p> <p className="text-sm font-medium">{formatCurrency(payment.amount)}</p>
{payment.fee > 0 && ( {payment.fee > 0 && (
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
+{formatCurrency(payment.fee)} +{formatCurrency(payment.fee)}
</p> </p>
)} )}
</div> </div>
</div> </div>
<div className="flex items-center justify-between text-xs text-muted-foreground"> <div className="flex items-center justify-between text-xs text-muted-foreground">
<span>{formatDate(payment.created_at)}</span> <span>{formatDate(payment.created_at)}</span>
{payment.status === 'pending' && ( {payment.status === 'pending' && (
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
onClick={() => checkPaymentMutation.mutate(payment.id)} onClick={() => checkPaymentMutation.mutate(payment.id)}
disabled={refreshingPayments.has(payment.id)} disabled={refreshingPayments.has(payment.id)}
className="h-6 px-2 text-xs" className="h-6 px-2 text-xs"
title="Refresh payment status" title="Refresh payment status"
> >
<RotateCcw className={`h-3 w-3 ${refreshingPayments.has(payment.id) ? 'animate-spin' : ''}`} /> <RotateCcw className={`h-3 w-3 ${refreshingPayments.has(payment.id) ? 'animate-spin' : ''}`} />
</Button> </Button>
{payment.url && ( {payment.url && (
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
onClick={() => { onClick={() => {
if (payment.method === 'lightning') { if (payment.method === 'lightning') {
setLightningInvoice(payment.url); setLightningInvoice(payment.url);
} else { } else {
window.open(payment.url, '_blank'); window.open(payment.url, '_blank');
} }
}} }}
className="h-6 px-2 text-xs" className="h-6 px-2 text-xs"
> >
<ExternalLink className="h-3 w-3 mr-1" /> <ExternalLink className="h-3 w-3 mr-1" />
{payment.method === 'lightning' ? 'Pay' : 'Pay'} {payment.method === 'lightning' ? 'Pay' : 'Pay'}
</Button> </Button>
)}
</div>
)} )}
</div> </div>
</div> )}
</div>
</div>
))} ))}
</div> </div>
)} )}
-151
View File
@@ -1,151 +0,0 @@
import { useEffect, useRef } from 'react';
import { useAnyProjectBusy } from '@/hooks/useAnyProjectBusy';
/**
* Component that dynamically updates the favicon when any project is busy with AI
* Rotates the favicon counter-clockwise when busy
*/
export function DynamicFavicon() {
const isBusy = useAnyProjectBusy();
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const animationRef = useRef<number | null>(null);
const rotationRef = useRef(0);
const originalFaviconRef = useRef<string | null>(null);
const originalImageRef = useRef<HTMLImageElement | null>(null);
// Initialize canvas and save original favicon
useEffect(() => {
// Create canvas element for drawing the favicon
if (!canvasRef.current) {
canvasRef.current = document.createElement('canvas');
canvasRef.current.width = 32;
canvasRef.current.height = 32;
}
// Store the original favicon URL
const faviconElement = document.querySelector('link[rel="icon"]');
if (faviconElement && !originalFaviconRef.current) {
originalFaviconRef.current = faviconElement.getAttribute('href');
}
// Preload the favicon image
if (!originalImageRef.current) {
const img = new Image();
img.crossOrigin = 'anonymous';
img.src = originalFaviconRef.current || '/shakespeare.png';
img.onload = () => {
originalImageRef.current = img;
};
}
return () => {
// Restore original favicon on unmount
if (originalFaviconRef.current) {
const faviconElement = document.querySelector('link[rel="icon"]');
if (faviconElement) {
faviconElement.setAttribute('href', originalFaviconRef.current);
}
}
// Cancel any ongoing animation
if (animationRef.current !== null) {
cancelAnimationFrame(animationRef.current);
}
};
}, []);
// Handle busy state changes
useEffect(() => {
if (!canvasRef.current) return;
// If busy, start rotation animation
if (isBusy) {
const startRotationAnimation = () => {
if (!canvasRef.current || !originalImageRef.current) {
// If image isn't loaded yet, try again in a moment
setTimeout(startRotationAnimation, 100);
return;
}
const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');
if (!ctx) return;
const img = originalImageRef.current;
const animate = () => {
if (!ctx || !canvas) return;
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Save context state
ctx.save();
// Translate to center for rotation
ctx.translate(canvas.width / 2, canvas.height / 2);
// Rotate counter-clockwise
ctx.rotate(-rotationRef.current);
// Draw the image centered
ctx.drawImage(
img,
-canvas.width / 2,
-canvas.height / 2,
canvas.width,
canvas.height
);
// Restore context state
ctx.restore();
// Update rotation for next frame (slower rotation)
rotationRef.current += 0.05;
// Update favicon
const faviconElement = document.querySelector('link[rel="icon"]');
if (faviconElement) {
faviconElement.setAttribute('href', canvas.toDataURL('image/png'));
}
// Continue animation
animationRef.current = requestAnimationFrame(animate);
};
// Start animation loop
animate();
};
startRotationAnimation();
} else {
// If not busy, restore original favicon and stop animation
if (animationRef.current !== null) {
cancelAnimationFrame(animationRef.current);
animationRef.current = null;
}
// Reset rotation
rotationRef.current = 0;
// Restore original favicon
if (originalFaviconRef.current) {
const faviconElement = document.querySelector('link[rel="icon"]');
if (faviconElement) {
faviconElement.setAttribute('href', originalFaviconRef.current);
}
}
}
return () => {
// Cancel animation on effect cleanup
if (animationRef.current !== null) {
cancelAnimationFrame(animationRef.current);
animationRef.current = null;
}
};
}, [isBusy]);
// This component doesn't render anything visible
return null;
}
-204
View File
@@ -1,204 +0,0 @@
import { useState, useEffect } from 'react';
import { Mail, CheckCircle } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useToast } from '@/hooks/useToast';
import { nip19 } from 'nostr-tools';
export function EmailSubscription() {
const { t } = useTranslation();
const { user } = useCurrentUser();
const { toast } = useToast();
const [email, setEmail] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSubmitted, setIsSubmitted] = useState(false);
const url = new URL('https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&id=f7271442a0&f_id=00ffa3e4f0');
const honeypot = `b_${url.searchParams.get('u')}_${url.searchParams.get('id')}`;
const tag = '8982396';
// Check localStorage on component mount
useEffect(() => {
const hasSubscribed = localStorage.getItem('shakespeare-email-subscribed');
if (hasSubscribed === 'true') {
setIsSubmitted(true);
}
}, []);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!email.trim()) {
toast({
title: "Email required",
description: "Please enter your email address",
variant: "destructive",
});
return;
}
// Basic email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
toast({
title: "Invalid email",
description: "Please enter a valid email address",
variant: "destructive",
});
return;
}
setIsSubmitting(true);
try {
// Submit to Mailchimp
const form = document.createElement('form');
form.method = 'POST';
form.action = url.href;
form.target = '_blank'; // Open in new tab
form.style.display = 'none';
// Add email field
const emailInput = document.createElement('input');
emailInput.type = 'email';
emailInput.name = 'EMAIL';
emailInput.value = email.trim();
form.appendChild(emailInput);
// Add tag field with the new Shakespeare tag ID
const tagInput = document.createElement('input');
tagInput.type = 'hidden';
tagInput.name = 'tags';
tagInput.value = tag;
form.appendChild(tagInput);
// Add npub if available
if (user?.pubkey) {
const npubInput = document.createElement('input');
npubInput.type = 'text';
npubInput.name = 'NPUB';
npubInput.value = nip19.npubEncode(user.pubkey);
npubInput.style.display = 'none';
form.appendChild(npubInput);
}
// Add honeypot field
const honeypotInput = document.createElement('input');
honeypotInput.type = 'text';
honeypotInput.name = honeypot;
honeypotInput.tabIndex = -1;
honeypotInput.style.position = 'absolute';
honeypotInput.style.left = '-5000px';
form.appendChild(honeypotInput);
// Add form to document and submit
document.body.appendChild(form);
form.submit();
// Clean up after a short delay
setTimeout(() => {
document.body.removeChild(form);
}, 1000);
// Save subscription status to localStorage
localStorage.setItem('shakespeare-email-subscribed', 'true');
setIsSubmitted(true);
toast({
title: "Successfully subscribed!",
description: "You'll receive Shakespeare updates and resources occasionally.",
});
} catch (error) {
console.error('Email signup error:', error);
toast({
title: "Subscription failed",
description: "There was an error subscribing you to updates. Please try again.",
variant: "destructive",
});
} finally {
setIsSubmitting(false);
}
};
if (isSubmitted) {
return (
<Card>
<CardContent className="pt-6">
<div className="text-center space-y-4">
<CheckCircle className="h-12 w-12 mx-auto text-green-500" />
<div className="space-y-2">
<h3 className="text-lg font-semibold">
Thanks for subscribing!
</h3>
<p className="text-muted-foreground text-sm">
You can opt out at any time using the unsubscribe link in our emails.
</p>
</div>
<Button
onClick={() => {
localStorage.removeItem('shakespeare-email-subscribed');
setIsSubmitted(false);
setEmail('');
}}
variant="outline"
className="w-full text-xs"
>
Subscribe with different email
</Button>
</div>
</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<Mail className="h-5 w-5 text-primary" />
{t('emailUpdates')}
</CardTitle>
<CardDescription>
{t('emailUpdatesDescription')}
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="email">
Email Address
</Label>
<Input
id="email"
type="email"
placeholder="[email protected]"
value={email}
onChange={(e) => setEmail(e.target.value)}
disabled={isSubmitting}
required
/>
</div>
<div className="space-y-3">
<Button
type="submit"
className="w-full"
disabled={isSubmitting}
>
{isSubmitting ? 'Subscribing...' : 'Subscribe to Updates'}
</Button>
<p className="text-xs text-muted-foreground text-center">
You can opt out at any time using the unsubscribe link in our emails.
</p>
</div>
</form>
</CardContent>
</Card>
);
}
+3 -30
View File
@@ -1,5 +1,5 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { import {
Dialog, Dialog,
@@ -47,7 +47,7 @@ import { cn } from '@/lib/utils';
import { findCredentialsForRepo } from '@/lib/gitCredentials'; import { findCredentialsForRepo } from '@/lib/gitCredentials';
import { nip19 } from 'nostr-tools'; import { nip19 } from 'nostr-tools';
const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev"]; const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev", "gitnostr.com"];
interface GitDialogProps { interface GitDialogProps {
projectId: string; projectId: string;
@@ -62,7 +62,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
const [isPushingToNostr, setIsPushingToNostr] = useState(false); const [isPushingToNostr, setIsPushingToNostr] = useState(false);
const [originUrl, setOriginUrl] = useState(''); const [originUrl, setOriginUrl] = useState('');
const [isSavingOrigin, setIsSavingOrigin] = useState(false); const [isSavingOrigin, setIsSavingOrigin] = useState(false);
const [searchParams, setSearchParams] = useSearchParams();
const navigate = useNavigate(); const navigate = useNavigate();
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId); const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
@@ -335,7 +334,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
title: "Push to Nostr failed", title: "Push to Nostr failed",
description: errorMessage, description: errorMessage,
variant: "destructive", variant: "destructive",
duration: Infinity,
}); });
} finally { } finally {
setIsPushingToNostr(false); setIsPushingToNostr(false);
@@ -397,7 +395,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
title: "Push failed", title: "Push failed",
description: errorMessage, description: errorMessage,
variant: "destructive", variant: "destructive",
duration: Infinity,
}); });
} finally { } finally {
setIsPushing(false); setIsPushing(false);
@@ -428,12 +425,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
try { try {
const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin') const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin')
// Get the current HEAD commit before pulling
const beforeCommit = await git.resolveRef({
dir: projectPath,
ref: 'HEAD',
});
await git.pull({ await git.pull({
dir: projectPath, dir: projectPath,
ref: gitStatus.currentBranch, ref: gitStatus.currentBranch,
@@ -445,38 +436,20 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
onAuth: (url) => findCredentialsForRepo(url, settings.credentials), onAuth: (url) => findCredentialsForRepo(url, settings.credentials),
}); });
// Get the current HEAD commit after pulling
const afterCommit = await git.resolveRef({
dir: projectPath,
ref: 'HEAD',
});
// Check if the repository actually changed
const repoChanged = beforeCommit !== afterCommit;
toast({ toast({
title: "Pull successful", title: "Pull successful",
description: repoChanged description: `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}`,
? `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}`
: `Already up to date with ${remote.name}/${gitStatus.currentBranch}`,
}); });
// Refresh git status after pull // Refresh git status after pull
await refetchGitStatus(); await refetchGitStatus();
// Only trigger build if the repository actually changed
if (repoChanged) {
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.set('build', '');
setSearchParams(newSearchParams);
}
} catch (error) { } catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
toast({ toast({
title: "Pull failed", title: "Pull failed",
description: errorMessage, description: errorMessage,
variant: "destructive", variant: "destructive",
duration: Infinity,
}); });
} finally { } finally {
setIsPulling(false); setIsPulling(false);
+7 -246
View File
@@ -1,7 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react'; import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Decimal } from 'decimal.js';
import { TestApp } from '@/test/TestApp'; import { TestApp } from '@/test/TestApp';
import { ModelSelector } from './ModelSelector'; import { ModelSelector } from './ModelSelector';
@@ -14,10 +12,6 @@ vi.mock('@/hooks/useProviderModels', () => ({
useProviderModels: vi.fn(), useProviderModels: vi.fn(),
})); }));
vi.mock('@/hooks/useIsMobile', () => ({
useIsMobile: vi.fn(),
}));
vi.mock('react-router-dom', async (importOriginal) => { vi.mock('react-router-dom', async (importOriginal) => {
const actual = await importOriginal() as Record<string, unknown>; const actual = await importOriginal() as Record<string, unknown>;
return { return {
@@ -28,11 +22,9 @@ vi.mock('react-router-dom', async (importOriginal) => {
import { useAISettings } from '@/hooks/useAISettings'; import { useAISettings } from '@/hooks/useAISettings';
import { useProviderModels } from '@/hooks/useProviderModels'; import { useProviderModels } from '@/hooks/useProviderModels';
import { useIsMobile } from '@/hooks/useIsMobile';
const mockUseAISettings = vi.mocked(useAISettings); const mockUseAISettings = vi.mocked(useAISettings);
const mockUseProviderModels = vi.mocked(useProviderModels); const mockUseProviderModels = vi.mocked(useProviderModels);
const mockUseIsMobile = vi.mocked(useIsMobile);
describe('ModelSelector', () => { describe('ModelSelector', () => {
const mockOnChange = vi.fn(); const mockOnChange = vi.fn();
@@ -49,7 +41,7 @@ describe('ModelSelector', () => {
removeProvider: vi.fn(), removeProvider: vi.fn(),
setProvider: vi.fn(), setProvider: vi.fn(),
setProviders: vi.fn(), setProviders: vi.fn(),
}); });
mockUseProviderModels.mockReturnValue({ mockUseProviderModels.mockReturnValue({
@@ -58,8 +50,6 @@ describe('ModelSelector', () => {
error: null, error: null,
refetch: vi.fn(), refetch: vi.fn(),
}); });
mockUseIsMobile.mockReturnValue(false);
}); });
it('hides recently used section when less than 5 models and all recently used are available', async () => { it('hides recently used section when less than 5 models and all recently used are available', async () => {
@@ -87,7 +77,7 @@ describe('ModelSelector', () => {
removeProvider: vi.fn(), removeProvider: vi.fn(),
setProvider: vi.fn(), setProvider: vi.fn(),
setProviders: vi.fn(), setProviders: vi.fn(),
}); });
render( render(
@@ -102,17 +92,11 @@ describe('ModelSelector', () => {
// Wait for the dropdown to open // Wait for the dropdown to open
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('provider2')).toBeInTheDocument(); expect(screen.getByText('provider1')).toBeInTheDocument();
}); });
// Recently used section should NOT be visible // Recently used section should NOT be visible
expect(screen.queryByText('Recently Used')).not.toBeInTheDocument(); expect(screen.queryByText('Recently Used')).not.toBeInTheDocument();
// provider1 should be hidden since all its models are in recently used
expect(screen.queryByText('provider1')).not.toBeInTheDocument();
// provider2 should still show with model3
expect(screen.getByText('provider2/model3')).toBeInTheDocument();
}); });
it('shows recently used section when less than 5 models but some recently used are not available', async () => { it('shows recently used section when less than 5 models but some recently used are not available', async () => {
@@ -140,7 +124,7 @@ describe('ModelSelector', () => {
removeProvider: vi.fn(), removeProvider: vi.fn(),
setProvider: vi.fn(), setProvider: vi.fn(),
setProviders: vi.fn(), setProviders: vi.fn(),
}); });
render( render(
@@ -189,7 +173,7 @@ describe('ModelSelector', () => {
removeProvider: vi.fn(), removeProvider: vi.fn(),
setProvider: vi.fn(), setProvider: vi.fn(),
setProviders: vi.fn(), setProviders: vi.fn(),
}); });
render( render(
@@ -204,19 +188,11 @@ describe('ModelSelector', () => {
// Wait for the dropdown to open // Wait for the dropdown to open
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('provider2')).toBeInTheDocument(); expect(screen.getByText('provider1')).toBeInTheDocument();
}); });
// Recently used section SHOULD be visible // Recently used section SHOULD be visible
expect(screen.getByText('Recently Used')).toBeInTheDocument(); expect(screen.getByText('Recently Used')).toBeInTheDocument();
// provider1 should be hidden since all its models are in recently used
expect(screen.queryByText('provider1')).not.toBeInTheDocument();
// provider2 and provider3 should still show
expect(screen.getByText('provider2/model3')).toBeInTheDocument();
expect(screen.getByText('provider2/model4')).toBeInTheDocument();
expect(screen.getByText('provider3/model5')).toBeInTheDocument();
}); });
it('hides recently used section when no recently used models exist', async () => { it('hides recently used section when no recently used models exist', async () => {
@@ -240,7 +216,7 @@ describe('ModelSelector', () => {
removeProvider: vi.fn(), removeProvider: vi.fn(),
setProvider: vi.fn(), setProvider: vi.fn(),
setProviders: vi.fn(), setProviders: vi.fn(),
}); });
render( render(
@@ -261,219 +237,4 @@ describe('ModelSelector', () => {
// Recently used section should NOT be visible // Recently used section should NOT be visible
expect(screen.queryByText('Recently Used')).not.toBeInTheDocument(); expect(screen.queryByText('Recently Used')).not.toBeInTheDocument();
}); });
it('shows caution icon for free models', async () => {
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
const paidModel = {
fullId: 'provider1/paid-model',
provider: 'provider1',
id: 'paid-model',
pricing: {
prompt: new Decimal('0.01'),
completion: new Decimal('0.02'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel, paidModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
// Test with free model selected
const { rerender } = render(
<TestApp>
<ModelSelector value="provider1/free-model" onChange={mockOnChange} />
</TestApp>
);
// Should show caution icon for free model
expect(screen.getByTestId('triangle-alert')).toBeInTheDocument();
// Test with paid model selected
rerender(
<TestApp>
<ModelSelector value="provider1/paid-model" onChange={mockOnChange} />
</TestApp>
);
// Should not show caution icon for paid model
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
});
it('does not show caution icon when no model is selected', () => {
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="" onChange={mockOnChange} />
</TestApp>
);
// Should not show caution icon when no model is selected
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
});
it('does not show caution icon for models without pricing information', () => {
const modelWithoutPricing = {
fullId: 'provider1/unknown-pricing',
provider: 'provider1',
id: 'unknown-pricing',
// No pricing property
};
mockUseProviderModels.mockReturnValue({
models: [modelWithoutPricing],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/unknown-pricing" onChange={mockOnChange} />
</TestApp>
);
// Should not show caution icon for models without pricing info
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
});
it('shows tooltip when hovering over caution icon', async () => {
const user = userEvent.setup();
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/free-model" onChange={mockOnChange} />
</TestApp>
);
const cautionIcon = screen.getByTestId('triangle-alert');
expect(cautionIcon).toBeInTheDocument();
// Hover over the caution icon
await user.hover(cautionIcon);
// Wait for tooltip to appear
await waitFor(() => {
expect(screen.getAllByText('You are using a free model. For better results, switch to a paid model.').length).toBeGreaterThan(0);
});
});
it('makes caution icon tappable on mobile with click-to-toggle tooltip', async () => {
const user = userEvent.setup();
mockUseIsMobile.mockReturnValue(true);
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/free-model" onChange={mockOnChange} />
</TestApp>
);
const cautionButton = screen.getByRole('button', { name: 'Free model warning' });
expect(cautionButton).toBeInTheDocument();
expect(cautionButton).toHaveAttribute('tabIndex', '0'); // Should be tappable on mobile
// Click to open tooltip - just verify the click works without errors
await user.click(cautionButton);
// Tooltip should appear
await waitFor(() => {
expect(screen.getAllByText('You are using a free model. For better results, switch to a paid model.').length).toBeGreaterThan(0);
});
// The button should still be clickable (no errors)
await user.click(cautionButton);
expect(cautionButton).toBeInTheDocument();
});
it('makes caution icon not focusable on desktop', () => {
mockUseIsMobile.mockReturnValue(false);
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/free-model" onChange={mockOnChange} />
</TestApp>
);
const cautionButton = screen.getByRole('button', { name: 'Free model warning' });
expect(cautionButton).toBeInTheDocument();
expect(cautionButton).toHaveAttribute('tabIndex', '-1'); // Should not be focusable on desktop
});
}); });
+156 -257
View File
@@ -1,16 +1,14 @@
import { useState, useMemo, useEffect } from 'react'; import { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings, TriangleAlert } from 'lucide-react'; import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'; import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from '@/components/ui/command'; import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from '@/components/ui/command';
import { Skeleton } from '@/components/ui/skeleton'; import { Skeleton } from '@/components/ui/skeleton';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { useAISettings } from '@/hooks/useAISettings'; import { useAISettings } from '@/hooks/useAISettings';
import { useProviderModels } from '@/hooks/useProviderModels'; import { useProviderModels } from '@/hooks/useProviderModels';
import { useIsMobile } from '@/hooks/useIsMobile';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
interface ModelSelectorProps { interface ModelSelectorProps {
@@ -34,7 +32,6 @@ export function ModelSelector({
}: ModelSelectorProps) { }: ModelSelectorProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const [uncontrolledOpen, setUncontrolledOpen] = useState(false); const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
const [isTooltipOpen, setIsTooltipOpen] = useState(false);
// Use controlled state if provided, otherwise use local state // Use controlled state if provided, otherwise use local state
const open = controlledOpen !== undefined ? controlledOpen : uncontrolledOpen; const open = controlledOpen !== undefined ? controlledOpen : uncontrolledOpen;
@@ -45,31 +42,22 @@ export function ModelSelector({
const { settings, addRecentlyUsedModel, isConfigured } = useAISettings(); const { settings, addRecentlyUsedModel, isConfigured } = useAISettings();
const { models, isLoading, error, refetch } = useProviderModels(); const { models, isLoading, error, refetch } = useProviderModels();
const navigate = useNavigate(); const navigate = useNavigate();
const isMobile = useIsMobile();
const defaultPlaceholder = t('selectOrEnterModel'); const defaultPlaceholder = t('selectOrEnterModel');
const recentlyUsedModels = useMemo(() => settings.recentlyUsedModels || [], [settings.recentlyUsedModels]); const recentlyUsedModels = useMemo(() => settings.recentlyUsedModels || [], [settings.recentlyUsedModels]);
// Create a Set of recently used model IDs for efficient lookup // Group models by provider
const recentlyUsedSet = useMemo(() => new Set(recentlyUsedModels), [recentlyUsedModels]);
// Group models by provider, excluding models that are in the recently used section
const modelsByProvider = useMemo(() => { const modelsByProvider = useMemo(() => {
const groups: Record<string, typeof models> = {}; const groups: Record<string, typeof models> = {};
for (const model of models) { for (const model of models) {
// Skip models that are already shown in recently used
if (recentlyUsedSet.has(model.fullId)) {
continue;
}
if (!groups[model.provider]) { if (!groups[model.provider]) {
groups[model.provider] = []; groups[model.provider] = [];
} }
groups[model.provider].push(model); groups[model.provider].push(model);
} }
return groups; return groups;
}, [models, recentlyUsedSet]); }, [models]);
// Determine if we should show the "Recently Used" section // Determine if we should show the "Recently Used" section
const shouldShowRecentlyUsed = useMemo(() => { const shouldShowRecentlyUsed = useMemo(() => {
@@ -94,43 +82,9 @@ export function ModelSelector({
return !allRecentlyUsedAreAvailable; return !allRecentlyUsedAreAvailable;
}, [recentlyUsedModels, models]); }, [recentlyUsedModels, models]);
// Check if the current model is free
const isCurrentModelFree = useMemo(() => {
if (!value) return false;
const currentModel = models.find(model => model.fullId === value);
if (!currentModel?.pricing) return false;
return currentModel.pricing.prompt.equals(0) && currentModel.pricing.completion.equals(0);
}, [value, models]);
// Don't auto-initialize with recently used models // Don't auto-initialize with recently used models
// Let the parent component handle initialization // Let the parent component handle initialization
// Close tooltip when clicking outside on mobile
useEffect(() => {
if (!isMobile || !isTooltipOpen) return;
const handleClickOutside = (event: MouseEvent | TouchEvent) => {
const target = event.target as Element;
// Check if the click is outside the tooltip and trigger
if (!target.closest('[data-radix-tooltip-content]') &&
!target.closest('[data-radix-tooltip-trigger]') &&
!target.closest('[data-testid="triangle-alert"]')) {
setIsTooltipOpen(false);
}
};
// Add both click and touch event listeners
document.addEventListener('click', handleClickOutside, true);
document.addEventListener('touchstart', handleClickOutside, true);
return () => {
document.removeEventListener('click', handleClickOutside, true);
document.removeEventListener('touchstart', handleClickOutside, true);
};
}, [isMobile, isTooltipOpen]);
const handleSelect = (selectedValue: string) => { const handleSelect = (selectedValue: string) => {
if (selectedValue === '__custom__') { if (selectedValue === '__custom__') {
setIsCustomInput(true); setIsCustomInput(true);
@@ -171,222 +125,167 @@ export function ModelSelector({
if (isCustomInput) { if (isCustomInput) {
return ( return (
<TooltipProvider> <div className={cn("flex items-center gap-1", className)}>
<div className={cn("flex items-center gap-1", className)}> <Input
<Input value={customValue}
value={customValue} onChange={(e) => setCustomValue(e.target.value)}
onChange={(e) => setCustomValue(e.target.value)} onKeyDown={handleCustomKeyDown}
onKeyDown={handleCustomKeyDown} onBlur={handleCustomSubmit}
onBlur={handleCustomSubmit} placeholder="provider/model (e.g., openrouter/anthropic/claude-sonnet-4)"
placeholder="provider/model (e.g., openrouter/anthropic/claude-sonnet-4)" className="h-8 text-xs"
className="h-8 text-xs" autoFocus
autoFocus />
/> <Button
<Button size="sm"
size="sm" variant="ghost"
variant="ghost" className="h-8 w-8 p-0"
className="h-8 w-8 p-0" onClick={handleCustomSubmit}
onClick={handleCustomSubmit} >
> <Check className="h-3 w-3" />
<Check className="h-3 w-3" /> </Button>
</Button> </div>
</div>
</TooltipProvider>
); );
} }
return ( return (
<TooltipProvider> <Popover open={open} onOpenChange={setOpen}>
<div className={cn("flex justify-end gap-0.5", className)}> <PopoverTrigger asChild>
{isCurrentModelFree && ( <Button
<Tooltip variant="ghost"
open={isMobile ? isTooltipOpen : undefined} role="combobox"
onOpenChange={isMobile ? setIsTooltipOpen : undefined} aria-expanded={open}
delayDuration={isMobile ? 0 : 700} className={cn(
disableHoverableContent={isMobile} "h-8 p-0 gap-0.5 justify-between text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right",
> className
<TooltipTrigger asChild> )}
<button disabled={disabled}
type="button" >
className="inline-flex items-center p-0 rounded-none border-0 bg-transparent hover:bg-transparent focus:bg-transparent active:bg-transparent focus:outline-none focus-visible:outline-none focus:ring-0 focus-visible:ring-0 focus:border-0 active:outline-none" <span className="w-full truncate">
aria-label="Free model warning" {value || placeholder || defaultPlaceholder}
tabIndex={isMobile ? 0 : -1} </span>
onClick={isMobile ? (e) => { <ChevronDown className="size-3 shrink-0 opacity-50" />
e.preventDefault(); </Button>
e.stopPropagation(); </PopoverTrigger>
setIsTooltipOpen(!isTooltipOpen); <PopoverContent className="w-96 p-0" align="end">
} : undefined} <Command>
onTouchStart={isMobile ? (e) => { {isConfigured && <CommandInput placeholder={t('searchModels')} className="h-9" />}
e.preventDefault(); <CommandList className="max-h-[300px]">
e.stopPropagation(); <CommandEmpty>
} : undefined} <div className="py-6 text-center text-sm text-muted-foreground">
onTouchEnd={isMobile ? (e) => { <p>{t('noModelsFound')}</p>
e.preventDefault(); <p className="mt-2 text-xs">{t('tryCustomModel')}</p>
e.stopPropagation(); </div>
setIsTooltipOpen(!isTooltipOpen); </CommandEmpty>
} : undefined}
style={{
WebkitTapHighlightColor: 'transparent',
outline: 'none',
border: 'none',
boxShadow: 'none'
}}
>
<TriangleAlert className="h-3 w-3 text-amber-500 flex-shrink-0" data-testid="triangle-alert" />
</button>
</TooltipTrigger>
<TooltipContent
side="top"
sideOffset={4}
className="max-w-xs text-center"
avoidCollisions={true}
collisionPadding={8}
>
<p>You are using a free model. For better results, switch to a paid model.</p>
</TooltipContent>
</Tooltip>
)}
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
role="combobox"
aria-expanded={open}
className={cn(
"h-8 p-0 gap-0.5 text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right min-w-0"
)}
disabled={disabled}
>
<span className="truncate">
{value || placeholder || defaultPlaceholder}
</span>
<ChevronDown className="size-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="p-0" align="end">
<Command>
{(isConfigured && models.length >= 5) && (
<CommandInput placeholder={t('searchModels')} className="h-9" />
)}
<CommandList className="max-h-[300px]">
<CommandEmpty>
<div className="py-6 text-center text-sm text-muted-foreground">
<p>{t('noModelsFound')}</p>
<p className="mt-2 text-xs">{t('tryCustomModel')}</p>
</div>
</CommandEmpty>
{shouldShowRecentlyUsed && ( {shouldShowRecentlyUsed && (
<CommandGroup heading={t('recentlyUsed')}> <CommandGroup heading={t('recentlyUsed')}>
{recentlyUsedModels.map((model) => ( {recentlyUsedModels.map((model) => (
<CommandItem
key={model}
value={model}
onSelect={() => handleSelect(model)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate">{model}</span>
</CommandItem>
))}
</CommandGroup>
)}
{shouldShowRecentlyUsed && <CommandSeparator />}
{/* Loading state */}
{isLoading && (
<CommandGroup heading={t('loading')}>
<div className="px-2 py-1.5">
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4 w-1/2" />
</div>
</div>
</CommandGroup>
)}
{/* Error state */}
{error && !isLoading && (
<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" />
<div className="space-y-2">
<p className="text-destructive">{error}</p>
<Button
variant="outline"
size="sm"
onClick={refetch}
className="h-7 text-xs"
>
<RefreshCw className="h-3 w-3 mr-1" />
{t('retry')}
</Button>
</div>
</div>
</div>
</CommandGroup>
)}
{/* Provider models */}
{!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => (
<div key={provider}>
<CommandSeparator />
<CommandGroup heading={provider}>
{providerModels.map((model) => (
<CommandItem
key={model.fullId}
value={model.fullId}
onSelect={() => handleSelect(model.fullId)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model.fullId ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate">{model.fullId}</span>
</CommandItem>
))}
</CommandGroup>
</div>
))}
{/* Custom model option and manage providers - moved to bottom */}
<CommandSeparator />
<CommandGroup>
{isConfigured && (
<CommandItem
value="__custom_model_option__"
onSelect={() => handleSelect('__custom__')}
className="cursor-pointer"
>
<Edit3 className="mr-2 h-4 w-4" />
{t('enterCustomModel')}
</CommandItem>
)}
<CommandItem <CommandItem
value="__manage_providers_option__" key={model}
onSelect={() => handleSelect('__manage_providers__')} value={model}
onSelect={() => handleSelect(model)}
className="cursor-pointer" className="cursor-pointer"
> >
<Settings className="mr-2 h-4 w-4" /> <Check
{t('manageProviders')} className={cn(
"mr-2 h-4 w-4",
value === model ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate">{model}</span>
</CommandItem> </CommandItem>
))}
</CommandGroup>
)}
{shouldShowRecentlyUsed && <CommandSeparator />}
{/* Loading state */}
{isLoading && (
<CommandGroup heading={t('loading')}>
<div className="px-2 py-1.5">
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4 w-1/2" />
</div>
</div>
</CommandGroup>
)}
{/* Error state */}
{error && !isLoading && (
<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" />
<div className="space-y-2">
<p className="text-destructive">{error}</p>
<Button
variant="outline"
size="sm"
onClick={refetch}
className="h-7 text-xs"
>
<RefreshCw className="h-3 w-3 mr-1" />
{t('retry')}
</Button>
</div>
</div>
</div>
</CommandGroup>
)}
{/* Provider models */}
{!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => (
<div key={provider}>
<CommandSeparator />
<CommandGroup heading={provider}>
{providerModels.map((model) => (
<CommandItem
key={model.fullId}
value={model.fullId}
onSelect={() => handleSelect(model.fullId)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model.fullId ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate">{model.fullId}</span>
</CommandItem>
))}
</CommandGroup> </CommandGroup>
</CommandList> </div>
</Command> ))}
</PopoverContent>
</Popover> {/* Custom model option and manage providers - moved to bottom */}
</div> <CommandSeparator />
</TooltipProvider> <CommandGroup>
{isConfigured && (
<CommandItem
value="__custom_model_option__"
onSelect={() => handleSelect('__custom__')}
className="cursor-pointer"
>
<Edit3 className="mr-2 h-4 w-4" />
{t('enterCustomModel')}
</CommandItem>
)}
<CommandItem
value="__manage_providers_option__"
onSelect={() => handleSelect('__manage_providers__')}
className="cursor-pointer"
>
<Settings className="mr-2 h-4 w-4" />
{t('manageProviders')}
</CommandItem>
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
); );
} }
+1
View File
@@ -18,6 +18,7 @@ const GIT_KINDS = [
const GIT_RELAYS = [ const GIT_RELAYS = [
'wss://git.shakespeare.diy/', 'wss://git.shakespeare.diy/',
'wss://relay.ngit.dev/', 'wss://relay.ngit.dev/',
'wss://gitnostr.com/',
]; ];
const NostrProvider: React.FC<NostrProviderProps> = (props) => { const NostrProvider: React.FC<NostrProviderProps> = (props) => {
@@ -1,103 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { OnboardingCreditsBadge } from './OnboardingCreditsBadge';
import type { UseQueryResult } from '@tanstack/react-query';
import type { CreditsResponse } from '@/hooks/useAICredits';
// Mock the useAICredits hook
vi.mock('@/hooks/useAICredits', () => ({
useAICredits: vi.fn(),
}));
import { useAICredits } from '@/hooks/useAICredits';
const mockUseAICredits = vi.mocked(useAICredits);
describe('OnboardingCreditsBadge', () => {
const mockProvider = {
id: 'shakespeare',
baseURL: 'https://ai.shakespeare.diy/v1',
nostr: true,
};
it('renders credits badge when data is available', () => {
mockUseAICredits.mockReturnValue({
data: { object: 'credits', amount: 25.50 },
isLoading: false,
error: null,
} as UseQueryResult<CreditsResponse, Error>);
render(
<TestApp>
<OnboardingCreditsBadge provider={mockProvider} />
</TestApp>
);
expect(screen.getByText('$25.50')).toBeInTheDocument();
});
it('does not render when loading', () => {
mockUseAICredits.mockReturnValue({
data: undefined,
isLoading: true,
error: null,
} as UseQueryResult<CreditsResponse, Error>);
const { container } = render(
<TestApp>
<OnboardingCreditsBadge provider={mockProvider} />
</TestApp>
);
expect(container.firstChild).toBeNull();
});
it('does not render when there is an error', () => {
mockUseAICredits.mockReturnValue({
data: undefined,
isLoading: false,
error: new Error('Provider does not support credits'),
} as UseQueryResult<CreditsResponse, Error>);
const { container } = render(
<TestApp>
<OnboardingCreditsBadge provider={mockProvider} />
</TestApp>
);
expect(container.firstChild).toBeNull();
});
it('does not render when no credits data is available', () => {
mockUseAICredits.mockReturnValue({
data: undefined,
isLoading: false,
error: null,
} as UseQueryResult<CreditsResponse, Error>);
const { container } = render(
<TestApp>
<OnboardingCreditsBadge provider={mockProvider} />
</TestApp>
);
expect(container.firstChild).toBeNull();
});
it('does not render when credits amount is 0', () => {
mockUseAICredits.mockReturnValue({
data: { object: 'credits', amount: 0 },
isLoading: false,
error: null,
} as UseQueryResult<CreditsResponse, Error>);
const { container } = render(
<TestApp>
<OnboardingCreditsBadge provider={mockProvider} />
</TestApp>
);
expect(container.firstChild).toBeNull();
});
});
-42
View File
@@ -1,42 +0,0 @@
import { Badge } from '@/components/ui/badge';
import { AIProvider } from '@/contexts/AISettingsContext';
import { useAICredits } from '@/hooks/useAICredits';
interface OnboardingCreditsBadgeProps {
provider: AIProvider;
className?: string;
}
/**
* Displays a non-clickable credits badge for onboarding showing the remaining credits for an AI provider
*/
export function OnboardingCreditsBadge({ provider, className }: OnboardingCreditsBadgeProps) {
const { data: credits, isLoading, error } = useAICredits(provider);
// 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 or if amount is 0
if (!credits || credits.amount === 0) {
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={`text-xs ${className}`}
>
{formattedAmount}
</Badge>
);
}
+1 -1
View File
@@ -42,7 +42,7 @@ describe('OnboardingDialog', () => {
</TestApp> </TestApp>
); );
expect(screen.getByText('Welcome to Shakespeare!')).toBeInTheDocument(); // Only in dialog title now expect(screen.getAllByText('Welcome to Shakespeare!')).toHaveLength(2); // Title and heading
expect(screen.getByText(/Your AI-powered development assistant/)).toBeInTheDocument(); expect(screen.getByText(/Your AI-powered development assistant/)).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Get Started/i })).toBeInTheDocument(); expect(screen.getByRole('button', { name: /Get Started/i })).toBeInTheDocument();
}); });
+62 -355
View File
@@ -1,100 +1,59 @@
import { Decimal } from 'decimal.js'; import { Decimal } from 'decimal.js';
import { useState, useEffect, useRef } from 'react'; import { useState, useEffect } from 'react';
import { generateSecretKey } from 'nostr-tools'; import { generateSecretKey } from 'nostr-tools';
import { nip19 } from 'nostr-tools'; import { nip19 } from 'nostr-tools';
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, ExternalLink } from 'lucide-react'; import { Bot, Check, Sparkles, ArrowRight, ArrowLeft } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton'; import { Skeleton } from '@/components/ui/skeleton';
import { Checkbox } from '@/components/ui/checkbox'; import { ScrollArea } from '@/components/ui/scroll-area';
import { PasswordInput } from '@/components/ui/password-input';
import { useAISettings } from '@/hooks/useAISettings'; import { useAISettings } from '@/hooks/useAISettings';
import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useLoginActions } from '@/hooks/useLoginActions'; import { useLoginActions } from '@/hooks/useLoginActions';
import { useProviderModels } from '@/hooks/useProviderModels'; import { useProviderModels } from '@/hooks/useProviderModels';
import { CreditsDialog } from '@/components/CreditsDialog'; import { CreditsDialog } from '@/components/CreditsDialog';
import { OnboardingCreditsBadge } from '@/components/OnboardingCreditsBadge';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
import { cn } from '@/lib/utils';
interface OnboardingDialogProps { interface OnboardingDialogProps {
open: boolean; open: boolean;
onOpenChange: (open: boolean) => void; onOpenChange: (open: boolean) => void;
} }
type OnboardingStep = 'welcome' | 'open-source' | 'provider-selection' | 'model-selection' | 'conclusion'; type OnboardingStep = 'welcome' | 'model-selection' | 'conclusion';
const SHAKESPEARE_PROVIDER = {
id: "shakespeare",
baseURL: "https://ai.shakespeare.diy/v1",
nostr: true,
};
export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) { export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) {
const [step, setStep] = useState<OnboardingStep>('welcome'); const [step, setStep] = useState<OnboardingStep>('welcome');
const [selectedProvider, setSelectedProvider] = useState<PresetProvider | null>(null);
const [providerApiKey, setProviderApiKey] = useState<string>('');
const [selectedModel, setSelectedModel] = useState<string>(''); const [selectedModel, setSelectedModel] = useState<string>('');
const [isSettingUp, setIsSettingUp] = useState(false); const [isSettingUp, setIsSettingUp] = useState(false);
const [showCreditsDialog, setShowCreditsDialog] = useState(false); const [showCreditsDialog, setShowCreditsDialog] = useState(false);
const [agreedToTerms, setAgreedToTerms] = useState(false);
const [agreedToProviderTerms, setAgreedToProviderTerms] = useState(false);
// Ref for the scrollable content area
const scrollableContentRef = useRef<HTMLDivElement>(null);
const { setProvider, addRecentlyUsedModel } = useAISettings(); const { setProvider, addRecentlyUsedModel } = useAISettings();
const { user } = useCurrentUser(); const { user } = useCurrentUser();
const login = useLoginActions(); const login = useLoginActions();
const { models, isLoading: isLoadingModels } = useProviderModels(); const { models, isLoading: isLoadingModels } = useProviderModels();
// Filter models to only show selected provider models // Filter models to only show Shakespeare provider models
const providerModels = selectedProvider const shakespeareModels = models.filter(model => model.provider === 'shakespeare');
? models.filter(model => model.provider === selectedProvider.id)
: [];
const handleGetStarted = () => {
setStep('open-source');
};
const handleContinueFromOpenSource = () => {
if (!agreedToTerms) return;
setStep('provider-selection');
};
const handleProviderSelect = (provider: PresetProvider) => {
setSelectedProvider(provider);
// Clear API key when switching providers
setProviderApiKey('');
// Reset provider terms agreement when switching providers
setAgreedToProviderTerms(false);
};
const handleContinueFromProviderSelection = async () => {
if (!selectedProvider) return;
// Check if user agreed to provider terms
if (!agreedToProviderTerms) return;
// Check if provider requires API key and if it's provided
const requiresApiKey = selectedProvider.apiKeysURL && !selectedProvider.nostr;
if (requiresApiKey && !providerApiKey.trim()) return;
const handleGetStarted = async () => {
setIsSettingUp(true); setIsSettingUp(true);
try { try {
// If user is not logged in and provider uses Nostr auth, generate and login with secret key // If user is not logged in, generate and login with secret key
if (!user && selectedProvider.nostr) { if (!user) {
const secretKey = generateSecretKey(); const secretKey = generateSecretKey();
const nsec = nip19.nsecEncode(secretKey); const nsec = nip19.nsecEncode(secretKey);
login.nsec(nsec); login.nsec(nsec);
} }
// Add selected provider to their config // Add Shakespeare provider to their config
const providerConfig = { setProvider(SHAKESPEARE_PROVIDER);
id: selectedProvider.id,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
apiKey: requiresApiKey ? providerApiKey.trim() : undefined,
};
setProvider(providerConfig);
// Move to model selection // Move to model selection
setStep('model-selection'); setStep('model-selection');
@@ -116,7 +75,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
addRecentlyUsedModel(selectedModel); addRecentlyUsedModel(selectedModel);
// Find the selected model to check if it's free // Find the selected model to check if it's free
const model = providerModels.find(m => m.fullId === selectedModel); const model = shakespeareModels.find(m => m.fullId === selectedModel);
const isFreeModel = !model?.pricing || ( const isFreeModel = !model?.pricing || (
model.pricing.prompt.equals(0) && model.pricing.completion.equals(0) model.pricing.prompt.equals(0) && model.pricing.completion.equals(0)
); );
@@ -151,30 +110,19 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
useEffect(() => { useEffect(() => {
if (open) { if (open) {
setStep('welcome'); setStep('welcome');
setSelectedProvider(null);
setProviderApiKey('');
setSelectedModel(''); setSelectedModel('');
setIsSettingUp(false); setIsSettingUp(false);
setShowCreditsDialog(false); setShowCreditsDialog(false);
setAgreedToTerms(false);
setAgreedToProviderTerms(false);
} }
}, [open]); }, [open]);
// Scroll to top when step changes
useEffect(() => {
if (scrollableContentRef.current) {
scrollableContentRef.current.scrollTop = 0;
}
}, [step]);
return ( return (
<> <>
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl h-dvh-safe sm:h-auto sm:max-h-[90vh] flex flex-col"> <DialogContent className="max-w-2xl max-h-[80vh] overflow-hidden">
<DialogHeader className="flex-shrink-0"> <DialogHeader>
<DialogTitle className="flex items-center gap-2"> <DialogTitle className="flex items-center gap-2">
{step === 'open-source' && ( {step === 'model-selection' && (
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
@@ -184,48 +132,18 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
<ArrowLeft className="h-4 w-4" /> <ArrowLeft className="h-4 w-4" />
</Button> </Button>
)} )}
{step === 'provider-selection' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('open-source')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{step === 'model-selection' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('provider-selection')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{step === 'conclusion' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('model-selection')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
<span className="text-xl"> <span className="text-xl">
{step === 'welcome' && 'Welcome to Shakespeare!'}
{step === 'model-selection' && 'Choose Your AI Model'} {step === 'model-selection' && 'Choose Your AI Model'}
{step === 'conclusion' && "You're All Set!"}
</span> </span>
</DialogTitle> </DialogTitle>
</DialogHeader> </DialogHeader>
<div ref={scrollableContentRef} className="flex-1 overflow-y-auto min-h-0"> <div className="flex-1 overflow-hidden">
{step === 'welcome' && ( {step === 'welcome' && (
<div className="text-center space-y-6 py-4"> <div className="text-center space-y-6 py-4">
<div className="mb-4"> <div className="text-6xl mb-4">🎭</div>
<ShakespeareLogo className="w-16 h-16 mx-auto" />
</div>
<div className="space-y-3"> <div className="space-y-3">
<h2 className="text-2xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent"> <h2 className="text-2xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Welcome to Shakespeare! Welcome to Shakespeare!
@@ -272,215 +190,16 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
</div> </div>
)} )}
{step === 'open-source' && (
<div className="space-y-6 py-4">
<div className="text-center space-y-4">
<h2 className="text-2xl font-bold">
Shakespeare is Open Source software that runs entirely in your web&nbsp;browser
</h2>
</div>
<div className="grid gap-1 max-w-md mx-auto">
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
<p className="text-sm">Your device connects directly to third-party AI providers of your choice</p>
</div>
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
<p className="text-sm">Your files are stored on your device in your browser</p>
</div>
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
<p className="text-sm">Be careful not to delete your browser data or you may lose project files</p>
</div>
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
<p className="text-sm">You are responsible for taking backups or syncing to git</p>
</div>
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
<p className="text-sm">Quality of output depends on quality of input and models used, and is not guaranteed</p>
</div>
</div>
<div className="space-y-3 max-w-md mx-auto">
<p className="text-xs text-muted-foreground max-w-xl mx-auto">
Shakespeare is not a cloud service. It's Open Source software that runs on your device.
You agree to the Terms of Service of AI providers you interact with.
Shakespeare is provided "as is" without warranty of any kind.
</p>
<div className="flex items-center justify-center gap-2">
<Checkbox
id="agree-terms"
checked={agreedToTerms}
onCheckedChange={(checked) => setAgreedToTerms(checked === true)}
/>
<label
htmlFor="agree-terms"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
>
I agree
</label>
</div>
</div>
<div className="flex justify-center">
<Button
onClick={handleContinueFromOpenSource}
disabled={!agreedToTerms}
className="gap-2 rounded-full w-full max-w-md"
>
Continue
<ArrowRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
{step === 'provider-selection' && (
<div className="space-y-6 py-4">
<div className="text-center space-y-4">
<h2 className="text-2xl font-bold">Choose your AI provider</h2>
<p className="text-muted-foreground max-w-md mx-auto">
Select an AI provider to power your development assistant. You can add more providers later in settings.
</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 p-1 gap-3 max-w-4xl mx-auto">
{AI_PROVIDER_PRESETS.map((provider) => {
const isSelected = selectedProvider?.id === provider.id;
const isShakespeare = provider.id === 'shakespeare';
return (
<Card
key={provider.id}
className={cn('cursor-pointer transition-all hover:shadow-md', {
'ring-2 ring-primary': isSelected,
})}
onClick={() => handleProviderSelect(provider)}
>
<div className="flex items-center justify-between p-3">
<div className="flex-1">
<CardTitle className={cn('text-lg font-semibold', {
'bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent': isShakespeare,
})}>
{provider.name}
</CardTitle>
</div>
<div className="flex items-center gap-2">
<OnboardingCreditsBadge provider={provider} />
{isSelected && (
<div className="h-5 w-5 rounded-full bg-primary flex items-center justify-center">
<Check className="h-3 w-3 text-primary-foreground" />
</div>
)}
</div>
</div>
</Card>
);
})}
</div>
{/* API Key Input Section */}
{selectedProvider && selectedProvider.apiKeysURL && !selectedProvider.nostr && (
<div className="space-y-3 max-w-md mx-auto">
<div className="text-center">
<h3 className="text-lg font-semibold">
{selectedProvider.id === 'routstr' ? 'Enter Cashu Token' : 'Enter API Key'}
</h3>
<p className="text-sm text-muted-foreground">
{selectedProvider.id === 'routstr' ? (
<>{selectedProvider.name} requires a Cashu token</>
) : (
<>
{selectedProvider.name} requires an {selectedProvider.apiKeysURL ? (
<a className="text-foreground underline" href={selectedProvider.apiKeysURL} target="_blank">
API key
<ExternalLink className="inline-block h-4 w-4 ml-1" />
</a>
) : (
<>API key</>
)}
</>
)}
</p>
</div>
<PasswordInput
placeholder={selectedProvider.id === 'routstr' ? 'Enter a Cashu Token' : 'Enter your API key'}
value={providerApiKey}
onChange={(e) => setProviderApiKey(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && providerApiKey.trim()) {
handleContinueFromProviderSelection();
}
}}
/>
</div>
)}
{/* Terms of Service Agreement */}
{selectedProvider && (
<div className="space-y-3 max-w-md mx-auto">
<div className="flex items-center justify-center gap-2">
<Checkbox
id="agree-provider-terms"
checked={agreedToProviderTerms}
onCheckedChange={(checked) => setAgreedToProviderTerms(checked === true)}
/>
<label
htmlFor="agree-provider-terms"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
>
I agree to {selectedProvider.name}'s{' '}
{selectedProvider.tosURL ? (
<a
href={selectedProvider.tosURL}
target="_blank"
rel="noopener noreferrer"
className="text-primary underline hover:no-underline"
onClick={(e) => e.stopPropagation()}
>
Terms of Service
</a>
) : (
'Terms of Service'
)}
</label>
</div>
</div>
)}
<div className="flex justify-center">
<Button
onClick={handleContinueFromProviderSelection}
disabled={
!selectedProvider ||
isSettingUp ||
!agreedToProviderTerms ||
!!(selectedProvider?.apiKeysURL && !selectedProvider?.nostr && !providerApiKey.trim())
}
className="gap-2 rounded-full w-full max-w-md"
>
{isSettingUp ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white" />
Setting up...
</>
) : (
<>
Continue
<ArrowRight className="h-4 w-4" />
</>
)}
</Button>
</div>
</div>
)}
{step === 'model-selection' && ( {step === 'model-selection' && (
<div className="flex flex-col h-full"> <div className="space-y-4">
<div className="flex-1 overflow-y-auto min-h-0 my-4"> <div className="text-center space-y-2">
<p className="text-muted-foreground">
Choose an AI model to power your development experience.
Different models offer various capabilities and pricing.
</p>
</div>
<ScrollArea className="h-96">
<div className="space-y-3 p-1"> <div className="space-y-3 p-1">
{isLoadingModels ? ( {isLoadingModels ? (
<> <>
@@ -500,7 +219,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
</Card> </Card>
))} ))}
</> </>
) : providerModels.length === 0 ? ( ) : shakespeareModels.length === 0 ? (
<Card className="p-6 text-center"> <Card className="p-6 text-center">
<div className="space-y-2"> <div className="space-y-2">
<Bot className="h-8 w-8 mx-auto text-muted-foreground" /> <Bot className="h-8 w-8 mx-auto text-muted-foreground" />
@@ -510,11 +229,9 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
</div> </div>
</Card> </Card>
) : ( ) : (
providerModels.map((model) => { shakespeareModels.map((model) => {
const isSelected = selectedModel === model.fullId; const isSelected = selectedModel === model.fullId;
const isFree = model.pricing?.prompt.equals(0) && model.pricing?.completion.equals(0); const isFree = model.pricing?.prompt.equals(0) && model.pricing?.completion.equals(0);
const isPremium = !!model.pricing && !isFree;
const modelName = model.name || model.id;
return ( return (
<Card <Card
@@ -524,19 +241,15 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
}`} }`}
onClick={() => handleModelSelect(model.fullId)} onClick={() => handleModelSelect(model.fullId)}
> >
<CardHeader> <CardHeader className="pb-3">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex-1"> <div className="flex-1">
<CardTitle className={cn('text-xl font-semibold', { <CardTitle className="text-base font-semibold">
'bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent': isPremium, {model.description || model.name || model.id}
})}>
{modelName}
</CardTitle> </CardTitle>
{model.description && ( {model.description && (
<p className="text-sm text-muted-foreground mt-1"> <p className="text-sm text-muted-foreground mt-1">
{model.description.length > 70 {model.name || model.id}
? model.description.slice(0, 70) + '...'
: model.description}
</p> </p>
)} )}
</div> </div>
@@ -546,11 +259,6 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
Free Free
</Badge> </Badge>
)} )}
{isPremium && (
<Badge className="text-xs bg-primary text-white border-0">
Premium
</Badge>
)}
{isSelected && ( {isSelected && (
<div className="h-5 w-5 rounded-full bg-primary flex items-center justify-center"> <div className="h-5 w-5 rounded-full bg-primary flex items-center justify-center">
<Check className="h-3 w-3 text-primary-foreground" /> <Check className="h-3 w-3 text-primary-foreground" />
@@ -559,29 +267,27 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
</div> </div>
</div> </div>
</CardHeader> </CardHeader>
{(model.pricing || model.contextLength) && ( <CardContent className="pt-0">
<CardContent className="pt-0"> <div className="flex items-center gap-4 text-xs text-muted-foreground">
<div className="flex items-end justify-end gap-4 text-xs text-muted-foreground"> {model.pricing && (
{model.pricing && ( <>
<div className="text-right"> <span>Input: {formatPrice(model.pricing.prompt)}</span>
<div>Input: {formatPrice(model.pricing.prompt)}</div> <span>Output: {formatPrice(model.pricing.completion)}</span>
<div>Output: {formatPrice(model.pricing.completion)}</div> </>
</div> )}
)} {model.contextLength && (
{model.contextLength && ( <span>Context: {model.contextLength.toLocaleString()} tokens</span>
<span>Context: {model.contextLength.toLocaleString()} tokens</span> )}
)} </div>
</div> </CardContent>
</CardContent>
)}
</Card> </Card>
); );
}) })
)} )}
</div> </div>
</div> </ScrollArea>
<div className="flex justify-end gap-2 pt-4 flex-shrink-0"> <div className="flex justify-end gap-2 pt-4 border-t">
<Button <Button
onClick={handleContinue} onClick={handleContinue}
disabled={!selectedModel} disabled={!selectedModel}
@@ -604,6 +310,11 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
Just enter your prompt to start building amazing Nostr applications. Just enter your prompt to start building amazing Nostr applications.
</p> </p>
</div> </div>
<div className="bg-muted/50 rounded-lg p-4 max-w-md mx-auto">
<p className="text-sm text-muted-foreground italic">
"Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies..."
</p>
</div>
<Button onClick={handleFinish} size="lg" className="gap-2"> <Button onClick={handleFinish} size="lg" className="gap-2">
<Sparkles className="h-4 w-4" /> <Sparkles className="h-4 w-4" />
Start Building Start Building
@@ -615,7 +326,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
</Dialog> </Dialog>
{/* Credits Dialog */} {/* Credits Dialog */}
{showCreditsDialog && selectedModel && selectedProvider && ( {showCreditsDialog && selectedModel && (
<CreditsDialog <CreditsDialog
open={showCreditsDialog} open={showCreditsDialog}
onOpenChange={(open) => { onOpenChange={(open) => {
@@ -623,11 +334,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
handleCreditsDialogClose(); handleCreditsDialogClose();
} }
}} }}
provider={{ provider={SHAKESPEARE_PROVIDER}
id: selectedProvider.id,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
}}
/> />
)} )}
</> </>
+1 -1
View File
@@ -208,7 +208,7 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
return ( return (
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md" onOpenAutoFocus={(e) => e.preventDefault()}> <DialogContent className="max-w-md">
<DialogHeader> <DialogHeader>
<DialogTitle className="flex items-center gap-2"> <DialogTitle className="flex items-center gap-2">
<Folder className="h-5 w-5" /> <Folder className="h-5 w-5" />
+13 -13
View File
@@ -54,13 +54,13 @@ describe('ProjectSidebar', () => {
render( render(
<TestApp> <TestApp>
<ProjectSidebar <ProjectSidebar
selectedItem={null} selectedProject={null}
onSelectItem={vi.fn()} onSelectProject={vi.fn()}
/> />
</TestApp> </TestApp>
); );
expect(screen.getByAltText('Shakespeare')).toBeInTheDocument(); expect(screen.getByText('🎭')).toBeInTheDocument();
expect(screen.getByText('Shakespeare')).toBeInTheDocument(); expect(screen.getByText('Shakespeare')).toBeInTheDocument();
}); });
@@ -70,8 +70,8 @@ describe('ProjectSidebar', () => {
render( render(
<TestApp> <TestApp>
<ProjectSidebar <ProjectSidebar
selectedItem={null} selectedProject={null}
onSelectItem={vi.fn()} onSelectProject={vi.fn()}
onToggleSidebar={mockToggle} onToggleSidebar={mockToggle}
/> />
</TestApp> </TestApp>
@@ -88,8 +88,8 @@ describe('ProjectSidebar', () => {
render( render(
<TestApp> <TestApp>
<ProjectSidebar <ProjectSidebar
selectedItem={null} selectedProject={null}
onSelectItem={vi.fn()} onSelectProject={vi.fn()}
/> />
</TestApp> </TestApp>
); );
@@ -101,8 +101,8 @@ describe('ProjectSidebar', () => {
render( render(
<TestApp> <TestApp>
<ProjectSidebar <ProjectSidebar
selectedItem={null} selectedProject={null}
onSelectItem={vi.fn()} onSelectProject={vi.fn()}
/> />
</TestApp> </TestApp>
); );
@@ -115,8 +115,8 @@ describe('ProjectSidebar', () => {
render( render(
<TestApp> <TestApp>
<ProjectSidebar <ProjectSidebar
selectedItem={null} selectedProject={null}
onSelectItem={vi.fn()} onSelectProject={vi.fn()}
/> />
</TestApp> </TestApp>
); );
@@ -128,8 +128,8 @@ describe('ProjectSidebar', () => {
render( render(
<TestApp> <TestApp>
<ProjectSidebar <ProjectSidebar
selectedItem={null} selectedProject={null}
onSelectItem={vi.fn()} onSelectProject={vi.fn()}
/> />
</TestApp> </TestApp>
); );
+94 -79
View File
@@ -1,7 +1,7 @@
import React, { useEffect } from 'react'; import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, MessageSquare } from 'lucide-react'; import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, FileArchive } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton'; import { Skeleton } from '@/components/ui/skeleton';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
@@ -9,29 +9,27 @@ import { useProjects } from '@/hooks/useProjects';
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus'; import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
import { useLocalStorage } from '@/hooks/useLocalStorage'; import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useIsMobile } from '@/hooks/useIsMobile'; import { useIsMobile } from '@/hooks/useIsMobile';
import type { ChatItem } from '@/lib/ProjectsManager'; import { ZipImportDialog } from '@/components/ZipImportDialog';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useToast } from '@/hooks/useToast';
import type { Project } from '@/lib/ProjectsManager';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { useQueryClient } from '@tanstack/react-query'; import { useQueryClient } from '@tanstack/react-query';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
interface ChatItemProps { interface ProjectItemProps {
item: ChatItem; project: Project;
isSelected: boolean; isSelected: boolean;
onSelect: (item: ChatItem) => void; onSelect: (project: Project) => void;
isFavorite?: boolean; isFavorite?: boolean;
} }
const ChatItemComponent: React.FC<ChatItemProps> = ({ item, isSelected, onSelect, isFavorite }) => { const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect, isFavorite }) => {
const navigate = useNavigate(); const navigate = useNavigate();
const { hasRunningSessions } = useProjectSessionStatus(item.id); const { hasRunningSessions } = useProjectSessionStatus(project.id);
const handleClick = () => { const handleClick = () => {
onSelect(item); onSelect(project);
if (item.type === 'project') { navigate(`/project/${project.id}`);
navigate(`/project/${item.id}`);
} else {
navigate(`/chat/${item.id}`);
}
}; };
return ( return (
@@ -50,8 +48,6 @@ const ChatItemComponent: React.FC<ChatItemProps> = ({ item, isSelected, onSelect
<div className="flex-shrink-0"> <div className="flex-shrink-0">
{hasRunningSessions ? ( {hasRunningSessions ? (
<Loader2 className="h-4 w-4 animate-spin text-blue-600 dark:text-blue-400" /> <Loader2 className="h-4 w-4 animate-spin text-blue-600 dark:text-blue-400" />
) : item.type === 'chat' ? (
<MessageSquare className="h-4 w-4 text-accent" />
) : ( ) : (
<Folder className="h-4 w-4 text-primary" /> <Folder className="h-4 w-4 text-primary" />
)} )}
@@ -59,7 +55,7 @@ const ChatItemComponent: React.FC<ChatItemProps> = ({ item, isSelected, onSelect
<div className="flex justify-between gap-2 flex-1 min-w-0"> <div className="flex justify-between gap-2 flex-1 min-w-0">
<div className="min-w-0 flex-1 flex items-center"> <div className="min-w-0 flex-1 flex items-center">
<h3 className="font-medium text-sm truncate"> <h3 className="font-medium text-sm truncate">
{item.name} {project.name}
</h3> </h3>
</div> </div>
@@ -78,27 +74,30 @@ const ChatItemComponent: React.FC<ChatItemProps> = ({ item, isSelected, onSelect
); );
}; };
ChatItemComponent.displayName = 'ChatItemComponent'; ProjectItem.displayName = 'ProjectItem';
interface ProjectSidebarProps { interface ProjectSidebarProps {
selectedItem: ChatItem | null; selectedProject: Project | null;
onSelectItem: (item: ChatItem | null) => void; onSelectProject: (project: Project | null) => void;
className?: string; className?: string;
onToggleSidebar?: () => void; onToggleSidebar?: () => void;
onClose?: () => void; onClose?: () => void;
} }
export function ProjectSidebar({ export function ProjectSidebar({
selectedItem, selectedProject,
onSelectItem, onSelectProject,
className, className,
onToggleSidebar, onToggleSidebar,
onClose onClose
}: ProjectSidebarProps) { }: ProjectSidebarProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const { data: items = [], isLoading, error } = useProjects(); const { data: projects = [], isLoading, error } = useProjects();
const [favorites] = useLocalStorage<string[]>('project-favorites', []); const [favorites] = useLocalStorage<string[]>('project-favorites', []);
const projectsManager = useProjectsManager();
const { toast } = useToast();
const [isZipDialogOpen, setIsZipDialogOpen] = useState(false);
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const navigate = useNavigate(); const navigate = useNavigate();
@@ -112,15 +111,10 @@ export function ProjectSidebar({
}; };
const handleNewProject = () => { const handleNewProject = () => {
onSelectItem(null); onSelectProject(null);
navigateAndClose('/'); navigateAndClose('/');
}; };
const handleNewChat = () => {
onSelectItem(null);
navigateAndClose('/?mode=chat');
};
const handleToggleSidebar = () => { const handleToggleSidebar = () => {
if (onToggleSidebar) { if (onToggleSidebar) {
onToggleSidebar(); onToggleSidebar();
@@ -129,7 +123,24 @@ export function ProjectSidebar({
} }
}; };
const handleImportZip = async (file: File, overwrite = false, projectId?: string) => {
try {
// Import project from zip file
const project = await projectsManager.importProjectFromZip(file, projectId, overwrite);
// Show success toast
toast({
title: overwrite ? "Project Overwritten Successfully" : "Project Imported Successfully",
description: `"${project.name}" has been ${overwrite ? 'overwritten' : 'imported'} and is ready to use.`,
});
// Navigate to the imported project
navigate(`/project/${project.id}`);
} catch (error) {
console.error('Failed to import project:', error);
throw error; // Re-throw to let the dialog handle the error display
}
};
useEffect(() => { useEffect(() => {
queryClient.invalidateQueries({ queryKey: ['projects'] }); queryClient.invalidateQueries({ queryKey: ['projects'] });
@@ -142,42 +153,40 @@ export function ProjectSidebar({
return ( return (
<div className={cn("flex flex-col h-full bg-gradient-to-b from-sidebar to-sidebar/95", className)}> <div className={cn("flex flex-col h-full bg-gradient-to-b from-sidebar to-sidebar/95", className)}>
{/* Header with Logo */} {/* Header with Logo */}
<div className="pt-safe bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10"> <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 px-4 h-12 border-b border-sidebar-border"> <div className="flex items-center justify-between w-full">
<div className="flex items-center justify-between w-full"> <button
<button onClick={() => navigateAndClose('/')}
onClick={() => navigateAndClose('/')} className="flex items-center gap-3 hover:opacity-80 transition-opacity text-left"
className="flex items-center gap-3 hover:opacity-80 transition-opacity text-left" >
> <span className="text-2xl">🎭</span>
<ShakespeareLogo className="w-6 h-6" /> <h1 className="text-xl font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
<h1 className="text-xl font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent"> Shakespeare
Shakespeare </h1>
</h1> </button>
</button> {(onToggleSidebar || (onClose && isMobile)) && (
{(onToggleSidebar || (onClose && isMobile)) && ( <div className="flex items-center gap-1">
<div className="flex items-center gap-1"> <Button
<Button variant="ghost"
variant="ghost" size="sm"
size="sm" className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2" onClick={handleToggleSidebar}
onClick={handleToggleSidebar} aria-label={(onClose && isMobile) ? t('closeSidebar') : t('collapseSidebar')}
aria-label={(onClose && isMobile) ? t('closeSidebar') : t('collapseSidebar')} >
> {(onClose && isMobile) ? (
{(onClose && isMobile) ? ( <X className="h-4 w-4 text-primary/60 hover:text-primary" />
<X className="h-4 w-4 text-primary/60 hover:text-primary" /> ) : (
) : ( <Columns2 className="h-4 w-4 text-primary/60 hover:text-primary" />
<Columns2 className="h-4 w-4 text-primary/60 hover:text-primary" /> )}
)} </Button>
</Button> </div>
</div> )}
)}
</div>
</div> </div>
</div> </div>
<div className="flex-1 overflow-y-auto"> <div className="flex-1 overflow-y-auto">
<div className="p-2"> <div className="p-2">
<div className="mb-2 space-y-2"> <div className="mb-2">
<div className="relative rounded-md bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90 transition-all duration-200"> <div className="relative rounded-md bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90 transition-all duration-200">
<div className="flex"> <div className="flex">
<button <button
@@ -202,18 +211,17 @@ export function ProjectSidebar({
<GitBranch className="h-4 w-4" /> <GitBranch className="h-4 w-4" />
{t('importRepository')} {t('importRepository')}
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem
onClick={() => setIsZipDialogOpen(true)}
className="flex items-center gap-2 w-full"
>
<FileArchive className="h-4 w-4" />
Import ZIP File
</DropdownMenuItem>
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>
</div> </div>
</div> </div>
<Button
onClick={handleNewChat}
className="w-full bg-gradient-to-r from-accent to-primary hover:from-accent/90 hover:to-primary/90 transition-all duration-200"
size="sm"
>
<MessageSquare className="h-4 w-4 mr-2" />
{t('newChat')}
</Button>
</div> </div>
{isLoading ? ( {isLoading ? (
@@ -227,7 +235,7 @@ export function ProjectSidebar({
</div> </div>
))} ))}
</div> </div>
) : items.length === 0 ? ( ) : projects.length === 0 ? (
<div className="text-center p-6 text-muted-foreground"> <div className="text-center p-6 text-muted-foreground">
<Folder className="h-8 w-8 mx-auto mb-2 opacity-50" /> <Folder className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">{t('noProjectsYet')}</p> <p className="text-sm">{t('noProjectsYet')}</p>
@@ -235,13 +243,13 @@ export function ProjectSidebar({
</div> </div>
) : ( ) : (
<div className="space-y-1"> <div className="space-y-1">
{items.map((item) => ( {projects.map((project) => (
<ChatItemComponent <ProjectItem
key={item.id} key={project.id}
item={item} project={project}
isSelected={selectedItem?.id === item.id} isSelected={selectedProject?.id === project.id}
onSelect={onSelectItem} onSelect={onSelectProject}
isFavorite={favorites.includes(item.id)} isFavorite={favorites.includes(project.id)}
/> />
))} ))}
</div> </div>
@@ -250,8 +258,8 @@ export function ProjectSidebar({
</div> </div>
{/* Settings and Help at Bottom */} {/* Settings and Help at Bottom */}
<div className="border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto pb-safe"> <div className="p-2 border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto">
<div className="p-2 flex items-center gap-2"> <div className="flex items-center gap-2">
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
@@ -272,6 +280,13 @@ export function ProjectSidebar({
</Button> </Button>
</div> </div>
</div> </div>
{/* ZIP Import Dialog */}
<ZipImportDialog
onImport={handleImportZip}
open={isZipDialogOpen}
onOpenChange={setIsZipDialogOpen}
/>
</div> </div>
); );
} }
-80
View File
@@ -1,80 +0,0 @@
import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import { Quilly } from './Quilly';
import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
// Mock all required hooks and components
vi.mock('@/hooks/useAISettings', () => ({
useAISettings: () => ({
settings: {
providers: []
}
})
}));
vi.mock('@/hooks/useAICredits', () => ({
useAICredits: () => ({
data: null
})
}));
vi.mock('react-router-dom', () => ({
useNavigate: () => vi.fn()
}));
// Mock CreditsDialog to avoid NostrProvider dependency
vi.mock('./CreditsDialog', () => ({
CreditsDialog: () => null
}));
describe('Quilly', () => {
const defaultProps = {
error: new Error('Generic error'),
onDismiss: vi.fn(),
onNewChat: vi.fn(),
onOpenModelSelector: vi.fn(),
providerModel: 'test/model'
};
it('renders generic error message', () => {
render(<Quilly {...defaultProps} />);
expect(screen.getByText(/AI service error: Generic error/)).toBeInTheDocument();
});
it('renders correctly for malformed tool call errors', () => {
const error = new MalformedToolCallError(
'The AI provider sent an incomplete response.',
'call_abc123',
'test/model'
);
render(
<Quilly
{...defaultProps}
error={error}
/>
);
expect(screen.getByText(/The AI sent an incomplete response/)).toBeInTheDocument();
expect(screen.getByText(/Change model/)).toBeInTheDocument();
});
it('renders correctly for console errors', () => {
const error = new ProjectPreviewConsoleError(
'Console error',
[]
);
render(
<Quilly
{...defaultProps}
error={error}
/>
);
expect(screen.getByText(/I noticed some console errors/)).toBeInTheDocument();
expect(screen.getByText(/Help fix errors/)).toBeInTheDocument();
});
});
+3 -23
View File
@@ -7,9 +7,8 @@ import { useAISettings } from '@/hooks/useAISettings';
import { parseProviderModel } from '@/lib/parseProviderModel'; import { parseProviderModel } from '@/lib/parseProviderModel';
import { useAICredits } from '@/hooks/useAICredits'; import { useAICredits } from '@/hooks/useAICredits';
import { CreditsDialog } from './CreditsDialog'; import { CreditsDialog } from './CreditsDialog';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages'; import { ProjectPreviewConsoleError } from '@/contexts/ConsoleContext';
import { useState } from 'react'; import { useState } from 'react';
import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError';
export interface QuillyProps { export interface QuillyProps {
error: Error; error: Error;
@@ -31,17 +30,8 @@ interface ErrorBody {
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onRequestConsoleErrorHelp, providerModel }: QuillyProps) { export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
const navigate = useNavigate(); const navigate = useNavigate();
const { settings } = useAISettings(); const { settings } = useAISettings();
const { provider } = parseProviderModel(providerModel, settings.providers);
// Handle empty provider model gracefully const credits = useAICredits(provider);
let provider;
try {
provider = parseProviderModel(providerModel, settings.providers).provider;
} catch {
// If no valid provider model, use a default or undefined
provider = undefined;
}
const credits = useAICredits(provider || { id: '', name: '', apiKey: '', nostr: false });
const [showCreditsDialog, setShowCreditsDialog] = useState(false); const [showCreditsDialog, setShowCreditsDialog] = useState(false);
const renderBody = (error: Error): ErrorBody => { const renderBody = (error: Error): ErrorBody => {
@@ -59,16 +49,6 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onReq
}; };
} }
if (error instanceof MalformedToolCallError) {
return {
message: 'The AI sent an incomplete response, possibly due to a network issue or provider problem. Try sending your message again, or switch to a different model if this persists.',
action: {
label: 'Change model',
onClick: onOpenModelSelector,
},
};
}
// Handle OpenAI API errors with specific error codes // Handle OpenAI API errors with specific error codes
if (error instanceof OpenAI.APIError) { if (error instanceof OpenAI.APIError) {
switch (error.code) { switch (error.code) {
+22 -19
View File
@@ -3,11 +3,11 @@ import { useNavigate, useLocation, Outlet } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area'; import { ScrollArea } from '@/components/ui/scroll-area';
import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react'; import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info, Mail } from 'lucide-react';
import { ProjectSidebar } from '@/components/ProjectSidebar'; import { ProjectSidebar } from '@/components/ProjectSidebar';
import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useIsMobile } from '@/hooks/useIsMobile'; import { useIsMobile } from '@/hooks/useIsMobile';
import { type ChatItem } from '@/lib/ProjectsManager'; import { type Project } from '@/lib/ProjectsManager';
import { useCallback } from 'react'; import { useCallback } from 'react';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
@@ -56,6 +56,13 @@ const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [
icon: Database, icon: Database,
href: '/settings/data', href: '/settings/data',
}, },
{
id: 'email',
title: t('emailUpdates'),
description: t('emailUpdatesDescription'),
icon: Mail,
href: '/settings/email',
},
{ {
id: 'about', id: 'about',
title: t('aboutShakespeare'), title: t('aboutShakespeare'),
@@ -72,14 +79,14 @@ export function SettingsLayout() {
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const projectsManager = useProjectsManager(); const projectsManager = useProjectsManager();
const [_projects, setProjects] = useState<ChatItem[]>([]); const [_projects, setProjects] = useState<Project[]>([]);
const [isSidebarVisible, setIsSidebarVisible] = useState(!isMobile); const [isSidebarVisible, setIsSidebarVisible] = useState(!isMobile);
const [hasSetInitialState, setHasSetInitialState] = useState(false); const [hasSetInitialState, setHasSetInitialState] = useState(false);
const loadProjects = useCallback(async () => { const loadProjects = useCallback(async () => {
try { try {
await projectsManager.init(); await projectsManager.init();
const projectList = await projectsManager.getAllChatItems(); const projectList = await projectsManager.getProjects();
setProjects(projectList); setProjects(projectList);
// Set initial sidebar state based on projects and device type // Set initial sidebar state based on projects and device type
@@ -104,14 +111,10 @@ export function SettingsLayout() {
loadProjects(); loadProjects();
}, [loadProjects]); }, [loadProjects]);
const handleProjectSelect = (item: ChatItem | null) => { const handleProjectSelect = (project: Project | null) => {
if (item) { if (project) {
setIsSidebarVisible(false); // Collapse sidebar on mobile navigation setIsSidebarVisible(false); // Collapse sidebar on mobile navigation
if (item.type === 'project') { navigate(`/project/${project.id}`);
navigate(`/project/${item.id}`);
} else {
navigate(`/chat/${item.id}`);
}
} else { } else {
navigate('/'); navigate('/');
} }
@@ -124,10 +127,10 @@ export function SettingsLayout() {
if (isMobile) { if (isMobile) {
return ( return (
<div className="min-h-dvh pb-safe bg-background"> <div className="min-h-dvh bg-background">
{/* Mobile Header */} {/* Mobile Header */}
<header className="pt-safe bg-background"> <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 h-12 border-b px-4 py-3"> <div className="flex items-center space-x-2">
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
@@ -149,10 +152,10 @@ export function SettingsLayout() {
/> />
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10"> <div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
<ProjectSidebar <ProjectSidebar
selectedItem={null} selectedProject={null}
onSelectItem={(item) => { onSelectProject={(project) => {
setIsSidebarVisible(false); setIsSidebarVisible(false);
handleProjectSelect(item); handleProjectSelect(project);
}} }}
onClose={() => setIsSidebarVisible(false)} onClose={() => setIsSidebarVisible(false)}
/> />
@@ -172,8 +175,8 @@ export function SettingsLayout() {
{isSidebarVisible && ( {isSidebarVisible && (
<div className="w-80 border-r bg-sidebar flex-shrink-0"> <div className="w-80 border-r bg-sidebar flex-shrink-0">
<ProjectSidebar <ProjectSidebar
selectedItem={null} selectedProject={null}
onSelectItem={handleProjectSelect} onSelectProject={handleProjectSelect}
className="h-full" className="h-full"
onToggleSidebar={() => setIsSidebarVisible(false)} onToggleSidebar={() => setIsSidebarVisible(false)}
/> />
+67 -103
View File
@@ -35,14 +35,13 @@ import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
import { ShellTool } from '@/lib/tools/ShellTool'; import { ShellTool } from '@/lib/tools/ShellTool';
import { TypecheckTool } from '@/lib/tools/TypecheckTool'; import { TypecheckTool } from '@/lib/tools/TypecheckTool';
import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool'; import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages'; import { useConsole, ProjectPreviewConsoleError } from '@/contexts/ConsoleContext';
import { toolToOpenAI } from '@/lib/tools/openai-adapter'; import { toolToOpenAI } from '@/lib/tools/openai-adapter';
import { Tool } from '@/lib/tools/Tool'; import { Tool } from '@/lib/tools/Tool';
import OpenAI from 'openai'; import OpenAI from 'openai';
import { saveFileToTmp } from '@/lib/fileUtils'; import { saveFileToTmp } from '@/lib/fileUtils';
import { useGit } from '@/hooks/useGit'; import { useGit } from '@/hooks/useGit';
import { Quilly } from '@/components/Quilly'; import { Quilly } from '@/components/Quilly';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
// Clean interfaces now handled by proper hooks // Clean interfaces now handled by proper hooks
@@ -53,9 +52,6 @@ interface ChatPaneProps {
onLoadingChange?: (isLoading: boolean) => void; onLoadingChange?: (isLoading: boolean) => void;
isLoading?: boolean; isLoading?: boolean;
isBuildLoading?: boolean; isBuildLoading?: boolean;
consoleError?: ProjectPreviewConsoleError | null;
onDismissConsoleError?: () => void;
isTextChat?: boolean; // Whether this is a text chat (no tools) vs a project chat
} }
export interface ChatPaneRef { export interface ChatPaneRef {
@@ -69,16 +65,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
onLoadingChange, onLoadingChange,
isLoading: externalIsLoading, isLoading: externalIsLoading,
isBuildLoading: externalIsBuildLoading, isBuildLoading: externalIsBuildLoading,
consoleError,
onDismissConsoleError,
isTextChat = false,
}, ref) => { }, ref) => {
const { t } = useTranslation(); const { t } = useTranslation();
const [searchParams, setSearchParams] = useSearchParams();
const { fs } = useFS();
const { git } = useGit();
const { user } = useCurrentUser();
const { models } = useProviderModels();
const [input, setInput] = useState(''); const [input, setInput] = useState('');
const [showScrollToBottom, setShowScrollToBottom] = useState(false); const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const [attachedFiles, setAttachedFiles] = useState<File[]>([]); const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
@@ -88,8 +76,21 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const [isStuck, setIsStuck] = useState(false); const [isStuck, setIsStuck] = useState(false);
const [aiError, setAIError] = useState<Error | null>(null); const [aiError, setAIError] = useState<Error | null>(null);
// Determine which error to show - console error takes priority over AI errors // Get console functionality early so it can be used in useEffect
const displayError = consoleError || aiError; const { messagesRef: consoleMessagesRef, addErrorListener, removeErrorListener } = useConsole();
// Console error handling
useEffect(() => {
const handleConsoleError = (error: ProjectPreviewConsoleError) => {
// Only show console errors if there's no existing AI error
if (!aiError) {
setAIError(error);
}
};
addErrorListener(handleConsoleError);
return () => removeErrorListener(handleConsoleError);
}, [aiError, addErrorListener, removeErrorListener]);
// Use external state if provided, otherwise default to false // Use external state if provided, otherwise default to false
const isBuildLoading = externalIsBuildLoading || false; const isBuildLoading = externalIsBuildLoading || false;
@@ -101,7 +102,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}); });
// State to control model selector dropdown // State to control model selector dropdown
const [isModelSelectorOpen, setIsModelSelectorOpen] = useState(false); const [isModelSelectorOpen, setIsModelSelectorOpen] = useState(false);
const [shouldAutostart, setShouldAutostart] = useState(false);
const autostartedRef = useRef(false); const autostartedRef = useRef(false);
useEffect(() => { useEffect(() => {
@@ -110,37 +110,20 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
} }
}, [providerModel, settings.recentlyUsedModels]); }, [providerModel, settings.recentlyUsedModels]);
useEffect(() => {
const urlModel = searchParams.get('model');
const autostart = searchParams.get('autostart');
if (urlModel && !providerModel) {
setProviderModel(urlModel);
}
if (autostart === 'true') {
setShouldAutostart(true);
}
// Clear the autostart and model parameters
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.delete('autostart');
newSearchParams.delete('model');
setSearchParams(newSearchParams, { replace: true });
}, [providerModel, searchParams, setSearchParams])
// Reset error state when navigating between projects and switching models // Reset error state when navigating between projects and switching models
useEffect(() => { useEffect(() => {
setAIError(null); setAIError(null);
}, [projectId, providerModel]); }, [projectId, providerModel]);
// Initialize AI chat with tools const [searchParams, setSearchParams] = useSearchParams();
const cwd = isTextChat ? `/chats/${projectId}` : `/projects/${projectId}`; const { fs } = useFS();
const customTools = useMemo(() => { const { git } = useGit();
// For text chats, return empty tools object const { user } = useCurrentUser();
if (isTextChat) { const { models } = useProviderModels();
return {};
}
// Initialize AI chat with tools
const cwd = `/projects/${projectId}`;
const customTools = useMemo(() => {
const baseTools = { const baseTools = {
git_commit: new GitCommitTool(fs, cwd, git), git_commit: new GitCommitTool(fs, cwd, git),
text_editor_view: new TextEditorViewTool(fs, cwd), text_editor_view: new TextEditorViewTool(fs, cwd),
@@ -158,7 +141,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
nostr_read_nips_index: new NostrReadNipsIndexTool(), nostr_read_nips_index: new NostrReadNipsIndexTool(),
nostr_generate_kind: new NostrGenerateKindTool(), nostr_generate_kind: new NostrGenerateKindTool(),
shell: new ShellTool(fs, cwd, git), shell: new ShellTool(fs, cwd, git),
read_console_messages: new ReadConsoleMessagesTool(), read_console_messages: new ReadConsoleMessagesTool(() => consoleMessagesRef.current),
}; };
// Add deploy tool only if user is logged in // Add deploy tool only if user is logged in
@@ -170,7 +153,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
} }
return baseTools; return baseTools;
}, [fs, git, cwd, user, projectId, isTextChat]); }, [fs, git, cwd, user, projectId, consoleMessagesRef]);
// Convert tools to OpenAI format // Convert tools to OpenAI format
const tools = useMemo(() => { const tools = useMemo(() => {
@@ -188,7 +171,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
artist: `Working on ${projectId}...`, artist: `Working on ${projectId}...`,
artwork: [ artwork: [
{ {
src: '/shakespeare.png', src: '/favicon.png',
sizes: '512x512', sizes: '512x512',
type: 'image/png' type: 'image/png'
} }
@@ -211,7 +194,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
isLoading: internalIsLoading, isLoading: internalIsLoading,
totalCost, totalCost,
lastInputTokens, lastInputTokens,
addMessage,
sendMessage, sendMessage,
startGeneration, startGeneration,
stopGeneration, stopGeneration,
@@ -222,46 +204,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
customTools, customTools,
onUpdateMetadata, onUpdateMetadata,
onAIError, onAIError,
isTextChat,
}); });
// Handle console error help requests // Handle console error help requests
const handleConsoleErrorHelp = useCallback(async () => { const handleConsoleErrorHelp = useCallback(() => {
const tool = new ReadConsoleMessagesTool(); sendMessage('Read the console messages and fix any errors present.', providerModel);
const toolCallId = `call_${crypto.randomUUID().replace(/-/g, '')}`; }, [sendMessage, providerModel]);
await addMessage({
role: 'assistant',
content: 'Let me take a look at the console messages to help diagnose the issue.',
tool_calls: [
{
id: toolCallId,
type: 'function',
function: {
name: 'read_console_messages',
arguments: '{}',
}
}
]
});
await addMessage({
role: 'tool',
content: await tool.execute({ filter: 'error' }),
tool_call_id: toolCallId,
});
await startGeneration(providerModel);
}, [addMessage, providerModel, startGeneration]);
// Handle error dismissal
const handleErrorDismiss = useCallback(() => {
if (consoleError && onDismissConsoleError) {
onDismissConsoleError();
} else {
setAIError(null);
}
}, [consoleError, onDismissConsoleError]);
// Use external loading state if provided, otherwise use internal state // Use external loading state if provided, otherwise use internal state
const isLoading = externalIsLoading !== undefined ? externalIsLoading : internalIsLoading; const isLoading = externalIsLoading !== undefined ? externalIsLoading : internalIsLoading;
@@ -309,24 +257,41 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
setIsModelSelectorOpen(true); setIsModelSelectorOpen(true);
}, []); }, []);
// Scroll to bottom when any error occurs (AI error or console error) // Scroll to bottom when AI error occurs
useEffect(() => { useEffect(() => {
if (displayError) { scrollToBottom();
scrollToBottom(); }, [aiError, scrollToBottom]);
}
}, [displayError, scrollToBottom]);
// Check for autostart parameter and trigger AI generation // Check for autostart parameter and trigger AI generation
useEffect(() => { useEffect(() => {
if (autostartedRef.current) return; if (autostartedRef.current) return;
if (shouldAutostart && providerModel && isConfigured) { const autostart = searchParams.get('autostart');
// Start AI generation const urlModel = searchParams.get('model');
addRecentlyUsedModel(providerModel);
startGeneration(providerModel); if (autostart === 'true' && isConfigured) {
autostartedRef.current = true; // Use model from URL if available, otherwise use current selection
const modelToUse = urlModel?.trim() || providerModel.trim();
if (modelToUse) {
// Update provider model if it came from URL
if (urlModel?.trim() && urlModel.trim() !== providerModel) {
setProviderModel(urlModel.trim());
}
// Clear the autostart and model parameters so they don't trigger again
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.delete('autostart');
newSearchParams.delete('model');
setSearchParams(newSearchParams, { replace: true });
// Start AI generation
addRecentlyUsedModel(modelToUse);
startGeneration(modelToUse);
autostartedRef.current = true;
}
} }
}, [addRecentlyUsedModel, isConfigured, providerModel, shouldAutostart, startGeneration]); }, [addRecentlyUsedModel, isConfigured, providerModel, searchParams, setSearchParams, startGeneration]);
// Simple scroll event listener // Simple scroll event listener
useEffect(() => { useEffect(() => {
@@ -565,9 +530,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
{messages.length === 0 && !streamingMessage && !isLoading && ( {messages.length === 0 && !streamingMessage && !isLoading && (
<div className="flex-1 flex items-center justify-center min-h-[400px]"> <div className="flex-1 flex items-center justify-center min-h-[400px]">
<div className="text-center space-y-4 max-w-md mx-auto"> <div className="text-center space-y-4 max-w-md mx-auto">
<div className="mb-6"> <div className="text-6xl mb-6">🎭</div>
<ShakespeareLogo className="w-16 h-16 mx-auto" />
</div>
<div> <div>
<h3 className="text-xl font-semibold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent"> <h3 className="text-xl font-semibold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
{t('welcomeToShakespeare')} {t('welcomeToShakespeare')}
@@ -650,11 +613,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</div> </div>
)} )}
{/* Error Alert (Console or AI) */} {/* AI Error Alert */}
{displayError && ( {aiError && (
<Quilly <Quilly
error={displayError} error={aiError}
onDismiss={handleErrorDismiss} onDismiss={() => setAIError(null)}
onNewChat={onNewChat} onNewChat={onNewChat}
onOpenModelSelector={openModelSelector} onOpenModelSelector={openModelSelector}
onRequestConsoleErrorHelp={handleConsoleErrorHelp} onRequestConsoleErrorHelp={handleConsoleErrorHelp}
@@ -682,7 +645,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
{/* Chat Input Container */} {/* Chat Input Container */}
<div <div
className={`flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : '' className={`flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
}`} }`}
onDragEnter={handleDragEnter} onDragEnter={handleDragEnter}
onDragOver={handleDragOver} onDragOver={handleDragOver}
onDragLeave={handleDragLeave} onDragLeave={handleDragLeave}
@@ -698,8 +661,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
!isConfigured !isConfigured
? t('askToAddFeatures') ? t('askToAddFeatures')
: providerModel.trim() : providerModel.trim()
? t('askToAddFeatures') ? t('askToAddFeatures')
: t('selectModelFirst') : 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" 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 || (isConfigured && !providerModel.trim())} disabled={isLoading || (isConfigured && !providerModel.trim())}
@@ -772,6 +735,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<ModelSelector <ModelSelector
value={providerModel} value={providerModel}
onChange={setProviderModel} onChange={setProviderModel}
className="w-full"
disabled={isLoading} disabled={isLoading}
placeholder={t('chooseModel')} placeholder={t('chooseModel')}
open={isModelSelectorOpen} open={isModelSelectorOpen}
+1 -1
View File
@@ -30,7 +30,7 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
const [gitignoreFilter, setGitignoreFilter] = useState<{ const [gitignoreFilter, setGitignoreFilter] = useState<{
isIgnored: (path: string) => boolean; isIgnored: (path: string) => boolean;
shouldShow: (path: string) => boolean; shouldShow: (path: string) => boolean;
} | null>(null); } | null>(null);
const [searchTerm, setSearchTerm] = useState(''); const [searchTerm, setSearchTerm] = useState('');
const [isSearching, setIsSearching] = useState(false); const [isSearching, setIsSearching] = useState(false);
const { fs } = useFS(); const { fs } = useFS();
+126 -198
View File
@@ -3,13 +3,12 @@ import { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useFS } from '@/hooks/useFS'; import { useFS } from '@/hooks/useFS';
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/consoleMessages'; import { useConsole, type ConsoleMessage } from '@/contexts/ConsoleContext';
import { useConsoleError } from '@/hooks/useConsoleError';
import { useBuildProject } from '@/hooks/useBuildProject'; import { useBuildProject } from '@/hooks/useBuildProject';
import { Tabs, TabsContent } from '@/components/ui/tabs'; import { Tabs, TabsContent } from '@/components/ui/tabs';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area'; import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload, X, Terminal } from 'lucide-react'; import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload, X } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile'; import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator'; import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { BrowserAddressBar } from '@/components/ui/browser-address-bar'; import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
@@ -28,7 +27,6 @@ import { cn } from '@/lib/utils';
import { FileTree } from './FileTree'; import { FileTree } from './FileTree';
import { FileEditor } from './FileEditor'; import { FileEditor } from './FileEditor';
import { DeployDialog } from '@/components/DeployDialog'; import { DeployDialog } from '@/components/DeployDialog';
import { Terminal as TerminalComponent } from '@/components/Terminal';
import { useSearchParams } from 'react-router-dom'; import { useSearchParams } from 'react-router-dom';
// Get iframe domain from environment variable // Get iframe domain from environment variable
@@ -78,8 +76,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
const [selectedFile, setSelectedFile] = useState<string | null>(null); const [selectedFile, setSelectedFile] = useState<string | null>(null);
const [fileContent, setFileContent] = useState<string>(''); const [fileContent, setFileContent] = useState<string>('');
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [mobileCodeView, setMobileCodeView] = useState<'explorer' | 'editor' | 'terminal'>('explorer'); const [mobileCodeView, setMobileCodeView] = useState<'explorer' | 'editor'>('explorer');
const [desktopCodeView, setDesktopCodeView] = useState<'files' | 'terminal'>('files');
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const [hasBuiltProject, setHasBuiltProject] = useState(false); const [hasBuiltProject, setHasBuiltProject] = useState(false);
const [currentPath, setCurrentPath] = useState('/'); const [currentPath, setCurrentPath] = useState('/');
@@ -90,9 +87,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
const iframeRef = useRef<HTMLIFrameElement>(null); const iframeRef = useRef<HTMLIFrameElement>(null);
const { fs } = useFS(); const { fs } = useFS();
const projectsManager = useProjectsManager(); const projectsManager = useProjectsManager();
const { addMessage: addConsoleMessage, messages: consoleMessages } = useConsole();
// Use console error state from provider
const { hasErrors: hasConsoleErrors, clearErrors } = useConsoleError();
const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId); const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId);
@@ -226,7 +221,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
// Log to parent console for debugging with appropriate level // Log to parent console for debugging with appropriate level
console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`); console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`);
}, []); }, [addConsoleMessage]);
const handleUpdateNavigationState = useCallback((message: { const handleUpdateNavigationState = useCallback((message: {
jsonrpc: '2.0'; jsonrpc: '2.0';
@@ -457,24 +452,16 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
}, [selectedFile, loadFileContent]); }, [selectedFile, loadFileContent]);
// Reset selected file and navigation history when projectId changes // Reset selected file and navigation history when projectId changes
const prevProjectIdRef = useRef<string>();
useEffect(() => { useEffect(() => {
setSelectedFile(null); setSelectedFile(null);
setFileContent(''); setFileContent('');
setMobileCodeView('explorer'); setMobileCodeView('explorer');
setDesktopCodeView('files');
// Reset navigation history and state // Reset navigation history and state
setCurrentPath('/'); setCurrentPath('/');
setNavigationHistory(['/']); setNavigationHistory(['/']);
setHistoryIndex(0); setHistoryIndex(0);
}, [projectId]);
// Only clear console messages when projectId actually changes (not on initial mount)
if (prevProjectIdRef.current && prevProjectIdRef.current !== projectId) {
clearErrors();
}
prevProjectIdRef.current = projectId;
}, [projectId, clearErrors]);
useEffect(() => { useEffect(() => {
checkForBuiltProject(); checkForBuiltProject();
@@ -508,12 +495,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
try { try {
await fs.writeFile(`/projects/${projectId}/${selectedFile}`, content); await fs.writeFile(`/projects/${projectId}/${selectedFile}`, content);
setFileContent(content); setFileContent(content);
// Automatically trigger a rebuild after saving a file
if (isPreviewable) {
console.log('File saved, triggering rebuild...');
handleBuildProject();
}
} catch (error) { } catch (error) {
console.error('Failed to save file:', error); console.error('Failed to save file:', error);
} }
@@ -523,8 +504,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null); const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
const messages = isOpen ? getConsoleMessages() : [];
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => { const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
try { try {
await navigator.clipboard.writeText(msg.message); await navigator.clipboard.writeText(msg.message);
@@ -535,7 +514,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
} }
}; };
const messageCount = messages.length; // consoleMessages is now available from the hook
const messageCount = consoleMessages.length;
const hasErrors = consoleMessages.some(msg => msg.level === 'error');
return ( return (
<Popover open={isOpen} onOpenChange={setIsOpen}> <Popover open={isOpen} onOpenChange={setIsOpen}>
@@ -543,10 +524,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
className="h-8 w-8 p-0 relative" className="h-8 w-8 p-0 relative hover:bg-accent hover:text-accent-foreground transition-colors"
> >
<Bug className="h-4 w-4" /> <Bug className="h-4 w-4" />
{hasConsoleErrors && ( {hasErrors && (
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" /> <span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
)} )}
</Button> </Button>
@@ -566,7 +547,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p> <p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
</div> </div>
) : ( ) : (
messages.map((msg, index) => ( consoleMessages.map((msg, index) => (
<div <div
key={index} key={index}
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer" className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer"
@@ -578,9 +559,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
<div className={cn( <div className={cn(
"text-xs font-mono leading-tight whitespace-pre-wrap break-words", "text-xs font-mono leading-tight whitespace-pre-wrap break-words",
msg.level === 'error' ? "text-destructive" : msg.level === 'error' ? "text-destructive" :
msg.level === 'warn' ? "text-warning" : msg.level === 'warn' ? "text-warning" :
msg.level === 'info' ? "text-primary" : msg.level === 'info' ? "text-primary" :
"text-muted-foreground" "text-muted-foreground"
)}> )}>
{msg.message} {msg.message}
</div> </div>
@@ -664,133 +645,103 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
<Tabs value={activeTab} className="h-full"> <Tabs value={activeTab} className="h-full">
{isPreviewable && ( {isPreviewable && (
<TabsContent value="preview" className="h-full mt-0"> <TabsContent value="preview" className="h-full mt-0">
<div className="h-full w-full flex flex-col relative"> <div className="h-full w-full flex flex-col relative">
{/* Always show browser address bar */} {/* Always show browser address bar */}
<div className="h-12 flex items-center w-full"> <div className="h-12 flex items-center w-full">
<BrowserAddressBar <BrowserAddressBar
currentPath={currentPath} currentPath={currentPath}
onNavigate={hasBuiltProject ? navigateIframe : undefined} onNavigate={hasBuiltProject ? navigateIframe : undefined}
onRefresh={hasBuiltProject ? refreshIframe : undefined} onRefresh={hasBuiltProject ? refreshIframe : undefined}
onBack={hasBuiltProject ? goBackIframe : undefined} onBack={hasBuiltProject ? goBackIframe : undefined}
onForward={hasBuiltProject ? goForwardIframe : undefined} onForward={hasBuiltProject ? goForwardIframe : undefined}
canGoBack={hasBuiltProject && historyIndex > 0} canGoBack={hasBuiltProject && historyIndex > 0}
canGoForward={hasBuiltProject && historyIndex < navigationHistory.length - 1} canGoForward={hasBuiltProject && historyIndex < navigationHistory.length - 1}
extraContent={( extraContent={(
<div className="flex items-center"> <div className="flex items-center">
{(!isMobile && onToggleView && isPreviewable) && ( {(!isMobile && onToggleView && isPreviewable) && (
<Button
variant="ghost"
size="sm"
onClick={onToggleView}
className="h-8 gap-2"
>
<Code className="h-4 w-4" />
</Button>
)}
<ConsoleDropdown />
<Menu />
</div>
)}
/>
</div>
{/* Content area */}
<div className="flex-1">
{hasBuiltProject ? (
<iframe
ref={iframeRef}
src={`https://${projectId}.${IFRAME_DOMAIN}/`}
className="w-full h-full border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin"
/>
) : (
<div className="h-full flex items-center justify-center bg-muted">
<div className="text-center">
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
<p className="text-muted-foreground mb-4">
{t('buildProjectToSeePreview')}
</p>
<Button <Button
onClick={handleBuildProject} variant="ghost"
disabled={isBuildLoading} size="sm"
variant="outline" onClick={onToggleView}
className="gap-2" className="h-8 gap-2"
> >
{isBuildLoading ? ( <Code className="h-4 w-4" />
<>
<Loader2 className="h-5 w-5 animate-spin" />
Building...
</>
) : (
<>
<Play className="h-5 w-5" />
Build Project
</>
)}
</Button> </Button>
</div> )}
<ConsoleDropdown />
<Menu />
</div> </div>
)} )}
</div> />
</div>
{/* Build loading overlay */} {/* Content area */}
{isBuildLoading && ( <div className="flex-1">
<div className="absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10"> {hasBuiltProject ? (
<div className="bg-background/90 border rounded-lg p-4 shadow-lg flex items-center gap-3"> <iframe
<Loader2 className="h-5 w-5 animate-spin text-primary" /> ref={iframeRef}
<span className="text-sm font-medium">Building project...</span> src={`https://${projectId}.${IFRAME_DOMAIN}/`}
className="w-full h-full border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin"
/>
) : (
<div className="h-full flex items-center justify-center bg-muted">
<div className="text-center">
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
<p className="text-muted-foreground mb-4">
{t('buildProjectToSeePreview')}
</p>
<Button
onClick={handleBuildProject}
disabled={isBuildLoading}
variant="outline"
className="gap-2"
>
{isBuildLoading ? (
<>
<Loader2 className="h-5 w-5 animate-spin" />
Building...
</>
) : (
<>
<Play className="h-5 w-5" />
Build Project
</>
)}
</Button>
</div> </div>
</div> </div>
)} )}
</div> </div>
</TabsContent>
{/* Build loading overlay */}
{isBuildLoading && (
<div className="absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10">
<div className="bg-background/90 border rounded-lg p-4 shadow-lg flex items-center gap-3">
<Loader2 className="h-5 w-5 animate-spin text-primary" />
<span className="text-sm font-medium">Building project...</span>
</div>
</div>
)}
</div>
</TabsContent>
)} )}
<TabsContent value="code" className="h-full mt-0"> <TabsContent value="code" className="h-full mt-0">
{isMobile ? ( {isMobile ? (
<div className="h-full flex flex-col min-h-0"> <div className="h-full flex flex-col">
{mobileCodeView === 'explorer' ? ( {mobileCodeView === 'explorer' ? (
<div className="flex-1 relative min-h-0"> <ScrollArea className="flex-1">
<ScrollArea className="h-full"> <ScrollBar orientation="horizontal" />
<ScrollBar orientation="horizontal" /> <div className="min-w-max">
<div className="min-w-max"> <FileTree
<FileTree projectId={projectId}
projectId={projectId} onFileSelect={handleFileSelect}
onFileSelect={handleFileSelect} selectedFile={selectedFile}
selectedFile={selectedFile} />
/>
</div>
</ScrollArea>
{/* Floating Terminal Button */}
<Button
variant="outline"
size="sm"
onClick={() => setMobileCodeView('terminal')}
className="fixed right-4 bottom-14 mb-safe z-20 size-12 p-0 rounded-full shadow-lg bg-background border-2"
>
<Terminal className="h-6 w-6" />
</Button>
</div>
) : mobileCodeView === 'terminal' ? (
<>
<div className="h-12 px-3 flex items-center gap-2 bg-black text-purple-400 flex-shrink-0">
<Button
variant="ghost"
size="sm"
onClick={() => setMobileCodeView('explorer')}
className="p-1 hover:bg-transparent hover:text-white"
>
<ArrowLeft className="h-4 w-4" />
</Button>
<h3 className="font-semibold">
Terminal
</h3>
</div> </div>
<div className="flex-1 min-h-0"> </ScrollArea>
<TerminalComponent projectId={projectId} />
</div>
</>
) : ( ) : (
<> <>
<div className="p-3 border-b bg-gradient-to-r from-primary/5 to-accent/5 flex items-center gap-2"> <div className="p-3 border-b bg-gradient-to-r from-primary/5 to-accent/5 flex items-center gap-2">
@@ -853,73 +804,50 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
{t('backToPreview')} {t('backToPreview')}
</Button> </Button>
<div className="flex-1" /> <div className="flex-1" />
<Button <GitStatusIndicator projectId={projectId} />
variant="ghost"
size="sm"
onClick={() => setDesktopCodeView(desktopCodeView === 'terminal' ? 'files' : 'terminal')}
className="gap-2 text-muted-foreground hover:text-foreground"
>
<Terminal className="h-4 w-4" />
</Button>
</div> </div>
)} )}
{/* Code view header without back button for non-previewable projects */} {/* Code view header without back button for non-previewable projects */}
{!isMobile && !isPreviewable && ( {!isMobile && !isPreviewable && (
<div className="h-12 px-4 border-b flex items-center bg-gradient-to-r from-muted/20 to-background"> <div className="h-12 px-4 border-b flex items-center bg-gradient-to-r from-muted/20 to-background">
<div className="flex-1" /> <div className="flex-1" />
<Button
variant="ghost"
size="sm"
onClick={() => setDesktopCodeView(desktopCodeView === 'terminal' ? 'files' : 'terminal')}
className="gap-2 text-muted-foreground hover:text-foreground"
>
<Terminal className="h-4 w-4" />
</Button>
<GitStatusIndicator projectId={projectId} /> <GitStatusIndicator projectId={projectId} />
</div> </div>
)} )}
<div className="flex-1 flex min-h-0"> <div className="flex-1 flex min-h-0">
{desktopCodeView === 'terminal' ? ( <div className="w-1/3 border-r flex flex-col">
<div className="flex-1"> <ScrollArea className="flex-1">
<TerminalComponent projectId={projectId} /> <ScrollBar orientation="horizontal" />
</div> <div className="min-w-max">
) : ( <FileTree
<> projectId={projectId}
<div className="w-1/3 border-r flex flex-col"> onFileSelect={handleFileSelect}
<ScrollArea className="flex-1"> selectedFile={selectedFile}
<ScrollBar orientation="horizontal" /> />
<div className="min-w-max">
<FileTree
projectId={projectId}
onFileSelect={handleFileSelect}
selectedFile={selectedFile}
/>
</div>
</ScrollArea>
</div> </div>
</ScrollArea>
</div>
<div className="flex-1"> <div className="flex-1">
{selectedFile ? ( {selectedFile ? (
<FileEditor <FileEditor
filePath={selectedFile} filePath={selectedFile}
content={fileContent} content={fileContent}
onSave={handleFileSave} onSave={handleFileSave}
isLoading={isLoading} isLoading={isLoading}
projectId={projectId} projectId={projectId}
/> />
) : ( ) : (
<div className="h-full flex items-center justify-center"> <div className="h-full flex items-center justify-center">
<div className="text-center"> <div className="text-center">
<p className="text-muted-foreground"> <p className="text-muted-foreground">
{t('selectFileFromExplorer')} {t('selectFileFromExplorer')}
</p> </p>
</div> </div>
</div>
)}
</div> </div>
</> )}
)} </div>
</div> </div>
</div> </div>
)} )}
-13
View File
@@ -1,13 +0,0 @@
export interface ShakespeareLogoProps {
className?: string;
}
export function ShakespeareLogo({ className }: ShakespeareLogoProps) {
return (
<img
src="/shakespeare.svg"
alt="Shakespeare"
className={className}
/>
);
}
-240
View File
@@ -1,240 +0,0 @@
import { useState, useRef, useEffect, useCallback } from 'react';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { Copy } from 'lucide-react';
import { cn } from '@/lib/utils';
import { ShellTool } from '@/lib/tools/ShellTool';
import { useFS } from '@/hooks/useFS';
import { useGit } from '@/hooks/useGit';
import { ansiToHtml, containsAnsiCodes } from '@/lib/ansiToHtml';
interface TerminalProps {
projectId: string;
className?: string;
}
interface TerminalLine {
id: string;
type: 'input' | 'output' | 'error';
content: string;
timestamp: Date;
}
export function Terminal({ projectId, className }: TerminalProps) {
const [lines, setLines] = useState<TerminalLine[]>([]);
const [currentInput, setCurrentInput] = useState('');
const [isExecuting, setIsExecuting] = useState(false);
const [commandHistory, setCommandHistory] = useState<string[]>([]);
const [historyIndex, setHistoryIndex] = useState(-1);
const inputRef = useRef<HTMLInputElement>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const shellToolRef = useRef<ShellTool | null>(null);
const { fs } = useFS();
const { git } = useGit();
// Initialize ShellTool
useEffect(() => {
shellToolRef.current = new ShellTool(fs, `/projects/${projectId}`, git);
// Add welcome message
setLines([{
id: Date.now().toString(),
type: 'output',
content: `Welcome to Shakespeare Terminal\nType 'help' to see available commands.`,
timestamp: new Date()
}]);
}, [projectId, fs, git]);
// Auto-scroll to bottom when new lines are added or execution state changes
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
}, [lines, isExecuting]);
// Focus input when component mounts
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
// Refocus input after command execution
useEffect(() => {
if (!isExecuting && inputRef.current) {
inputRef.current.focus();
}
}, [isExecuting]);
const addLine = useCallback((type: TerminalLine['type'], content: string) => {
const newLine: TerminalLine = {
id: Date.now().toString() + Math.random(),
type,
content,
timestamp: new Date()
};
setLines(prev => [...prev, newLine]);
}, []);
const executeCommand = useCallback(async (command: string) => {
if (!shellToolRef.current || !command.trim()) return;
// Add command to history
if (command.trim() && !commandHistory.includes(command.trim())) {
setCommandHistory(prev => [...prev, command.trim()]);
}
setHistoryIndex(-1);
// Add input line
addLine('input', command);
setIsExecuting(true);
try {
// Handle special help command
if (command.trim() === 'help') {
const availableCommands = shellToolRef.current.getAvailableCommands();
const helpText = `Available commands:\n\n${availableCommands.map(cmd =>
`${cmd.name.padEnd(12)} - ${cmd.description}`
).join('\n')}\n\nUse 'which <command>' for more details about a specific command.`;
addLine('output', helpText);
} else if (command.trim() === 'clear') {
setLines([]);
} else {
const result = await shellToolRef.current.execute({ command });
// Add output
if (result && result.trim()) {
addLine('output', result);
}
}
} catch (error) {
addLine('error', `Error: ${error instanceof Error ? error.message : 'Unknown error'}`);
} finally {
setIsExecuting(false);
}
}, [addLine, commandHistory]);
const handleSubmit = useCallback((e: React.FormEvent) => {
e.preventDefault();
if (currentInput.trim() && !isExecuting) {
executeCommand(currentInput);
setCurrentInput('');
}
}, [currentInput, isExecuting, executeCommand]);
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
if (e.key === 'ArrowUp') {
e.preventDefault();
if (commandHistory.length > 0) {
const newIndex = historyIndex === -1 ? commandHistory.length - 1 : Math.max(0, historyIndex - 1);
setHistoryIndex(newIndex);
setCurrentInput(commandHistory[newIndex]);
}
} else if (e.key === 'ArrowDown') {
e.preventDefault();
if (historyIndex >= 0) {
const newIndex = historyIndex + 1;
if (newIndex >= commandHistory.length) {
setHistoryIndex(-1);
setCurrentInput('');
} else {
setHistoryIndex(newIndex);
setCurrentInput(commandHistory[newIndex]);
}
}
} else if (e.key === 'Tab') {
e.preventDefault();
// Basic tab completion could be added here
}
}, [commandHistory, historyIndex]);
const copyToClipboard = useCallback(async (content: string) => {
try {
// Strip ANSI codes when copying to clipboard
const cleanContent = content.replace(/\u001b\[(?:\d+;)*\d+m/g, '');
await navigator.clipboard.writeText(cleanContent);
} catch (error) {
console.error('Failed to copy to clipboard:', error);
}
}, []);
// Focus input when clicking anywhere in the terminal
const handleTerminalClick = useCallback(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
return (
<div className={cn("h-full flex flex-col bg-black text-slate-300 font-mono text-sm", className)}>
{/* Terminal Content */}
<div className="flex-1 flex flex-col min-h-0" onClick={handleTerminalClick}>
<ScrollArea className="flex-1" ref={scrollRef}>
<div className="p-2 space-y-1">
{lines.map((line) => (
<div
key={line.id}
className={cn(
"group relative",
line.type === 'input' && "text-white",
line.type === 'error' && "text-red-400",
line.type === 'output' && "text-slate-300"
)}
>
<pre className="whitespace-pre-wrap break-words font-mono leading-relaxed">
{line.type === 'input' ? (
<span className="text-purple-400 font-mono whitespace-nowrap">
${' '}
</span>
) : null}
{containsAnsiCodes(line.content)
? <span dangerouslySetInnerHTML={{ __html: ansiToHtml(line.content) }} />
: line.content}
</pre>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
copyToClipboard(line.content);
}}
className="absolute right-0 top-0 h-4 w-4 p-0 opacity-0 group-hover:opacity-100 transition-opacity text-gray-500 hover:text-white hover:bg-gray-700"
>
<Copy className="h-2 w-2" />
</Button>
</div>
))}
{/* Current Command Input - inline with content */}
{!isExecuting && (
<div className="flex items-center gap-2">
<span className="text-purple-400 font-mono whitespace-nowrap">
$
</span>
<form onSubmit={handleSubmit} className="flex-1 relative">
<input
ref={inputRef}
type="text"
value={currentInput}
onChange={(e) => setCurrentInput(e.target.value)}
onKeyDown={handleKeyDown}
disabled={isExecuting}
className="w-full bg-transparent border-none outline-none text-white font-mono placeholder-gray-500 caret-white leading-relaxed"
placeholder=""
autoComplete="off"
spellCheck="false"
autoCapitalize="off"
autoCorrect="off"
/>
</form>
</div>
)}
</div>
</ScrollArea>
</div>
</div>
);
}
-12
View File
@@ -1,12 +0,0 @@
import { Terminal } from './Terminal';
/**
* A test component to verify ANSI color code rendering in the terminal
*/
export function TerminalTest() {
return (
<div className="h-[500px] w-full">
<Terminal projectId="test" />
</div>
);
}
+142 -142
View File
@@ -41,29 +41,29 @@ const AddWalletContent = forwardRef<HTMLDivElement, {
setAlias: (value: string) => void; setAlias: (value: string) => void;
connectionUri: string; connectionUri: string;
setConnectionUri: (value: string) => void; setConnectionUri: (value: string) => void;
}>(({ alias, setAlias, connectionUri, setConnectionUri }, ref) => ( }>(({ alias, setAlias, connectionUri, setConnectionUri }, ref) => (
<div className="space-y-4 px-4" ref={ref}> <div className="space-y-4 px-4" ref={ref}>
<div> <div>
<Label htmlFor="alias">Wallet Name (optional)</Label> <Label htmlFor="alias">Wallet Name (optional)</Label>
<Input <Input
id="alias" id="alias"
placeholder="My Lightning Wallet" placeholder="My Lightning Wallet"
value={alias} value={alias}
onChange={(e) => setAlias(e.target.value)} onChange={(e) => setAlias(e.target.value)}
/> />
</div> </div>
<div> <div>
<Label htmlFor="connection-uri">Connection URI</Label> <Label htmlFor="connection-uri">Connection URI</Label>
<Textarea <Textarea
id="connection-uri" id="connection-uri"
placeholder="nostr+walletconnect://..." placeholder="nostr+walletconnect://..."
value={connectionUri} value={connectionUri}
onChange={(e) => setConnectionUri(e.target.value)} onChange={(e) => setConnectionUri(e.target.value)}
rows={3} rows={3}
/> />
</div> </div>
</div> </div>
)); ));
AddWalletContent.displayName = 'AddWalletContent'; AddWalletContent.displayName = 'AddWalletContent';
// Extracted WalletContent to prevent re-renders // Extracted WalletContent to prevent re-renders
@@ -77,132 +77,132 @@ const WalletContent = forwardRef<HTMLDivElement, {
handleSetActive: (cs: string) => void; handleSetActive: (cs: string) => void;
handleRemoveConnection: (cs: string) => void; handleRemoveConnection: (cs: string) => void;
setAddDialogOpen: (open: boolean) => void; setAddDialogOpen: (open: boolean) => void;
}>(({ }>(({
hasWebLN, hasWebLN,
isDetecting, isDetecting,
hasNWC, hasNWC,
connections, connections,
connectionInfo, connectionInfo,
activeConnection, activeConnection,
handleSetActive, handleSetActive,
handleRemoveConnection, handleRemoveConnection,
setAddDialogOpen setAddDialogOpen
}, ref) => ( }, ref) => (
<div className="space-y-6 px-4 pb-4" ref={ref}> <div className="space-y-6 px-4 pb-4" ref={ref}>
{/* Current Status */} {/* Current Status */}
<div className="space-y-3"> <div className="space-y-3">
<h3 className="font-medium">Current Status</h3> <h3 className="font-medium">Current Status</h3>
<div className="grid gap-3"> <div className="grid gap-3">
{/* WebLN */} {/* WebLN */}
<div className="flex items-center justify-between p-3 border rounded-lg"> <div className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<Globe className="h-4 w-4 text-muted-foreground" /> <Globe className="h-4 w-4 text-muted-foreground" />
<div> <div>
<p className="text-sm font-medium">WebLN</p> <p className="text-sm font-medium">WebLN</p>
<p className="text-xs text-muted-foreground">Browser extension</p> <p className="text-xs text-muted-foreground">Browser extension</p>
</div>
</div>
<div className="flex items-center gap-2">
{hasWebLN && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={hasWebLN ? "default" : "secondary"} className="text-xs">
{isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found"}
</Badge>
</div>
</div>
{/* NWC */}
<div className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">Nostr Wallet Connect</p>
<p className="text-xs text-muted-foreground">
{connections.length > 0
? `${connections.length} wallet${connections.length !== 1 ? 's' : ''} connected`
: "Remote wallet connection"
}
</p>
</div>
</div>
<div className="flex items-center gap-2">
{hasNWC && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={hasNWC ? "default" : "secondary"} className="text-xs">
{hasNWC ? "Ready" : "None"}
</Badge>
</div>
</div> </div>
</div> </div>
</div> <div className="flex items-center gap-2">
<Separator /> {hasWebLN && <CheckCircle className="h-4 w-4 text-green-600" />}
{/* NWC Management */} <Badge variant={hasWebLN ? "default" : "secondary"} className="text-xs">
<div className="space-y-4"> {isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found"}
<div className="flex items-center justify-between"> </Badge>
<h3 className="font-medium">Nostr Wallet Connect</h3>
<Button size="sm" variant="outline" onClick={() => setAddDialogOpen(true)}>
<Plus className="h-4 w-4 mr-1" />
Add
</Button>
</div> </div>
{/* Connected Wallets List */}
{connections.length === 0 ? (
<div className="text-center py-6 text-muted-foreground">
<p className="text-sm">No wallets connected</p>
</div>
) : (
<div className="space-y-2">
{connections.map((connection) => {
const info = connectionInfo[connection.connectionString];
const isActive = activeConnection === connection.connectionString;
return (
<div key={connection.connectionString} className={`flex items-center justify-between p-3 border rounded-lg ${isActive ? 'ring-2 ring-primary' : ''}`}>
<div className="flex items-center gap-3">
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">
{connection.alias || info?.alias || 'Lightning Wallet'}
</p>
<p className="text-xs text-muted-foreground">
NWC Connection
</p>
</div>
</div>
<div className="flex items-center gap-2">
{isActive && <CheckCircle className="h-4 w-4 text-green-600" />}
{!isActive && (
<Button
size="sm"
variant="ghost"
onClick={() => handleSetActive(connection.connectionString)}
>
<Zap className="h-3 w-3" />
</Button>
)}
<Button
size="sm"
variant="ghost"
onClick={() => handleRemoveConnection(connection.connectionString)}
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
</div>
);
})}
</div>
)}
</div> </div>
{/* Help */} {/* NWC */}
{!hasWebLN && connections.length === 0 && ( <div className="flex items-center justify-between p-3 border rounded-lg">
<> <div className="flex items-center gap-3">
<Separator /> <WalletMinimal className="h-4 w-4 text-muted-foreground" />
<div className="text-center py-4 space-y-2"> <div>
<p className="text-sm text-muted-foreground"> <p className="text-sm font-medium">Nostr Wallet Connect</p>
Install a WebLN extension or connect a NWC wallet for zaps. <p className="text-xs text-muted-foreground">
{connections.length > 0
? `${connections.length} wallet${connections.length !== 1 ? 's' : ''} connected`
: "Remote wallet connection"
}
</p> </p>
</div> </div>
</> </div>
)} <div className="flex items-center gap-2">
{hasNWC && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={hasNWC ? "default" : "secondary"} className="text-xs">
{hasNWC ? "Ready" : "None"}
</Badge>
</div>
</div>
</div> </div>
)); </div>
<Separator />
{/* NWC Management */}
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="font-medium">Nostr Wallet Connect</h3>
<Button size="sm" variant="outline" onClick={() => setAddDialogOpen(true)}>
<Plus className="h-4 w-4 mr-1" />
Add
</Button>
</div>
{/* Connected Wallets List */}
{connections.length === 0 ? (
<div className="text-center py-6 text-muted-foreground">
<p className="text-sm">No wallets connected</p>
</div>
) : (
<div className="space-y-2">
{connections.map((connection) => {
const info = connectionInfo[connection.connectionString];
const isActive = activeConnection === connection.connectionString;
return (
<div key={connection.connectionString} className={`flex items-center justify-between p-3 border rounded-lg ${isActive ? 'ring-2 ring-primary' : ''}`}>
<div className="flex items-center gap-3">
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">
{connection.alias || info?.alias || 'Lightning Wallet'}
</p>
<p className="text-xs text-muted-foreground">
NWC Connection
</p>
</div>
</div>
<div className="flex items-center gap-2">
{isActive && <CheckCircle className="h-4 w-4 text-green-600" />}
{!isActive && (
<Button
size="sm"
variant="ghost"
onClick={() => handleSetActive(connection.connectionString)}
>
<Zap className="h-3 w-3" />
</Button>
)}
<Button
size="sm"
variant="ghost"
onClick={() => handleRemoveConnection(connection.connectionString)}
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
</div>
);
})}
</div>
)}
</div>
{/* Help */}
{!hasWebLN && connections.length === 0 && (
<>
<Separator />
<div className="text-center py-4 space-y-2">
<p className="text-sm text-muted-foreground">
Install a WebLN extension or connect a NWC wallet for zaps.
</p>
</div>
</>
)}
</div>
));
WalletContent.displayName = 'WalletContent'; WalletContent.displayName = 'WalletContent';
export function WalletModal({ children, className }: WalletModalProps) { export function WalletModal({ children, className }: WalletModalProps) {
+3 -3
View File
@@ -199,9 +199,9 @@ This reverts the codebase back to the state at commit ${targetCommit.oid.substri
Reverted ${commitsToRevert.length} commit(s): Reverted ${commitsToRevert.length} commit(s):
${commitsToRevert.map(c => { ${commitsToRevert.map(c => {
const commitFirstLine = getCommitMessageLines(c.commit.message).firstLine; const commitFirstLine = getCommitMessageLines(c.commit.message).firstLine;
return `- ${c.oid.substring(0, 7)}: ${commitFirstLine}`; return `- ${c.oid.substring(0, 7)}: ${commitFirstLine}`;
}).join('\n')}`; }).join('\n')}`;
await git.commit({ await git.commit({
dir: projectPath, dir: projectPath,
+4 -4
View File
@@ -186,9 +186,9 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
> >
<DialogHeader className={cn('px-6 pt-6 pb-1 relative')}> <DialogHeader className={cn('px-6 pt-6 pb-1 relative')}>
<DialogDescription className="text-center"> <DialogDescription className="text-center">
Sign up or log in to continue Sign up or log in to continue
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-auto flex-1'> <div className='px-6 pt-2 pb-4 space-y-4 overflow-y-auto flex-1'>
{/* Prominent Sign Up Section */} {/* Prominent Sign Up Section */}
@@ -370,7 +370,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
</div> </div>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
); );
}; };
export default LoginDialog; export default LoginDialog;
+35 -35
View File
@@ -505,11 +505,11 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
<div className='grid grid-cols-1 gap-2'> <div className='grid grid-cols-1 gap-2'>
{/* Download Option */} {/* Download Option */}
<Card className={`cursor-pointer transition-all duration-200 ${ <Card className={`cursor-pointer transition-all duration-200 ${
keySecured === 'downloaded' keySecured === 'downloaded'
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20' ? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
: 'hover:bg-primary/5 hover:border-primary/20' : 'hover:bg-primary/5 hover:border-primary/20'
}`}> }`}>
<CardContent className='p-3'> <CardContent className='p-3'>
<Button <Button
variant="ghost" variant="ghost"
@@ -519,39 +519,39 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
<div className='flex items-center gap-3 w-full'> <div className='flex items-center gap-3 w-full'>
<div className={`p-1.5 rounded-lg ${ <div className={`p-1.5 rounded-lg ${
keySecured === 'downloaded' keySecured === 'downloaded'
? 'bg-green-100 dark:bg-green-900' ? 'bg-green-100 dark:bg-green-900'
: 'bg-primary/10' : 'bg-primary/10'
}`}> }`}>
{keySecured === 'downloaded' ? ( {keySecured === 'downloaded' ? (
<CheckCircle className='w-4 h-4 text-green-600' /> <CheckCircle className='w-4 h-4 text-green-600' />
) : ( ) : (
<Download className='w-4 h-4 text-primary' /> <Download className='w-4 h-4 text-primary' />
)} )}
</div> </div>
<div className='flex-1 text-left'> <div className='flex-1 text-left'>
<div className='font-medium text-sm'> <div className='font-medium text-sm'>
Download as File Download as File
</div> </div>
<div className='text-xs text-muted-foreground'> <div className='text-xs text-muted-foreground'>
Save as secret-key.txt file Save as secret-key.txt file
</div> </div>
</div> </div>
{keySecured === 'downloaded' && ( {keySecured === 'downloaded' && (
<div className='text-xs font-medium text-green-600'> <div className='text-xs font-medium text-green-600'>
✓ Downloaded ✓ Downloaded
</div> </div>
)} )}
</div> </div>
</Button> </Button>
</CardContent> </CardContent>
</Card> </Card>
{/* Copy Option */} {/* Copy Option */}
<Card className={`cursor-pointer transition-all duration-200 ${ <Card className={`cursor-pointer transition-all duration-200 ${
keySecured === 'copied' keySecured === 'copied'
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20' ? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
: 'hover:bg-primary/5 hover:border-primary/20' : 'hover:bg-primary/5 hover:border-primary/20'
}`}> }`}>
<CardContent className='p-3'> <CardContent className='p-3'>
<Button <Button
variant="ghost" variant="ghost"
@@ -561,20 +561,20 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
<div className='flex items-center gap-3 w-full'> <div className='flex items-center gap-3 w-full'>
<div className={`p-1.5 rounded-lg ${ <div className={`p-1.5 rounded-lg ${
keySecured === 'copied' keySecured === 'copied'
? 'bg-green-100 dark:bg-green-900' ? 'bg-green-100 dark:bg-green-900'
: 'bg-primary/10' : 'bg-primary/10'
}`}> }`}>
{keySecured === 'copied' ? ( {keySecured === 'copied' ? (
<CheckCircle className='w-4 h-4 text-green-600' /> <CheckCircle className='w-4 h-4 text-green-600' />
) : ( ) : (
<Copy className='w-4 h-4 text-primary' /> <Copy className='w-4 h-4 text-primary' />
)} )}
</div> </div>
<div className='flex-1 text-left'> <div className='flex-1 text-left'>
<div className='font-medium text-sm'> <div className='font-medium text-sm'>
Copy to Clipboard Copy to Clipboard
</div> </div>
<div className='text-xs text-muted-foreground'> <div className='text-xs text-muted-foreground'>
Save to password manager Save to password manager
</div> </div>
<div className='text-[.7rem] text-muted-foreground'> <div className='text-[.7rem] text-muted-foreground'>
@@ -582,10 +582,10 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
</div> </div>
</div> </div>
{keySecured === 'copied' && ( {keySecured === 'copied' && (
<div className='text-xs font-medium text-green-600'> <div className='text-xs font-medium text-green-600'>
✓ Copied ✓ Copied
</div> </div>
)} )}
</div> </div>
</Button> </Button>
</CardContent> </CardContent>
+24 -88
View File
@@ -1,5 +1,5 @@
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect } from 'react';
import { Cloud, Upload } from 'lucide-react'; import { Cloud } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
@@ -32,7 +32,6 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
}) => { }) => {
// Removed step state - we only have one step now // Removed step state - we only have one step now
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [isFileLoading, setIsFileLoading] = useState(false);
const [nsec, setNsec] = useState(''); const [nsec, setNsec] = useState('');
const [bunkerUri, setBunkerUri] = useState(''); const [bunkerUri, setBunkerUri] = useState('');
const [activeTab, setActiveTab] = useState<'nsec' | 'bunker'>('nsec'); const [activeTab, setActiveTab] = useState<'nsec' | 'bunker'>('nsec');
@@ -40,9 +39,7 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
nsec?: string; nsec?: string;
bunker?: string; bunker?: string;
extension?: string; extension?: string;
file?: string;
}>({}); }>({});
const fileInputRef = useRef<HTMLInputElement>(null);
const login = useLoginActions(); const login = useLoginActions();
@@ -50,15 +47,10 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
useEffect(() => { useEffect(() => {
if (isOpen) { if (isOpen) {
setIsLoading(false); setIsLoading(false);
setIsFileLoading(false);
setNsec(''); setNsec('');
setBunkerUri(''); setBunkerUri('');
setActiveTab('nsec'); setActiveTab('nsec');
setErrors({}); setErrors({});
// Reset file input
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
} }
}, [isOpen]); }, [isOpen]);
@@ -94,7 +86,20 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' })); setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
return; return;
} }
executeLogin(nsec);
setIsLoading(true);
setErrors({});
setTimeout(() => {
try {
login.nsec(nsec);
onLogin();
onClose();
} catch {
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
setIsLoading(false);
}
}, 50);
}; };
const handleBunkerLogin = async () => { const handleBunkerLogin = async () => {
@@ -126,52 +131,6 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
} }
}; };
const executeLogin = (key: string) => {
setIsLoading(true);
setErrors({});
// Use a timeout to allow the UI to update before the synchronous login call
setTimeout(() => {
try {
login.nsec(key);
onLogin();
onClose();
} catch {
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
setIsLoading(false);
}
}, 50);
};
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setIsFileLoading(true);
setErrors({});
const reader = new FileReader();
reader.onload = (event) => {
setIsFileLoading(false);
const content = event.target?.result as string;
if (content) {
const trimmedContent = content.trim();
if (validateNsec(trimmedContent)) {
executeLogin(trimmedContent);
} else {
setErrors({ file: 'File does not contain a valid secret key.' });
}
} else {
setErrors({ file: 'Could not read file content.' });
}
};
reader.onerror = () => {
setIsFileLoading(false);
setErrors({ file: 'Failed to read file.' });
};
reader.readAsText(file);
};
const handleSignupClick = () => { const handleSignupClick = () => {
onClose(); onClose();
if (onSignup) { if (onSignup) {
@@ -243,37 +202,14 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
)} )}
</div> </div>
<div className="flex space-x-2"> <Button
<Button size="lg"
size="lg" onClick={handleKeyLogin}
onClick={handleKeyLogin} disabled={isLoading || !nsec.trim()}
disabled={isLoading || !nsec.trim()} className="w-full"
className="flex-1" >
> {isLoading ? 'Verifying...' : 'Add Key'}
{isLoading ? 'Verifying...' : 'Add Key'} </Button>
</Button>
<input
type="file"
accept=".txt"
className="hidden"
ref={fileInputRef}
onChange={handleFileUpload}
/>
<Button
variant="outline"
size="lg"
onClick={() => fileInputRef.current?.click()}
disabled={isLoading || isFileLoading}
className="px-3"
>
<Upload className="w-4 h-4" />
</Button>
</div>
{errors.file && (
<p className="text-sm text-red-500 text-center">{errors.file}</p>
)}
</div> </div>
)} )}
+42 -42
View File
@@ -1,63 +1,63 @@
import React from 'react'; import React from 'react';
interface QuillySVGProps extends React.SVGProps<SVGSVGElement> { interface QuillySVGProps extends React.SVGProps<SVGSVGElement> {
className?: string; className?: string;
fillColor?: string; fillColor?: string;
} }
export function QuillySVG({ className = "w-4 h-4", fillColor = "currentColor", ...props }: QuillySVGProps) { export function QuillySVG({ className = "w-4 h-4", fillColor = "currentColor", ...props }: QuillySVGProps) {
return ( return (
<svg <svg
className={className} className={className}
viewBox="140 30 220 420" viewBox="140 30 220 420"
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
{...props} {...props}
> >
{/* Main quill head/top part */} {/* Main quill head/top part */}
<path fill={fillColor} d="M 241.5,33.5 C 246.833,33.5 252.167,33.5 257.5,33.5C 269.508,34.507 280.508,38.3403 290.5,45C 294,47.3342 297,50.1675 299.5,53.5C 298.21,54.0577 297.377,55.0577 297,56.5C 294.888,52.8729 293.221,52.8729 292,56.5C 291.086,55.3463 290.253,55.513 289.5,57C 292.321,58.6213 292.987,60.788 291.5,63.5C 281.078,49.3135 266.911,42.3135 249,42.5C 229.512,42.5414 213.845,50.2081 202,65.5C 196.198,75.0401 193.698,85.3734 194.5,96.5C 193.546,91.1876 192.546,85.1876 191.5,78.5C 189.508,78.6715 187.842,78.0049 186.5,76.5C 183.867,77.7822 183.867,79.1156 186.5,80.5C 185.234,81.3624 183.901,82.0291 182.5,82.5C 183.047,79.2976 184.047,76.2976 185.5,73.5C 186.906,73.0269 187.573,72.0269 187.5,70.5C 188.498,66.4945 190.498,63.1612 193.5,60.5C 194.906,60.0269 195.573,59.0269 195.5,57.5C 196.833,55.8333 198.167,54.1667 199.5,52.5C 211.392,41.6322 225.392,35.2989 241.5,33.5 Z" /> <path fill={fillColor} d="M 241.5,33.5 C 246.833,33.5 252.167,33.5 257.5,33.5C 269.508,34.507 280.508,38.3403 290.5,45C 294,47.3342 297,50.1675 299.5,53.5C 298.21,54.0577 297.377,55.0577 297,56.5C 294.888,52.8729 293.221,52.8729 292,56.5C 291.086,55.3463 290.253,55.513 289.5,57C 292.321,58.6213 292.987,60.788 291.5,63.5C 281.078,49.3135 266.911,42.3135 249,42.5C 229.512,42.5414 213.845,50.2081 202,65.5C 196.198,75.0401 193.698,85.3734 194.5,96.5C 193.546,91.1876 192.546,85.1876 191.5,78.5C 189.508,78.6715 187.842,78.0049 186.5,76.5C 183.867,77.7822 183.867,79.1156 186.5,80.5C 185.234,81.3624 183.901,82.0291 182.5,82.5C 183.047,79.2976 184.047,76.2976 185.5,73.5C 186.906,73.0269 187.573,72.0269 187.5,70.5C 188.498,66.4945 190.498,63.1612 193.5,60.5C 194.906,60.0269 195.573,59.0269 195.5,57.5C 196.833,55.8333 198.167,54.1667 199.5,52.5C 211.392,41.6322 225.392,35.2989 241.5,33.5 Z" />
{/* Main quill feather/plume part */} {/* Main quill feather/plume part */}
<path fill={fillColor} d="M 299.5,53.5 C 305.302,58.4362 309.635,64.4362 312.5,71.5C 312.343,72.8734 312.51,74.2068 313,75.5C 313.876,77.7582 315.043,79.7582 316.5,81.5C 318.737,87.0285 320.903,92.6952 323,98.5C 328.732,104.725 334.232,111.058 339.5,117.5C 339.427,119.027 340.094,120.027 341.5,120.5C 343.293,122.426 344.293,124.759 344.5,127.5C 345.22,133.138 345.553,138.804 345.5,144.5C 344.999,150.505 342.499,155.505 338,159.5C 338.33,165.569 338.164,171.569 337.5,177.5C 336.732,178.263 336.232,179.263 336,180.5C 335.261,178.779 334.427,177.113 333.5,175.5C 333.034,177.705 333.034,179.705 333.5,181.5C 332.23,180.438 331.063,179.438 330,178.5C 329.667,178.833 329.333,179.167 329,179.5C 328.333,178.5 328.333,177.5 329,176.5C 329.718,177.451 330.551,177.617 331.5,177C 330.418,175.67 329.751,174.17 329.5,172.5C 329.799,170.396 329.466,168.396 328.5,166.5C 317.499,170.764 306.666,170.431 296,165.5C 295.617,166.056 295.117,166.389 294.5,166.5C 293.533,167.806 292.199,168.473 290.5,168.5C 290.688,170.103 290.188,171.437 289,172.5C 287.477,170.431 286.643,168.097 286.5,165.5C 287.351,161.435 288.517,157.435 290,153.5C 293.306,151.968 296.806,150.801 300.5,150C 303.708,147.229 305.708,143.729 306.5,139.5C 305.527,137.36 304.027,135.693 302,134.5C 299.684,135.367 297.684,134.701 296,132.5C 293.685,129.223 292.351,125.556 292,121.5C 292.692,108.983 293.858,96.4825 295.5,84C 295.554,78.7227 294.887,73.556 293.5,68.5C 293.771,66.6203 293.104,65.287 291.5,64.5C 291.5,64.1667 291.5,63.8333 291.5,63.5C 292.987,60.788 292.321,58.6213 289.5,57C 290.253,55.513 291.086,55.3463 292,56.5C 293.221,52.8729 294.888,52.8729 297,56.5C 297.377,55.0577 298.21,54.0577 299.5,53.5 Z" /> <path fill={fillColor} d="M 299.5,53.5 C 305.302,58.4362 309.635,64.4362 312.5,71.5C 312.343,72.8734 312.51,74.2068 313,75.5C 313.876,77.7582 315.043,79.7582 316.5,81.5C 318.737,87.0285 320.903,92.6952 323,98.5C 328.732,104.725 334.232,111.058 339.5,117.5C 339.427,119.027 340.094,120.027 341.5,120.5C 343.293,122.426 344.293,124.759 344.5,127.5C 345.22,133.138 345.553,138.804 345.5,144.5C 344.999,150.505 342.499,155.505 338,159.5C 338.33,165.569 338.164,171.569 337.5,177.5C 336.732,178.263 336.232,179.263 336,180.5C 335.261,178.779 334.427,177.113 333.5,175.5C 333.034,177.705 333.034,179.705 333.5,181.5C 332.23,180.438 331.063,179.438 330,178.5C 329.667,178.833 329.333,179.167 329,179.5C 328.333,178.5 328.333,177.5 329,176.5C 329.718,177.451 330.551,177.617 331.5,177C 330.418,175.67 329.751,174.17 329.5,172.5C 329.799,170.396 329.466,168.396 328.5,166.5C 317.499,170.764 306.666,170.431 296,165.5C 295.617,166.056 295.117,166.389 294.5,166.5C 293.533,167.806 292.199,168.473 290.5,168.5C 290.688,170.103 290.188,171.437 289,172.5C 287.477,170.431 286.643,168.097 286.5,165.5C 287.351,161.435 288.517,157.435 290,153.5C 293.306,151.968 296.806,150.801 300.5,150C 303.708,147.229 305.708,143.729 306.5,139.5C 305.527,137.36 304.027,135.693 302,134.5C 299.684,135.367 297.684,134.701 296,132.5C 293.685,129.223 292.351,125.556 292,121.5C 292.692,108.983 293.858,96.4825 295.5,84C 295.554,78.7227 294.887,73.556 293.5,68.5C 293.771,66.6203 293.104,65.287 291.5,64.5C 291.5,64.1667 291.5,63.8333 291.5,63.5C 292.987,60.788 292.321,58.6213 289.5,57C 290.253,55.513 291.086,55.3463 292,56.5C 293.221,52.8729 294.888,52.8729 297,56.5C 297.377,55.0577 298.21,54.0577 299.5,53.5 Z" />
{/* Body/torso part */} {/* Body/torso part */}
<path fill={fillColor} d="M 194.5,96.5 C 205.307,90.5958 215.64,91.2624 225.5,98.5C 227.97,102.11 229.304,106.11 229.5,110.5C 227.359,120.522 224.859,130.522 222,140.5C 221.176,143.882 221.343,147.216 222.5,150.5C 223.607,151.022 224.774,151.355 226,151.5C 229.926,150.727 233.759,149.727 237.5,148.5C 240.135,147.461 242.135,145.794 243.5,143.5C 247.778,147.659 247.111,151.159 241.5,154C 245.303,156.071 248.97,158.404 252.5,161C 255.77,162.66 259.103,162.994 262.5,162C 263.935,164.267 263.602,166.267 261.5,168C 258.448,169.211 255.281,170.045 252,170.5C 244.065,169.521 236.398,167.521 229,164.5C 222.843,167.108 216.51,169.108 210,170.5C 207.815,170.079 205.649,169.579 203.5,169C 202.424,167.274 202.257,165.441 203,163.5C 207.408,161.43 211.575,158.93 215.5,156C 213.504,151.729 213.004,147.229 214,142.5C 216.819,132.558 219.319,122.558 221.5,112.5C 221.81,108.306 220.143,105.139 216.5,103C 208.667,100.569 201.501,101.736 195,106.5C 191.661,123.896 191.827,141.229 195.5,158.5C 194.895,160.026 193.729,161.026 192,161.5C 191.14,156.863 188.307,154.697 183.5,155C 184.833,154.333 184.833,153.667 183.5,153C 181.934,152.7 180.601,153.2 179.5,154.5C 166.076,151.07 158.742,142.403 157.5,128.5C 158.051,123.851 159.385,119.518 161.5,115.5C 162.906,115.027 163.573,114.027 163.5,112.5C 167.455,107.373 171.622,102.373 176,97.5C 178.486,92.5113 180.652,87.5113 182.5,82.5C 183.901,82.0291 185.234,81.3624 186.5,80.5C 183.867,79.1156 183.867,77.7822 186.5,76.5C 187.842,78.0049 189.508,78.6715 191.5,78.5C 192.546,85.1876 193.546,91.1876 194.5,96.5 Z" /> <path fill={fillColor} d="M 194.5,96.5 C 205.307,90.5958 215.64,91.2624 225.5,98.5C 227.97,102.11 229.304,106.11 229.5,110.5C 227.359,120.522 224.859,130.522 222,140.5C 221.176,143.882 221.343,147.216 222.5,150.5C 223.607,151.022 224.774,151.355 226,151.5C 229.926,150.727 233.759,149.727 237.5,148.5C 240.135,147.461 242.135,145.794 243.5,143.5C 247.778,147.659 247.111,151.159 241.5,154C 245.303,156.071 248.97,158.404 252.5,161C 255.77,162.66 259.103,162.994 262.5,162C 263.935,164.267 263.602,166.267 261.5,168C 258.448,169.211 255.281,170.045 252,170.5C 244.065,169.521 236.398,167.521 229,164.5C 222.843,167.108 216.51,169.108 210,170.5C 207.815,170.079 205.649,169.579 203.5,169C 202.424,167.274 202.257,165.441 203,163.5C 207.408,161.43 211.575,158.93 215.5,156C 213.504,151.729 213.004,147.229 214,142.5C 216.819,132.558 219.319,122.558 221.5,112.5C 221.81,108.306 220.143,105.139 216.5,103C 208.667,100.569 201.501,101.736 195,106.5C 191.661,123.896 191.827,141.229 195.5,158.5C 194.895,160.026 193.729,161.026 192,161.5C 191.14,156.863 188.307,154.697 183.5,155C 184.833,154.333 184.833,153.667 183.5,153C 181.934,152.7 180.601,153.2 179.5,154.5C 166.076,151.07 158.742,142.403 157.5,128.5C 158.051,123.851 159.385,119.518 161.5,115.5C 162.906,115.027 163.573,114.027 163.5,112.5C 167.455,107.373 171.622,102.373 176,97.5C 178.486,92.5113 180.652,87.5113 182.5,82.5C 183.901,82.0291 185.234,81.3624 186.5,80.5C 183.867,79.1156 183.867,77.7822 186.5,76.5C 187.842,78.0049 189.508,78.6715 191.5,78.5C 192.546,85.1876 193.546,91.1876 194.5,96.5 Z" />
{/* Additional body details */} {/* Additional body details */}
<path fill={fillColor} d="M 272.5,96.5 C 273.785,98.4516 275.451,100.118 277.5,101.5C 279.574,103.715 279.907,106.215 278.5,109C 275.758,109.295 273.425,108.462 271.5,106.5C 271.167,105.5 270.5,104.833 269.5,104.5C 265.505,102.79 261.339,101.456 257,100.5C 252.701,101.544 248.535,102.878 244.5,104.5C 237.97,101.229 237.97,97.7288 244.5,94C 251.789,91.6687 259.122,91.3353 266.5,93C 268.727,93.941 270.727,95.1077 272.5,96.5 Z" /> <path fill={fillColor} d="M 272.5,96.5 C 273.785,98.4516 275.451,100.118 277.5,101.5C 279.574,103.715 279.907,106.215 278.5,109C 275.758,109.295 273.425,108.462 271.5,106.5C 271.167,105.5 270.5,104.833 269.5,104.5C 265.505,102.79 261.339,101.456 257,100.5C 252.701,101.544 248.535,102.878 244.5,104.5C 237.97,101.229 237.97,97.7288 244.5,94C 251.789,91.6687 259.122,91.3353 266.5,93C 268.727,93.941 270.727,95.1077 272.5,96.5 Z" />
{/* Eyes */} {/* Eyes */}
<path fill={fillColor} d="M 216.5,118.5 C 215.603,119.598 214.77,119.598 214,118.5C 213.59,119.901 213.09,121.234 212.5,122.5C 209.43,122.632 206.43,122.299 203.5,121.5C 200.197,118.335 199.697,114.668 202,110.5C 209.746,105.174 214.913,107.008 217.5,116C 217.257,116.902 216.923,117.735 216.5,118.5 Z" /> <path fill={fillColor} d="M 216.5,118.5 C 215.603,119.598 214.77,119.598 214,118.5C 213.59,119.901 213.09,121.234 212.5,122.5C 209.43,122.632 206.43,122.299 203.5,121.5C 200.197,118.335 199.697,114.668 202,110.5C 209.746,105.174 214.913,107.008 217.5,116C 217.257,116.902 216.923,117.735 216.5,118.5 Z" />
<path fill={fillColor} d="M 254.5,107.5 C 262.982,107.765 266.149,112.099 264,120.5C 258.514,126.08 253.514,125.747 249,119.5C 247.486,113.877 249.319,109.877 254.5,107.5 Z" /> <path fill={fillColor} d="M 254.5,107.5 C 262.982,107.765 266.149,112.099 264,120.5C 258.514,126.08 253.514,125.747 249,119.5C 247.486,113.877 249.319,109.877 254.5,107.5 Z" />
{/* Extended body details */} {/* Extended body details */}
<path fill={fillColor} d="M 329.5,172.5 C 329.751,174.17 330.418,175.67 331.5,177C 330.551,177.617 329.718,177.451 329,176.5C 328.333,177.5 328.333,178.5 329,179.5C 329.333,179.167 329.667,178.833 330,178.5C 331.063,179.438 332.23,180.438 333.5,181.5C 333.034,179.705 333.034,177.705 333.5,175.5C 334.427,177.113 335.261,178.779 336,180.5C 336.232,179.263 336.732,178.263 337.5,177.5C 337.657,178.873 337.49,180.207 337,181.5C 336.124,183.758 334.957,185.758 333.5,187.5C 331.455,188.923 330.455,190.923 330.5,193.5C 321.603,207.727 311.937,221.394 301.5,234.5C 301.785,232.712 301.452,231.045 300.5,229.5C 297.606,230.909 296.606,230.242 297.5,227.5C 298.167,225.833 298.833,224.167 299.5,222.5C 306.66,212.186 313.827,201.853 321,191.5C 324.438,185.303 327.271,178.969 329.5,172.5 Z" /> <path fill={fillColor} d="M 329.5,172.5 C 329.751,174.17 330.418,175.67 331.5,177C 330.551,177.617 329.718,177.451 329,176.5C 328.333,177.5 328.333,178.5 329,179.5C 329.333,179.167 329.667,178.833 330,178.5C 331.063,179.438 332.23,180.438 333.5,181.5C 333.034,179.705 333.034,177.705 333.5,175.5C 334.427,177.113 335.261,178.779 336,180.5C 336.232,179.263 336.732,178.263 337.5,177.5C 337.657,178.873 337.49,180.207 337,181.5C 336.124,183.758 334.957,185.758 333.5,187.5C 331.455,188.923 330.455,190.923 330.5,193.5C 321.603,207.727 311.937,221.394 301.5,234.5C 301.785,232.712 301.452,231.045 300.5,229.5C 297.606,230.909 296.606,230.242 297.5,227.5C 298.167,225.833 298.833,224.167 299.5,222.5C 306.66,212.186 313.827,201.853 321,191.5C 324.438,185.303 327.271,178.969 329.5,172.5 Z" />
{/* Main body section */} {/* Main body section */}
<path fill={fillColor} d="M 195.5,158.5 C 199.127,167.099 202.794,175.765 206.5,184.5C 206.427,186.027 207.094,187.027 208.5,187.5C 213.391,196.567 220.558,202.9 230,206.5C 254.97,200.996 273.803,187.329 286.5,165.5C 286.643,168.097 287.477,170.431 289,172.5C 290.188,171.437 290.688,170.103 290.5,168.5C 292.199,168.473 293.533,167.806 294.5,166.5C 290.454,177.733 283.787,187.233 274.5,195C 259.369,206.946 243.036,214.112 225.5,216.5C 222.868,215.466 220.201,214.466 217.5,213.5C 217.5,212.833 217.5,212.167 217.5,211.5C 211.822,206.986 206.989,201.653 203,195.5C 198.434,187.483 194.434,179.15 191,170.5C 175.85,181.982 164.684,196.482 157.5,214C 164.095,213.183 170.762,212.683 177.5,212.5C 174.695,213.319 171.695,213.819 168.5,214C 170.167,214.333 171.833,214.667 173.5,215C 171.136,216.012 169.802,217.345 169.5,219C 170.448,219.483 171.448,219.649 172.5,219.5C 172.5,219.833 172.5,220.167 172.5,220.5C 164.95,221.221 157.617,222.888 150.5,225.5C 148.06,224.726 146.727,223.06 146.5,220.5C 146.886,218.068 147.553,215.734 148.5,213.5C 149.906,213.027 150.573,212.027 150.5,210.5C 153.084,202.664 156.751,195.331 161.5,188.5C 169.649,178.517 178.649,169.351 188.5,161C 187.62,159.644 187.286,158.144 187.5,156.5C 184.505,156.706 181.838,156.04 179.5,154.5C 180.601,153.2 181.934,152.7 183.5,153C 184.833,153.667 184.833,154.333 183.5,155C 188.307,154.697 191.14,156.863 192,161.5C 193.729,161.026 194.895,160.026 195.5,158.5 Z M 217.5,211.5 C 216.221,212.968 214.554,213.635 212.5,213.5C 211.167,213.5 209.833,213.5 208.5,213.5C 202.225,212.066 195.725,211.4 189,211.5C 184.985,211.501 181.151,211.835 177.5,212.5C 170.762,212.683 164.095,213.183 157.5,214C 164.684,196.482 175.85,181.982 191,170.5C 194.434,179.15 198.434,187.483 203,195.5C 206.989,201.653 211.822,206.986 217.5,211.5 Z" /> <path fill={fillColor} d="M 195.5,158.5 C 199.127,167.099 202.794,175.765 206.5,184.5C 206.427,186.027 207.094,187.027 208.5,187.5C 213.391,196.567 220.558,202.9 230,206.5C 254.97,200.996 273.803,187.329 286.5,165.5C 286.643,168.097 287.477,170.431 289,172.5C 290.188,171.437 290.688,170.103 290.5,168.5C 292.199,168.473 293.533,167.806 294.5,166.5C 290.454,177.733 283.787,187.233 274.5,195C 259.369,206.946 243.036,214.112 225.5,216.5C 222.868,215.466 220.201,214.466 217.5,213.5C 217.5,212.833 217.5,212.167 217.5,211.5C 211.822,206.986 206.989,201.653 203,195.5C 198.434,187.483 194.434,179.15 191,170.5C 175.85,181.982 164.684,196.482 157.5,214C 164.095,213.183 170.762,212.683 177.5,212.5C 174.695,213.319 171.695,213.819 168.5,214C 170.167,214.333 171.833,214.667 173.5,215C 171.136,216.012 169.802,217.345 169.5,219C 170.448,219.483 171.448,219.649 172.5,219.5C 172.5,219.833 172.5,220.167 172.5,220.5C 164.95,221.221 157.617,222.888 150.5,225.5C 148.06,224.726 146.727,223.06 146.5,220.5C 146.886,218.068 147.553,215.734 148.5,213.5C 149.906,213.027 150.573,212.027 150.5,210.5C 153.084,202.664 156.751,195.331 161.5,188.5C 169.649,178.517 178.649,169.351 188.5,161C 187.62,159.644 187.286,158.144 187.5,156.5C 184.505,156.706 181.838,156.04 179.5,154.5C 180.601,153.2 181.934,152.7 183.5,153C 184.833,153.667 184.833,154.333 183.5,155C 188.307,154.697 191.14,156.863 192,161.5C 193.729,161.026 194.895,160.026 195.5,158.5 Z M 217.5,211.5 C 216.221,212.968 214.554,213.635 212.5,213.5C 211.167,213.5 209.833,213.5 208.5,213.5C 202.225,212.066 195.725,211.4 189,211.5C 184.985,211.501 181.151,211.835 177.5,212.5C 170.762,212.683 164.095,213.183 157.5,214C 164.684,196.482 175.85,181.982 191,170.5C 194.434,179.15 198.434,187.483 203,195.5C 206.989,201.653 211.822,206.986 217.5,211.5 Z" />
{/* Additional body details */} {/* Additional body details */}
<path fill={fillColor} d="M 221.5,184.5 C 224.113,183.565 226.779,183.398 229.5,184C 227.709,184.415 226.376,185.415 225.5,187C 228.167,187.667 230.833,187.667 233.5,187C 230.983,183.799 231.483,180.966 235,178.5C 235.667,177.167 235.667,175.833 235,174.5C 232.323,172.959 229.49,171.959 226.5,171.5C 232.176,171.072 237.843,170.905 243.5,171C 245.283,172.067 245.783,173.567 245,175.5C 243.247,176.627 241.413,177.627 239.5,178.5C 238.303,181.934 236.636,185.1 234.5,188C 231.167,188.667 227.833,188.667 224.5,188C 223.29,186.961 222.29,185.794 221.5,184.5 Z" /> <path fill={fillColor} d="M 221.5,184.5 C 224.113,183.565 226.779,183.398 229.5,184C 227.709,184.415 226.376,185.415 225.5,187C 228.167,187.667 230.833,187.667 233.5,187C 230.983,183.799 231.483,180.966 235,178.5C 235.667,177.167 235.667,175.833 235,174.5C 232.323,172.959 229.49,171.959 226.5,171.5C 232.176,171.072 237.843,170.905 243.5,171C 245.283,172.067 245.783,173.567 245,175.5C 243.247,176.627 241.413,177.627 239.5,178.5C 238.303,181.934 236.636,185.1 234.5,188C 231.167,188.667 227.833,188.667 224.5,188C 223.29,186.961 222.29,185.794 221.5,184.5 Z" />
{/* Body shading */} {/* Body shading */}
<path fill={fillColor} d="M 226.5,171.5 C 229.49,171.959 232.323,172.959 235,174.5C 235.667,175.833 235.667,177.167 235,178.5C 231.483,180.966 230.983,183.799 233.5,187C 230.833,187.667 228.167,187.667 225.5,187C 226.376,185.415 227.709,184.415 229.5,184C 226.779,183.398 224.113,183.565 221.5,184.5C 221.5,183.833 221.5,183.167 221.5,182.5C 221.656,179.934 221.322,177.434 220.5,175C 220.905,174.055 221.572,173.388 222.5,173C 221.5,172.667 220.5,172.333 219.5,172C 221.81,171.503 224.143,171.337 226.5,171.5 Z" /> <path fill={fillColor} d="M 226.5,171.5 C 229.49,171.959 232.323,172.959 235,174.5C 235.667,175.833 235.667,177.167 235,178.5C 231.483,180.966 230.983,183.799 233.5,187C 230.833,187.667 228.167,187.667 225.5,187C 226.376,185.415 227.709,184.415 229.5,184C 226.779,183.398 224.113,183.565 221.5,184.5C 221.5,183.833 221.5,183.167 221.5,182.5C 221.656,179.934 221.322,177.434 220.5,175C 220.905,174.055 221.572,173.388 222.5,173C 221.5,172.667 220.5,172.333 219.5,172C 221.81,171.503 224.143,171.337 226.5,171.5 Z" />
{/* More body shading */} {/* More body shading */}
<path fill={fillColor} d="M 226.5,171.5 C 224.143,171.337 221.81,171.503 219.5,172C 220.5,172.333 221.5,172.667 222.5,173C 221.572,173.388 220.905,174.055 220.5,175C 221.322,177.434 221.656,179.934 221.5,182.5C 220.916,180.257 219.75,178.257 218,176.5C 217.333,174.833 217.333,173.167 218,171.5C 220.937,170.183 223.77,170.183 226.5,171.5 Z" /> <path fill={fillColor} d="M 226.5,171.5 C 224.143,171.337 221.81,171.503 219.5,172C 220.5,172.333 221.5,172.667 222.5,173C 221.572,173.388 220.905,174.055 220.5,175C 221.322,177.434 221.656,179.934 221.5,182.5C 220.916,180.257 219.75,178.257 218,176.5C 217.333,174.833 217.333,173.167 218,171.5C 220.937,170.183 223.77,170.183 226.5,171.5 Z" />
{/* Lower body/legs area */} {/* Lower body/legs area */}
<path fill={fillColor} d="M 177.5,212.5 C 187.85,212.44 198.183,212.774 208.5,213.5C 209.833,213.5 211.167,213.5 212.5,213.5C 214.167,214.833 215.833,214.833 217.5,213.5C 220.201,214.466 222.868,215.466 225.5,216.5C 225.034,218.201 225.034,219.701 225.5,221C 224.429,221.852 223.429,222.685 222.5,223.5C 219.43,223.632 216.43,223.299 213.5,222.5C 213.44,221.957 213.107,221.624 212.5,221.5C 211.516,224.428 211.183,227.428 211.5,230.5C 209.859,228.797 208.859,226.63 208.5,224C 207.258,223.689 206.258,224.189 205.5,225.5C 204.692,225.192 204.025,224.692 203.5,224C 204.833,222.667 204.833,221.333 203.5,220C 201.866,219.506 200.199,219.34 198.5,219.5C 195.102,219.18 191.768,219.513 188.5,220.5C 188.624,221.107 188.957,221.44 189.5,221.5C 188.891,224.878 190.224,226.878 193.5,227.5C 195.288,228.622 197.288,228.789 199.5,228C 200.756,227.583 201.423,226.75 201.5,225.5C 202.995,225.415 203.995,226.081 204.5,227.5C 203.092,228.243 201.759,229.077 200.5,230C 202.249,232.213 204.249,233.213 206.5,233C 204.881,233.236 203.881,234.069 203.5,235.5C 202.5,235.5 201.5,235.5 200.5,235.5C 198.167,235.5 195.833,235.5 193.5,235.5C 193.333,285.168 193.5,334.834 194,384.5C 194.232,385.737 194.732,386.737 195.5,387.5C 197.821,396.471 201.488,404.805 206.5,412.5C 207.956,415.431 207.123,416.098 204,414.5C 203.333,416.167 203.333,417.833 204,419.5C 204.333,418.833 204.667,418.167 205,417.5C 206.109,420.947 205.109,423.614 202,425.5C 200.086,424.324 200.252,423.324 202.5,422.5C 202.167,422.167 201.833,421.833 201.5,421.5C 199.557,421.535 197.557,421.202 195.5,420.5C 186.876,409.404 181.876,396.738 180.5,382.5C 180.5,328.167 180.5,273.833 180.5,219.5C 177.833,219.5 175.167,219.5 172.5,219.5C 171.448,219.649 170.448,219.483 169.5,219C 169.802,217.345 171.136,216.012 173.5,215C 171.833,214.667 170.167,214.333 168.5,214C 171.695,213.819 174.695,213.319 177.5,212.5 Z M 189.5,221.5 C 192.287,220.523 195.287,220.19 198.5,220.5C 203.5,220.134 204.5,221.8 201.5,225.5C 199.087,227.051 196.421,227.717 193.5,227.5C 191.71,225.728 190.377,223.728 189.5,221.5 Z" /> <path fill={fillColor} d="M 177.5,212.5 C 187.85,212.44 198.183,212.774 208.5,213.5C 209.833,213.5 211.167,213.5 212.5,213.5C 214.167,214.833 215.833,214.833 217.5,213.5C 220.201,214.466 222.868,215.466 225.5,216.5C 225.034,218.201 225.034,219.701 225.5,221C 224.429,221.852 223.429,222.685 222.5,223.5C 219.43,223.632 216.43,223.299 213.5,222.5C 213.44,221.957 213.107,221.624 212.5,221.5C 211.516,224.428 211.183,227.428 211.5,230.5C 209.859,228.797 208.859,226.63 208.5,224C 207.258,223.689 206.258,224.189 205.5,225.5C 204.692,225.192 204.025,224.692 203.5,224C 204.833,222.667 204.833,221.333 203.5,220C 201.866,219.506 200.199,219.34 198.5,219.5C 195.102,219.18 191.768,219.513 188.5,220.5C 188.624,221.107 188.957,221.44 189.5,221.5C 188.891,224.878 190.224,226.878 193.5,227.5C 195.288,228.622 197.288,228.789 199.5,228C 200.756,227.583 201.423,226.75 201.5,225.5C 202.995,225.415 203.995,226.081 204.5,227.5C 203.092,228.243 201.759,229.077 200.5,230C 202.249,232.213 204.249,233.213 206.5,233C 204.881,233.236 203.881,234.069 203.5,235.5C 202.5,235.5 201.5,235.5 200.5,235.5C 198.167,235.5 195.833,235.5 193.5,235.5C 193.333,285.168 193.5,334.834 194,384.5C 194.232,385.737 194.732,386.737 195.5,387.5C 197.821,396.471 201.488,404.805 206.5,412.5C 207.956,415.431 207.123,416.098 204,414.5C 203.333,416.167 203.333,417.833 204,419.5C 204.333,418.833 204.667,418.167 205,417.5C 206.109,420.947 205.109,423.614 202,425.5C 200.086,424.324 200.252,423.324 202.5,422.5C 202.167,422.167 201.833,421.833 201.5,421.5C 199.557,421.535 197.557,421.202 195.5,420.5C 186.876,409.404 181.876,396.738 180.5,382.5C 180.5,328.167 180.5,273.833 180.5,219.5C 177.833,219.5 175.167,219.5 172.5,219.5C 171.448,219.649 170.448,219.483 169.5,219C 169.802,217.345 171.136,216.012 173.5,215C 171.833,214.667 170.167,214.333 168.5,214C 171.695,213.819 174.695,213.319 177.5,212.5 Z M 189.5,221.5 C 192.287,220.523 195.287,220.19 198.5,220.5C 203.5,220.134 204.5,221.8 201.5,225.5C 199.087,227.051 196.421,227.717 193.5,227.5C 191.71,225.728 190.377,223.728 189.5,221.5 Z" />
{/* Extended body section */} {/* Extended body section */}
<path fill={fillColor} d="M 225.5,216.5 C 247.583,219.231 268.249,225.898 287.5,236.5C 289.507,234.467 291.507,232.467 293.5,230.5C 294.906,230.027 295.573,229.027 295.5,227.5C 296.167,227.5 296.833,227.5 297.5,227.5C 296.606,230.242 297.606,230.909 300.5,229.5C 301.452,231.045 301.785,232.712 301.5,234.5C 300.585,236.754 299.252,238.754 297.5,240.5C 296.667,276.829 296.167,313.162 296,349.5C 295.065,357.682 292.231,365.016 287.5,371.5C 286.118,372.801 284.452,373.634 282.5,374C 283.252,374.671 283.586,375.504 283.5,376.5C 272.573,387.751 259.239,391.917 243.5,389C 219.325,381.522 207.825,365.022 209,339.5C 208.333,313.833 208.333,288.167 209,262.5C 209.391,257.944 211.891,255.61 216.5,255.5C 219.037,255.435 221.037,256.435 222.5,258.5C 223.333,289.495 223.833,320.495 224,351.5C 227.652,365.323 236.485,373.323 250.5,375.5C 251.793,376.158 253.293,376.492 255,376.5C 257.821,376.592 260.321,375.926 262.5,374.5C 272.878,370.283 279.044,362.616 281,351.5C 281.5,315.835 281.667,280.168 281.5,244.5C 281.027,243.094 280.027,242.427 278.5,242.5C 272.117,238.977 265.451,235.977 258.5,233.5C 257.558,233.608 256.725,233.941 256,234.5C 251.175,245.334 243.342,248.501 232.5,244C 230.622,242.457 229.122,240.624 228,238.5C 226.992,240.259 225.492,241.426 223.5,242C 220.167,242.667 216.833,242.667 213.5,242C 209.903,240.048 206.569,237.881 203.5,235.5C 203.881,234.069 204.881,233.236 206.5,233C 204.249,233.213 202.249,232.213 200.5,230C 201.759,229.077 203.092,228.243 204.5,227.5C 203.995,226.081 202.995,225.415 201.5,225.5C 204.5,221.8 203.5,220.134 198.5,220.5C 198.5,220.167 198.5,219.833 198.5,219.5C 200.199,219.34 201.866,219.506 203.5,220C 204.833,221.333 204.833,222.667 203.5,224C 204.025,224.692 204.692,225.192 205.5,225.5C 206.258,224.189 207.258,223.689 208.5,224C 208.859,226.63 209.859,228.797 211.5,230.5C 211.5,231.167 211.833,231.5 212.5,231.5C 215.518,234.97 218.852,235.304 222.5,232.5C 223.965,230.401 225.299,228.234 226.5,226C 225.644,224.405 224.311,223.572 222.5,223.5C 223.429,222.685 224.429,221.852 225.5,221C 225.034,219.701 225.034,218.201 225.5,216.5 Z M 244.5,228.5 C 245.609,229.29 246.942,229.79 248.5,230C 247.663,231.011 247.33,232.178 247.5,233.5C 238.193,240.515 234.36,238.181 236,226.5C 238.778,227.325 241.611,227.992 244.5,228.5 Z M 213.5,222.5 C 216.43,223.299 219.43,223.632 222.5,223.5C 224.311,223.572 225.644,224.405 226.5,226C 225.299,228.234 223.965,230.401 222.5,232.5C 218.852,235.304 215.518,234.97 212.5,231.5C 212.19,228.287 212.523,225.287 213.5,222.5 Z" /> <path fill={fillColor} d="M 225.5,216.5 C 247.583,219.231 268.249,225.898 287.5,236.5C 289.507,234.467 291.507,232.467 293.5,230.5C 294.906,230.027 295.573,229.027 295.5,227.5C 296.167,227.5 296.833,227.5 297.5,227.5C 296.606,230.242 297.606,230.909 300.5,229.5C 301.452,231.045 301.785,232.712 301.5,234.5C 300.585,236.754 299.252,238.754 297.5,240.5C 296.667,276.829 296.167,313.162 296,349.5C 295.065,357.682 292.231,365.016 287.5,371.5C 286.118,372.801 284.452,373.634 282.5,374C 283.252,374.671 283.586,375.504 283.5,376.5C 272.573,387.751 259.239,391.917 243.5,389C 219.325,381.522 207.825,365.022 209,339.5C 208.333,313.833 208.333,288.167 209,262.5C 209.391,257.944 211.891,255.61 216.5,255.5C 219.037,255.435 221.037,256.435 222.5,258.5C 223.333,289.495 223.833,320.495 224,351.5C 227.652,365.323 236.485,373.323 250.5,375.5C 251.793,376.158 253.293,376.492 255,376.5C 257.821,376.592 260.321,375.926 262.5,374.5C 272.878,370.283 279.044,362.616 281,351.5C 281.5,315.835 281.667,280.168 281.5,244.5C 281.027,243.094 280.027,242.427 278.5,242.5C 272.117,238.977 265.451,235.977 258.5,233.5C 257.558,233.608 256.725,233.941 256,234.5C 251.175,245.334 243.342,248.501 232.5,244C 230.622,242.457 229.122,240.624 228,238.5C 226.992,240.259 225.492,241.426 223.5,242C 220.167,242.667 216.833,242.667 213.5,242C 209.903,240.048 206.569,237.881 203.5,235.5C 203.881,234.069 204.881,233.236 206.5,233C 204.249,233.213 202.249,232.213 200.5,230C 201.759,229.077 203.092,228.243 204.5,227.5C 203.995,226.081 202.995,225.415 201.5,225.5C 204.5,221.8 203.5,220.134 198.5,220.5C 198.5,220.167 198.5,219.833 198.5,219.5C 200.199,219.34 201.866,219.506 203.5,220C 204.833,221.333 204.833,222.667 203.5,224C 204.025,224.692 204.692,225.192 205.5,225.5C 206.258,224.189 207.258,223.689 208.5,224C 208.859,226.63 209.859,228.797 211.5,230.5C 211.5,231.167 211.833,231.5 212.5,231.5C 215.518,234.97 218.852,235.304 222.5,232.5C 223.965,230.401 225.299,228.234 226.5,226C 225.644,224.405 224.311,223.572 222.5,223.5C 223.429,222.685 224.429,221.852 225.5,221C 225.034,219.701 225.034,218.201 225.5,216.5 Z M 244.5,228.5 C 245.609,229.29 246.942,229.79 248.5,230C 247.663,231.011 247.33,232.178 247.5,233.5C 238.193,240.515 234.36,238.181 236,226.5C 238.778,227.325 241.611,227.992 244.5,228.5 Z M 213.5,222.5 C 216.43,223.299 219.43,223.632 222.5,223.5C 224.311,223.572 225.644,224.405 226.5,226C 225.299,228.234 223.965,230.401 222.5,232.5C 218.852,235.304 215.518,234.97 212.5,231.5C 212.19,228.287 212.523,225.287 213.5,222.5 Z" />
{/* Additional details */} {/* Additional details */}
<path fill={fillColor} d="M 325.5,381.5 C 324.176,384.148 322.843,386.814 321.5,389.5C 318.621,387.559 315.788,388.226 313,391.5C 311.798,389.323 311.298,386.989 311.5,384.5C 311.333,336.832 311.5,289.166 312,241.5C 313.399,235.938 316.899,234.105 322.5,236C 324.049,237.214 325.215,238.714 326,240.5C 326.832,287.668 326.665,334.668 325.5,381.5 Z" /> <path fill={fillColor} d="M 325.5,381.5 C 324.176,384.148 322.843,386.814 321.5,389.5C 318.621,387.559 315.788,388.226 313,391.5C 311.798,389.323 311.298,386.989 311.5,384.5C 311.333,336.832 311.5,289.166 312,241.5C 313.399,235.938 316.899,234.105 322.5,236C 324.049,237.214 325.215,238.714 326,240.5C 326.832,287.668 326.665,334.668 325.5,381.5 Z" />
{/* Final details */} {/* Final details */}
<path fill={fillColor} d="M 287.5,371.5 C 286.92,373.749 285.587,375.415 283.5,376.5C 283.586,375.504 283.252,374.671 282.5,374C 284.452,373.634 286.118,372.801 287.5,371.5 Z" /> <path fill={fillColor} d="M 287.5,371.5 C 286.92,373.749 285.587,375.415 283.5,376.5C 283.586,375.504 283.252,374.671 282.5,374C 284.452,373.634 286.118,372.801 287.5,371.5 Z" />
{/* Bottom section */} {/* Bottom section */}
<path fill={fillColor} d="M 325.5,381.5 C 322.774,410.382 308.44,431.215 282.5,444C 280.564,444.813 278.564,445.313 276.5,445.5C 274.447,445.402 272.78,446.069 271.5,447.5C 243.945,453.656 220.111,446.99 200,427.5C 198.25,425.266 196.75,422.932 195.5,420.5C 197.557,421.202 199.557,421.535 201.5,421.5C 201.833,421.833 202.167,422.167 202.5,422.5C 200.252,423.324 200.086,424.324 202,425.5C 205.109,423.614 206.109,420.947 205,417.5C 204.667,418.167 204.333,418.833 204,419.5C 203.333,417.833 203.333,416.167 204,414.5C 207.123,416.098 207.956,415.431 206.5,412.5C 217.31,425.907 231.31,433.573 248.5,435.5C 253.65,436.651 258.984,436.817 264.5,436C 265.416,435.722 266.082,435.222 266.5,434.5C 284.985,429.357 298.318,418.024 306.5,400.5C 307.906,400.027 308.573,399.027 308.5,397.5C 309.598,393.089 310.598,388.755 311.5,384.5C 311.298,386.989 311.798,389.323 313,391.5C 315.788,388.226 318.621,387.559 321.5,389.5C 322.843,386.814 324.176,384.148 325.5,381.5 Z" /> <path fill={fillColor} d="M 325.5,381.5 C 322.774,410.382 308.44,431.215 282.5,444C 280.564,444.813 278.564,445.313 276.5,445.5C 274.447,445.402 272.78,446.069 271.5,447.5C 243.945,453.656 220.111,446.99 200,427.5C 198.25,425.266 196.75,422.932 195.5,420.5C 197.557,421.202 199.557,421.535 201.5,421.5C 201.833,421.833 202.167,422.167 202.5,422.5C 200.252,423.324 200.086,424.324 202,425.5C 205.109,423.614 206.109,420.947 205,417.5C 204.667,418.167 204.333,418.833 204,419.5C 203.333,417.833 203.333,416.167 204,414.5C 207.123,416.098 207.956,415.431 206.5,412.5C 217.31,425.907 231.31,433.573 248.5,435.5C 253.65,436.651 258.984,436.817 264.5,436C 265.416,435.722 266.082,435.222 266.5,434.5C 284.985,429.357 298.318,418.024 306.5,400.5C 307.906,400.027 308.573,399.027 308.5,397.5C 309.598,393.089 310.598,388.755 311.5,384.5C 311.298,386.989 311.798,389.323 313,391.5C 315.788,388.226 318.621,387.559 321.5,389.5C 322.843,386.814 324.176,384.148 325.5,381.5 Z" />
</svg> </svg>
); );
} }
+2 -2
View File
@@ -9,10 +9,10 @@ export const buttonVariants = cva(
destructive: destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90", "bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline: outline:
"border border-input bg-background hover:bg-border/20 dark:hover:bg-border/50", "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary: secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80", "bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "", ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline", link: "text-primary underline-offset-4 hover:underline",
}, },
size: { size: {
+5 -5
View File
@@ -82,13 +82,13 @@ const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
([theme, prefix]) => ` ([theme, prefix]) => `
${prefix} [data-chart=${id}] { ${prefix} [data-chart=${id}] {
${colorConfig ${colorConfig
.map(([key, itemConfig]) => { .map(([key, itemConfig]) => {
const color = const color =
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] || itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
itemConfig.color itemConfig.color
return color ? ` --color-${key}: ${color};` : null return color ? ` --color-${key}: ${color};` : null
}) })
.join("\n")} .join("\n")}
} }
` `
) )
+2 -2
View File
@@ -19,8 +19,8 @@ const FormField = <
TFieldValues extends FieldValues = FieldValues, TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues> TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
>({ >({
...props ...props
}: ControllerProps<TFieldValues, TName>) => { }: ControllerProps<TFieldValues, TName>) => {
return ( return (
<FormFieldContext.Provider value={{ name: props.name }}> <FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} /> <Controller {...props} />
+87 -87
View File
@@ -35,107 +35,107 @@ const SidebarProvider = React.forwardRef<
defaultOpen?: boolean defaultOpen?: boolean
open?: boolean open?: boolean
onOpenChange?: (open: boolean) => void onOpenChange?: (open: boolean) => void
} }
>( >(
( (
{ {
defaultOpen = true, defaultOpen = true,
open: openProp, open: openProp,
onOpenChange: setOpenProp, onOpenChange: setOpenProp,
className, className,
style, style,
children, children,
...props ...props
}, },
ref ref
) => { ) => {
const isMobile = useIsMobile() const isMobile = useIsMobile()
const [openMobile, setOpenMobile] = React.useState(false) const [openMobile, setOpenMobile] = React.useState(false)
// This is the internal state of the sidebar. // This is the internal state of the sidebar.
// We use openProp and setOpenProp for control from outside the component. // We use openProp and setOpenProp for control from outside the component.
const [_open, _setOpen] = React.useState(defaultOpen) const [_open, _setOpen] = React.useState(defaultOpen)
const open = openProp ?? _open const open = openProp ?? _open
const setOpen = React.useCallback( const setOpen = React.useCallback(
(value: boolean | ((value: boolean) => boolean)) => { (value: boolean | ((value: boolean) => boolean)) => {
const openState = typeof value === "function" ? value(open) : value const openState = typeof value === "function" ? value(open) : value
if (setOpenProp) { if (setOpenProp) {
setOpenProp(openState) setOpenProp(openState)
} else { } else {
_setOpen(openState) _setOpen(openState)
} }
// This sets the cookie to keep the sidebar state. // This sets the cookie to keep the sidebar state.
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}` document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
}, },
[setOpenProp, open] [setOpenProp, open]
) )
// Helper to toggle the sidebar. // Helper to toggle the sidebar.
const toggleSidebar = React.useCallback(() => { const toggleSidebar = React.useCallback(() => {
return isMobile return isMobile
? setOpenMobile((open) => !open) ? setOpenMobile((open) => !open)
: setOpen((open) => !open) : setOpen((open) => !open)
}, [isMobile, setOpen, setOpenMobile]) }, [isMobile, setOpen, setOpenMobile])
// Adds a keyboard shortcut to toggle the sidebar. // Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => { React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => { const handleKeyDown = (event: KeyboardEvent) => {
if ( if (
event.key === SIDEBAR_KEYBOARD_SHORTCUT && event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
(event.metaKey || event.ctrlKey) (event.metaKey || event.ctrlKey)
) { ) {
event.preventDefault() event.preventDefault()
toggleSidebar() toggleSidebar()
} }
} }
window.addEventListener("keydown", handleKeyDown) window.addEventListener("keydown", handleKeyDown)
return () => window.removeEventListener("keydown", handleKeyDown) return () => window.removeEventListener("keydown", handleKeyDown)
}, [toggleSidebar]) }, [toggleSidebar])
// We add a state so that we can do data-state="expanded" or "collapsed". // We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes. // This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed" const state = open ? "expanded" : "collapsed"
const contextValue = React.useMemo<SidebarContextType>( const contextValue = React.useMemo<SidebarContextType>(
() => ({ () => ({
state, state,
open, open,
setOpen, setOpen,
isMobile, isMobile,
openMobile, openMobile,
setOpenMobile, setOpenMobile,
toggleSidebar, toggleSidebar,
}), }),
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar] [state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
) )
return ( return (
<SidebarContext.Provider value={contextValue}> <SidebarContext.Provider value={contextValue}>
<TooltipProvider delayDuration={0}> <TooltipProvider delayDuration={0}>
<div <div
style={ style={
{ {
"--sidebar-width": SIDEBAR_WIDTH, "--sidebar-width": SIDEBAR_WIDTH,
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON, "--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
...style, ...style,
} as React.CSSProperties } as React.CSSProperties
} }
className={cn( className={cn(
"group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar", "group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",
className className
)} )}
ref={ref} ref={ref}
{...props} {...props}
> >
{children} {children}
</div> </div>
</TooltipProvider> </TooltipProvider>
</SidebarContext.Provider> </SidebarContext.Provider>
) )
} }
) )
SidebarProvider.displayName = "SidebarProvider" SidebarProvider.displayName = "SidebarProvider"
const Sidebar = React.forwardRef< const Sidebar = React.forwardRef<
+1 -1
View File
@@ -14,7 +14,7 @@ const ToastViewport = React.forwardRef<
<ToastPrimitives.Viewport <ToastPrimitives.Viewport
ref={ref} ref={ref}
className={cn( className={cn(
"fixed top-safe z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-safe sm:right-safe sm:top-auto sm:flex-col md:max-w-[480px]", "fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[480px]",
className className
)} )}
{...props} {...props}
+169
View File
@@ -0,0 +1,169 @@
import { describe, it, expect, vi } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { ConsoleProvider, useConsole } from './ConsoleContext';
import { ProjectPreviewConsoleError } from '@/lib/errors/ProjectPreviewConsoleError';
// Test wrapper component
function TestWrapper({ children }: { children: React.ReactNode }) {
return <ConsoleProvider>{children}</ConsoleProvider>;
}
describe('ConsoleContext', () => {
it('should provide console functionality', () => {
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
expect(result.current.messages).toEqual([]);
expect(result.current.messagesRef.current).toEqual([]);
expect(typeof result.current.addMessage).toBe('function');
expect(typeof result.current.clearMessages).toBe('function');
expect(typeof result.current.addErrorListener).toBe('function');
expect(typeof result.current.removeErrorListener).toBe('function');
});
it('should add and retrieve messages', () => {
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
act(() => {
result.current.addMessage('log', 'Test log message');
result.current.addMessage('error', 'Test error message');
});
expect(result.current.messages).toHaveLength(2);
expect(result.current.messagesRef.current).toHaveLength(2);
expect(result.current.messages[0]).toEqual({
level: 'log',
message: 'Test log message',
});
expect(result.current.messagesRef.current[0]).toEqual({
level: 'log',
message: 'Test log message',
});
expect(result.current.messages[1]).toEqual({
level: 'error',
message: 'Test error message',
});
expect(result.current.messagesRef.current[1]).toEqual({
level: 'error',
message: 'Test error message',
});
});
it('should clear messages', () => {
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
act(() => {
result.current.addMessage('log', 'Test message');
});
expect(result.current.messages).toHaveLength(1);
expect(result.current.messagesRef.current).toHaveLength(1);
act(() => {
result.current.clearMessages();
});
expect(result.current.messages).toHaveLength(0);
expect(result.current.messagesRef.current).toHaveLength(0);
});
it('should trigger error listener when error message is added', () => {
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
const errorListener = vi.fn();
act(() => {
result.current.addErrorListener(errorListener);
});
act(() => {
result.current.addMessage('error', 'Test error message');
});
expect(errorListener).toHaveBeenCalledTimes(1);
expect(errorListener).toHaveBeenCalledWith(
expect.objectContaining({
message: 'Console error detected: Test error message',
logs: expect.arrayContaining([
expect.objectContaining({
level: 'error',
message: 'Test error message',
}),
]),
})
);
});
it('should not trigger error listener for non-error messages', () => {
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
const errorListener = vi.fn();
act(() => {
result.current.addErrorListener(errorListener);
});
act(() => {
result.current.addMessage('log', 'Test log message');
result.current.addMessage('warn', 'Test warning message');
result.current.addMessage('info', 'Test info message');
});
expect(errorListener).not.toHaveBeenCalled();
});
it('should remove error listener correctly', () => {
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
const errorListener = vi.fn();
act(() => {
result.current.addErrorListener(errorListener);
result.current.removeErrorListener(errorListener);
});
act(() => {
result.current.addMessage('error', 'Test error message');
});
expect(errorListener).not.toHaveBeenCalled();
});
it('should handle listener errors gracefully', () => {
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
const faultyListener = vi.fn(() => {
throw new Error('Listener error');
});
const workingListener = vi.fn();
act(() => {
result.current.addErrorListener(faultyListener);
result.current.addErrorListener(workingListener);
});
// Should not throw despite faulty listener
expect(() => {
act(() => {
result.current.addMessage('error', 'Test error message');
});
}).not.toThrow();
expect(faultyListener).toHaveBeenCalled();
expect(workingListener).toHaveBeenCalled();
});
it('should throw error when used outside provider', () => {
expect(() => {
renderHook(() => useConsole());
}).toThrow('useConsole must be used within a ConsoleProvider');
});
});
describe('ProjectPreviewConsoleError', () => {
it('should create error with console logs', () => {
const logs = [{ level: 'error' as const, message: 'Test error' }];
const error = new ProjectPreviewConsoleError('Test message', logs);
expect(error.message).toBe('Test message');
expect(error.name).toBe('ProjectPreviewConsoleError');
expect(error.logs).toEqual(logs);
expect(error instanceof Error).toBe(true);
expect(error instanceof ProjectPreviewConsoleError).toBe(true);
});
});
+95
View File
@@ -0,0 +1,95 @@
import React, { createContext, useContext, useState, useCallback, useRef, ReactNode } from 'react';
import { ProjectPreviewConsoleError } from '@/lib/errors/ProjectPreviewConsoleError';
export interface ConsoleMessage {
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
message: string;
}
export { ProjectPreviewConsoleError };
interface ConsoleContextType {
messages: ConsoleMessage[];
messagesRef: React.MutableRefObject<ConsoleMessage[]>;
addMessage: (level: ConsoleMessage['level'], message: string) => void;
clearMessages: () => void;
addErrorListener: (listener: (error: ProjectPreviewConsoleError) => void) => void;
removeErrorListener: (listener: (error: ProjectPreviewConsoleError) => void) => void;
}
const ConsoleContext = createContext<ConsoleContextType | undefined>(undefined);
export function useConsole(): ConsoleContextType {
const context = useContext(ConsoleContext);
if (context === undefined) {
throw new Error('useConsole must be used within a ConsoleProvider');
}
return context;
}
interface ConsoleProviderProps {
children: ReactNode;
}
export function ConsoleProvider({ children }: ConsoleProviderProps) {
const [messages, setMessages] = useState<ConsoleMessage[]>([]);
const messagesRef = useRef<ConsoleMessage[]>([]);
const [errorListeners, setErrorListeners] = useState<Array<(error: ProjectPreviewConsoleError) => void>>([]);
const addMessage = useCallback((level: ConsoleMessage['level'], message: string) => {
const consoleMessage: ConsoleMessage = {
level,
message,
};
// Update both state and ref
const newMessages = [...messagesRef.current, consoleMessage];
messagesRef.current = newMessages;
setMessages(newMessages);
// If this is an error, notify listeners
if (level === 'error') {
const error = new ProjectPreviewConsoleError(
`Console error detected: ${message}`,
newMessages.filter(msg => msg.level === 'error')
);
errorListeners.forEach(listener => {
try {
listener(error);
} catch (err) {
console.warn('Error listener failed:', err);
}
});
}
}, [errorListeners]);
const clearMessages = useCallback(() => {
setMessages([]);
messagesRef.current = [];
}, []);
const addErrorListener = useCallback((listener: (error: ProjectPreviewConsoleError) => void) => {
setErrorListeners(prev => [...prev, listener]);
}, []);
const removeErrorListener = useCallback((listener: (error: ProjectPreviewConsoleError) => void) => {
setErrorListeners(prev => prev.filter(l => l !== listener));
}, []);
const value: ConsoleContextType = {
messages,
messagesRef,
addMessage,
clearMessages,
addErrorListener,
removeErrorListener,
};
return (
<ConsoleContext.Provider value={value}>
{children}
</ConsoleContext.Provider>
);
}
-11
View File
@@ -1,11 +0,0 @@
import { createContext } from 'react';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
export interface ConsoleErrorContextValue {
hasErrors: boolean;
consoleError: ProjectPreviewConsoleError | null;
clearErrors: () => void;
dismissConsoleError: () => void;
}
export const ConsoleErrorContext = createContext<ConsoleErrorContextValue | undefined>(undefined);
+3 -5
View File
@@ -13,7 +13,6 @@ interface UseAIChatSessionOptions {
maxSteps?: number; maxSteps?: number;
onUpdateMetadata?: (title: string, description: string) => void; onUpdateMetadata?: (title: string, description: string) => void;
onAIError?: (error: Error) => void; onAIError?: (error: Error) => void;
isTextChat?: boolean;
} }
interface StreamingMessage { interface StreamingMessage {
@@ -33,8 +32,7 @@ export function useAIChat({
customTools = {}, customTools = {},
maxSteps = 50, maxSteps = 50,
onUpdateMetadata, onUpdateMetadata,
onAIError, onAIError
isTextChat = false
}: UseAIChatSessionOptions) { }: UseAIChatSessionOptions) {
const sessionManager = useSessionManager(); const sessionManager = useSessionManager();
const { isConfigured } = useAISettings(); const { isConfigured } = useAISettings();
@@ -48,14 +46,14 @@ export function useAIChat({
const initSession = useCallback(async () => { const initSession = useCallback(async () => {
// Load or update session // Load or update session
const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps, isTextChat); const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps);
// Initialize individual state variables from existing session // Initialize individual state variables from existing session
setMessages([...session.messages]); setMessages([...session.messages]);
setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined); setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined);
setIsLoading(session.isLoading); setIsLoading(session.isLoading);
setTotalCost(session.totalCost || 0); setTotalCost(session.totalCost || 0);
setLastInputTokens(session.lastInputTokens || 0); setLastInputTokens(session.lastInputTokens || 0);
}, [sessionManager, projectId, tools, customTools, maxSteps, isTextChat]); }, [sessionManager, projectId, tools, customTools, maxSteps]);
// Initialize session // Initialize session
useEffect(() => { useEffect(() => {
+33 -4
View File
@@ -4,18 +4,34 @@ import { createAIClient } from '@/lib/ai-client';
import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useCurrentUser } from '@/hooks/useCurrentUser';
import { AIProvider } from '@/contexts/AISettingsContext'; import { AIProvider } from '@/contexts/AISettingsContext';
const creditsResponseSchema = z.object({ // Zod schemas for the two possible response formats
const creditsResponseV1Schema = z.object({
object: z.literal('credits'), object: z.literal('credits'),
amount: z.number(), amount: z.number(),
}); });
const creditsResponseV2Schema = z.object({
data: z.object({
total_credits: z.number(),
total_usage: z.number(),
}),
});
// Union schema to handle both response formats
const creditsResponseSchema = z.union([creditsResponseV1Schema, creditsResponseV2Schema]);
// Normalized response type (always in V1 format) // Normalized response type (always in V1 format)
export interface CreditsResponse { export interface CreditsResponse {
object: 'credits'; object: 'credits';
amount: number; amount: number;
} }
/** Custom hook to fetch AI provider credits */ /**
* Custom hook to fetch AI provider credits
* @param providerId - The ID of the AI provider
* @param connection - The AI connection configuration
* @returns Query result with credits information
*/
export function useAICredits(provider: AIProvider) { export function useAICredits(provider: AIProvider) {
const { user } = useCurrentUser(); const { user } = useCurrentUser();
@@ -25,7 +41,20 @@ export function useAICredits(provider: AIProvider) {
try { try {
const ai = createAIClient(provider, user); const ai = createAIClient(provider, user);
const data = await ai.get('/credits'); const data = await ai.get('/credits');
return creditsResponseSchema.parse(data);
// Validate and normalize the response
const parsed = creditsResponseSchema.parse(data);
// Convert V2 format to V1 format if needed
if ('data' in parsed) {
return {
object: 'credits',
amount: parsed.data.total_credits - parsed.data.total_usage,
};
}
// Already in V1 format
return parsed;
} catch (error) { } catch (error) {
if (error instanceof Error && !error.message.includes('Connection error')) { if (error instanceof Error && !error.message.includes('Connection error')) {
console.error('Error fetching AI credits:', error); console.error('Error fetching AI credits:', error);
@@ -36,6 +65,6 @@ export function useAICredits(provider: AIProvider) {
retry: false, // Don't retry as not all providers support this endpoint retry: false, // Don't retry as not all providers support this endpoint
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
staleTime: 5 * 60 * 1000, // 5 minutes staleTime: 5 * 60 * 1000, // 5 minutes
enabled: !!provider.nostr && !!user, enabled: provider.id === 'shakespeare' && !!user,
}); });
} }
+1 -1
View File
@@ -80,7 +80,7 @@ export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
} catch (error) { } catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Failed to generate project ID'; const errorMessage = error instanceof Error ? error.message : 'Failed to generate project ID';
onError?.(errorMessage); onError?.(errorMessage);
throw error; throw new Error(errorMessage);
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
-35
View File
@@ -1,35 +0,0 @@
import { useState, useEffect } from 'react';
import { useSessionManager } from './useSessionManager';
/**
* Hook to check if any project has running AI sessions
* @returns {boolean} True if any project has a running AI session
*/
export function useAnyProjectBusy(): boolean {
const sessionManager = useSessionManager();
const [anyProjectBusy, setAnyProjectBusy] = useState(false);
useEffect(() => {
const updateStatus = () => {
const sessions = sessionManager.getAllSessions();
const hasBusyProject = sessions.some(session => session.isLoading);
setAnyProjectBusy(hasBusyProject);
};
// Initial update
updateStatus();
// Subscribe to session changes
sessionManager.on('sessionCreated', updateStatus);
sessionManager.on('sessionDeleted', updateStatus);
sessionManager.on('loadingChanged', updateStatus);
return () => {
sessionManager.off('sessionCreated', updateStatus);
sessionManager.off('sessionDeleted', updateStatus);
sessionManager.off('loadingChanged', updateStatus);
};
}, [sessionManager]);
return anyProjectBusy;
}
-12
View File
@@ -1,12 +0,0 @@
import { describe, it, expect } from 'vitest';
import { renderHook } from '@testing-library/react';
import { useConsoleError } from './useConsoleError';
describe('useConsoleError', () => {
it('should throw error when used outside ConsoleErrorProvider', () => {
// Expect the hook to throw when not wrapped in provider
expect(() => {
renderHook(() => useConsoleError());
}).toThrow('useConsoleError must be used within a ConsoleErrorProvider');
});
});
-16
View File
@@ -1,16 +0,0 @@
import { useContext } from 'react';
import { ConsoleErrorContext } from '@/contexts/ConsoleErrorContext';
/**
* Hook to access console error state from the ConsoleErrorProvider.
* Provides boolean error state and console error information for Quilly.
*/
export function useConsoleError() {
const context = useContext(ConsoleErrorContext);
if (context === undefined) {
throw new Error('useConsoleError must be used within a ConsoleErrorProvider');
}
return context;
}
+1 -4
View File
@@ -25,24 +25,21 @@ function createTestWrapper() {
vi.mock('./useProjectsManager', () => ({ vi.mock('./useProjectsManager', () => ({
useProjectsManager: () => ({ useProjectsManager: () => ({
init: vi.fn().mockResolvedValue(undefined), init: vi.fn().mockResolvedValue(undefined),
getAllChatItems: vi.fn().mockResolvedValue([ getProjects: vi.fn().mockResolvedValue([
{ {
id: 'project-1', id: 'project-1',
name: 'Project 1', name: 'Project 1',
lastModified: new Date('2023-01-01'), lastModified: new Date('2023-01-01'),
type: 'project' as const,
}, },
{ {
id: 'project-2', id: 'project-2',
name: 'Project 2', name: 'Project 2',
lastModified: new Date('2023-01-02'), lastModified: new Date('2023-01-02'),
type: 'project' as const,
}, },
{ {
id: 'project-3', id: 'project-3',
name: 'Project 3', name: 'Project 3',
lastModified: new Date('2023-01-03'), lastModified: new Date('2023-01-03'),
type: 'project' as const,
}, },
] as Project[]), ] as Project[]),
}), }),
+6 -6
View File
@@ -1,7 +1,7 @@
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useLocalStorage } from '@/hooks/useLocalStorage'; import { useLocalStorage } from '@/hooks/useLocalStorage';
import type { ChatItem } from '@/lib/ProjectsManager'; import type { Project } from '@/lib/ProjectsManager';
export function useProjects() { export function useProjects() {
const projectsManager = useProjectsManager(); const projectsManager = useProjectsManager();
@@ -9,12 +9,12 @@ export function useProjects() {
return useQuery({ return useQuery({
queryKey: ['projects'], queryKey: ['projects'],
queryFn: async (): Promise<ChatItem[]> => { queryFn: async (): Promise<Project[]> => {
await projectsManager.init(); await projectsManager.init();
const items = await projectsManager.getAllChatItems(); const projects = await projectsManager.getProjects();
// Sort items: favorites first, then by lastModified (newest first) // Sort projects: favorites first, then by lastModified (newest first)
return items.sort((a, b) => { return projects.sort((a, b) => {
const aIsFavorite = favorites.includes(a.id); const aIsFavorite = favorites.includes(a.id);
const bIsFavorite = favorites.includes(b.id); const bIsFavorite = favorites.includes(b.id);
+1 -1
View File
@@ -11,7 +11,7 @@ export function useTheme(): {
systemTheme: "light" | "dark"; systemTheme: "light" | "dark";
displayTheme: "light" | "dark"; displayTheme: "light" | "dark";
setTheme: (theme: Theme) => void; setTheme: (theme: Theme) => void;
} { } {
const { config, updateConfig } = useAppContext(); const { config, updateConfig } = useAppContext();
const systemTheme = useSystemTheme(); const systemTheme = useSystemTheme();
+3 -3
View File
@@ -96,9 +96,9 @@ export const reducer = (state: State, action: Action): State => {
toasts: state.toasts.map((t) => toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined t.id === toastId || toastId === undefined
? { ? {
...t, ...t,
open: false, open: false,
} }
: t : t
), ),
} }
+2 -2
View File
@@ -73,8 +73,8 @@ export function useWallet() {
const preferredMethod: WalletStatus['preferredMethod'] = activeNWC const preferredMethod: WalletStatus['preferredMethod'] = activeNWC
? 'nwc' ? 'nwc'
: webln : webln
? 'webln' ? 'webln'
: 'manual'; : 'manual';
const status: WalletStatus = { const status: WalletStatus = {
hasWebLN: !!webln, hasWebLN: !!webln,
+75 -75
View File
@@ -209,98 +209,98 @@ export function useZaps(
try { try {
const res = await fetch(`${zapEndpoint}?amount=${zapAmount}&nostr=${encodeURI(JSON.stringify(signedZapRequest))}`); const res = await fetch(`${zapEndpoint}?amount=${zapAmount}&nostr=${encodeURI(JSON.stringify(signedZapRequest))}`);
const responseData = await res.json(); const responseData = await res.json();
if (!res.ok) { if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${responseData.reason || 'Unknown error'}`); throw new Error(`HTTP ${res.status}: ${responseData.reason || 'Unknown error'}`);
} }
const newInvoice = responseData.pr; const newInvoice = responseData.pr;
if (!newInvoice || typeof newInvoice !== 'string') { if (!newInvoice || typeof newInvoice !== 'string') {
throw new Error('Lightning service did not return a valid invoice'); throw new Error('Lightning service did not return a valid invoice');
} }
// Get the current active NWC connection dynamically // Get the current active NWC connection dynamically
const currentNWCConnection = getActiveConnection(); const currentNWCConnection = getActiveConnection();
// Try NWC first if available and properly connected // Try NWC first if available and properly connected
if (currentNWCConnection && currentNWCConnection.connectionString && currentNWCConnection.isConnected) { if (currentNWCConnection && currentNWCConnection.connectionString && currentNWCConnection.isConnected) {
try { try {
await sendPayment(currentNWCConnection, newInvoice); await sendPayment(currentNWCConnection, newInvoice);
// Clear states immediately on success // Clear states immediately on success
setIsZapping(false); setIsZapping(false);
setInvoice(null); setInvoice(null);
toast({ toast({
title: 'Zap successful!', title: 'Zap successful!',
description: `You sent ${amount} sats via NWC to the author.`, description: `You sent ${amount} sats via NWC to the author.`,
}); });
// Invalidate zap queries to refresh counts // Invalidate zap queries to refresh counts
queryClient.invalidateQueries({ queryKey: ['zaps'] }); queryClient.invalidateQueries({ queryKey: ['zaps'] });
// Close dialog last to ensure clean state // Close dialog last to ensure clean state
onZapSuccess?.(); onZapSuccess?.();
return; return;
} catch (nwcError) { } catch (nwcError) {
console.error('NWC payment failed, falling back:', nwcError); console.error('NWC payment failed, falling back:', nwcError);
// Show specific NWC error to user for debugging // Show specific NWC error to user for debugging
const errorMessage = nwcError instanceof Error ? nwcError.message : 'Unknown NWC error'; const errorMessage = nwcError instanceof Error ? nwcError.message : 'Unknown NWC error';
toast({ toast({
title: 'NWC payment failed', title: 'NWC payment failed',
description: `${errorMessage}. Falling back to other payment methods...`, description: `${errorMessage}. Falling back to other payment methods...`,
variant: 'destructive', variant: 'destructive',
}); });
} }
} }
if (webln) { // Try WebLN next if (webln) { // Try WebLN next
try { try {
await webln.sendPayment(newInvoice); await webln.sendPayment(newInvoice);
// Clear states immediately on success // Clear states immediately on success
setIsZapping(false); setIsZapping(false);
setInvoice(null); setInvoice(null);
toast({
title: 'Zap successful!',
description: `You sent ${amount} sats to the author.`,
});
// Invalidate zap queries to refresh counts
queryClient.invalidateQueries({ queryKey: ['zaps'] });
// Close dialog last to ensure clean state
onZapSuccess?.();
} catch (weblnError) {
console.error('webln payment failed, falling back:', weblnError);
// Show specific WebLN error to user for debugging
const errorMessage = weblnError instanceof Error ? weblnError.message : 'Unknown WebLN error';
toast({
title: 'WebLN payment failed',
description: `${errorMessage}. Falling back to other payment methods...`,
variant: 'destructive',
});
setInvoice(newInvoice);
setIsZapping(false);
}
} else { // Default - show QR code and manual Lightning URI
setInvoice(newInvoice);
setIsZapping(false);
}
} catch (err) {
console.error('Zap error:', err);
toast({ toast({
title: 'Zap successful!', title: 'Zap failed',
description: `You sent ${amount} sats to the author.`, description: (err as Error).message,
});
// Invalidate zap queries to refresh counts
queryClient.invalidateQueries({ queryKey: ['zaps'] });
// Close dialog last to ensure clean state
onZapSuccess?.();
} catch (weblnError) {
console.error('webln payment failed, falling back:', weblnError);
// Show specific WebLN error to user for debugging
const errorMessage = weblnError instanceof Error ? weblnError.message : 'Unknown WebLN error';
toast({
title: 'WebLN payment failed',
description: `${errorMessage}. Falling back to other payment methods...`,
variant: 'destructive', variant: 'destructive',
}); });
setInvoice(newInvoice);
setIsZapping(false); setIsZapping(false);
} }
} else { // Default - show QR code and manual Lightning URI
setInvoice(newInvoice);
setIsZapping(false);
}
} catch (err) {
console.error('Zap error:', err);
toast({
title: 'Zap failed',
description: (err as Error).message,
variant: 'destructive',
});
setIsZapping(false);
}
} catch (err) { } catch (err) {
console.error('Zap error:', err); console.error('Zap error:', err);
toast({ toast({
+4 -30
View File
@@ -110,13 +110,11 @@
@layer base { @layer base {
* { * {
border-color: hsl(var(--border)); @apply border-border;
} }
body { body {
background-color: hsl(var(--background)); @apply bg-background text-foreground font-sans;
color: hsl(var(--foreground));
font-family: 'Inter Variable', 'Inter', 'system-ui', 'sans-serif';
font-feature-settings: "rlig" 1, "calt" 1; font-feature-settings: "rlig" 1, "calt" 1;
} }
@@ -140,10 +138,8 @@
} }
/* GitHub-style focus rings */ /* GitHub-style focus rings */
.focus-ring:focus-visible { .focus-ring {
outline: none; @apply focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2;
box-shadow: 0 0 0 2px hsl(var(--ring));
outline-offset: 2px;
} }
/* Smooth transitions for theme switching */ /* Smooth transitions for theme switching */
@@ -251,22 +247,6 @@
max-height: 100dvh; max-height: 100dvh;
} }
/* Mobile navigation button styles - text/icon highlighting only */
.mobile-nav-button,
.mobile-nav-button:hover,
.mobile-nav-button:active,
.mobile-nav-button-active,
.mobile-nav-button-active:hover,
.mobile-nav-button-active:active {
background-color: transparent !important;
}
.mobile-nav-button-active,
.mobile-nav-button-active:hover,
.mobile-nav-button-active:active {
color: hsl(var(--primary)) !important;
}
pre.shiki { pre.shiki {
background-color: transparent !important; background-color: transparent !important;
} }
@@ -285,10 +265,4 @@
max-height: 100vh; max-height: 100vh;
} }
} }
/* Capacitor/Mobile specific styles */
.keyboard-open {
/* Adjust layout when keyboard is open */
--keyboard-height: env(keyboard-height, 0px);
}
} }
+6 -4
View File
@@ -98,6 +98,8 @@ invalid json line
it('should create history directory if it does not exist', async () => { it('should create history directory if it does not exist', async () => {
// Mock historyDirExists to return false initially // Mock historyDirExists to return false initially
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false); vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false);
// Mock setupAiHistoryDir
vi.spyOn(dotAI, 'setupAiHistoryDir').mockResolvedValue();
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [ const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'user', content: 'Hello' } { role: 'user', content: 'Hello' }
@@ -105,8 +107,8 @@ invalid json line
await dotAI.setHistory('test-session', messages); await dotAI.setHistory('test-session', messages);
// Verify mkdir was called with recursive option // Verify setupAiHistoryDir was called
expect(mockFS.mkdir).toHaveBeenCalledWith('/test-project/.git/ai/history', { recursive: true }); expect(dotAI.setupAiHistoryDir).toHaveBeenCalled();
}); });
it('should write messages as JSONL format', async () => { it('should write messages as JSONL format', async () => {
@@ -122,7 +124,7 @@ invalid json line
// Verify writeFile was called with correct content // Verify writeFile was called with correct content
expect(mockFS.writeFile).toHaveBeenCalledWith( expect(mockFS.writeFile).toHaveBeenCalledWith(
'/test-project/.git/ai/history/test-session.jsonl', '/test-project/.ai/history/test-session.jsonl',
'{"role":"user","content":"Hello"}\n{"role":"assistant","content":"Hi there!"}\n' '{"role":"user","content":"Hello"}\n{"role":"assistant","content":"Hi there!"}\n'
); );
}); });
@@ -135,7 +137,7 @@ invalid json line
// Verify writeFile was called with empty content // Verify writeFile was called with empty content
expect(mockFS.writeFile).toHaveBeenCalledWith( expect(mockFS.writeFile).toHaveBeenCalledWith(
'/test-project/.git/ai/history/test-session.jsonl', '/test-project/.ai/history/test-session.jsonl',
'' ''
); );
}); });
+87 -17
View File
@@ -2,16 +2,16 @@ import { join } from "path-browserify";
import type OpenAI from "openai"; import type OpenAI from "openai";
import type { JSRuntimeFS } from "./JSRuntime"; import type { JSRuntimeFS } from "./JSRuntime";
/** AI message history manager and .git/ai directory utilities */ /** AI message history manager and .ai directory utilities */
export class DotAI { export class DotAI {
readonly fs: JSRuntimeFS; readonly fs: JSRuntimeFS;
readonly historyDir: string; readonly historyDir: string;
readonly workingDir: string; readonly workingDir: string;
constructor(fs: JSRuntimeFS, workingDir: string = "/", customHistoryDir?: string) { constructor(fs: JSRuntimeFS, workingDir: string = "/") {
this.fs = fs; this.fs = fs;
this.workingDir = workingDir; this.workingDir = workingDir;
this.historyDir = customHistoryDir || join(workingDir, ".git", "ai", "history"); this.historyDir = join(workingDir, ".ai", "history");
} }
/** Generate a unique session name based on the current date and time */ /** Generate a unique session name based on the current date and time */
@@ -31,6 +31,8 @@ export class DotAI {
return filename; return filename;
} }
/** Check if the history directory exists */ /** Check if the history directory exists */
async historyDirExists(): Promise<boolean> { async historyDirExists(): Promise<boolean> {
try { try {
@@ -49,9 +51,10 @@ export class DotAI {
// Validate messages before saving // Validate messages before saving
this.validateMessages(messages); this.validateMessages(messages);
// Always create the .ai directory and write session history
// Create the history directory if it doesn't exist // Create the history directory if it doesn't exist
if (!(await this.historyDirExists())) { if (!(await this.historyDirExists())) {
await this.fs.mkdir(this.historyDir, { recursive: true }); await this.setupAiHistoryDir();
} }
const sessionFile = join(this.historyDir, sessionName + ".jsonl"); const sessionFile = join(this.historyDir, sessionName + ".jsonl");
@@ -119,11 +122,29 @@ export class DotAI {
} }
/** /**
* Read the model from .git/ai/MODEL file * Creates .ai/history directory and ensures .ai/ is gitignored at the project root.
*/
async setupAiHistoryDir(): Promise<void> {
const aiHistoryDir = join(this.workingDir, ".ai", "history");
try {
// Create .ai/history directory
await this.fs.mkdir(aiHistoryDir, { recursive: true });
// Ensure .ai/ is gitignored at the project root
await this.ensureAiGitignored();
} catch (error) {
// Log error but don't fail the main operation
console.warn(`Failed to setup .ai/history directory: ${error}`);
}
}
/**
* Read the model from .ai/MODEL file
*/ */
async readAiModel(): Promise<string | undefined> { async readAiModel(): Promise<string | undefined> {
try { try {
const modelPath = join(this.workingDir, ".git", "ai", "MODEL"); const modelPath = join(this.workingDir, ".ai", "MODEL");
const content = await this.fs.readFile(modelPath, "utf8"); const content = await this.fs.readFile(modelPath, "utf8");
return content.trim(); return content.trim();
} catch { } catch {
@@ -132,29 +153,32 @@ export class DotAI {
} }
/** /**
* Write the model to .git/ai/MODEL file * Write the model to .ai/MODEL file
*/ */
async writeAiModel(model: string): Promise<void> { async writeAiModel(model: string): Promise<void> {
const aiDir = join(this.workingDir, ".git", "ai"); const aiDir = join(this.workingDir, ".ai");
const modelPath = join(aiDir, "MODEL"); const modelPath = join(aiDir, "MODEL");
try { try {
// Ensure .git/ai directory exists // Ensure .ai directory exists
await this.fs.mkdir(aiDir, { recursive: true }); await this.fs.mkdir(aiDir, { recursive: true });
// Ensure .ai/ is gitignored
await this.ensureAiGitignored();
// Write the model // Write the model
await this.fs.writeFile(modelPath, model.trim() + "\n"); await this.fs.writeFile(modelPath, model.trim() + "\n");
} catch (error) { } catch (error) {
console.warn(`Failed to write .git/ai/MODEL file: ${error}`); console.warn(`Failed to write .ai/MODEL file: ${error}`);
} }
} }
/** /**
* Read parameters from .git/ai/PARAMETERS file * Read parameters from .ai/PARAMETERS file
*/ */
async readAiParameters(): Promise<Record<string, string>> { async readAiParameters(): Promise<Record<string, string>> {
try { try {
const parametersPath = join(this.workingDir, ".git", "ai", "PARAMETERS"); const parametersPath = join(this.workingDir, ".ai", "PARAMETERS");
const content = await this.fs.readFile(parametersPath, "utf8"); const content = await this.fs.readFile(parametersPath, "utf8");
const parameters: Record<string, string> = {}; const parameters: Record<string, string> = {};
@@ -179,16 +203,19 @@ export class DotAI {
} }
/** /**
* Write parameters to .git/ai/PARAMETERS file * Write parameters to .ai/PARAMETERS file
*/ */
async writeAiParameters(parameters: Record<string, string>): Promise<void> { async writeAiParameters(parameters: Record<string, string>): Promise<void> {
const aiDir = join(this.workingDir, ".git", "ai"); const aiDir = join(this.workingDir, ".ai");
const parametersPath = join(aiDir, "PARAMETERS"); const parametersPath = join(aiDir, "PARAMETERS");
try { try {
// Ensure .git/ai directory exists // Ensure .ai directory exists
await this.fs.mkdir(aiDir, { recursive: true }); await this.fs.mkdir(aiDir, { recursive: true });
// Ensure .ai/ is gitignored
await this.ensureAiGitignored();
// Format parameters as key=value pairs // Format parameters as key=value pairs
const lines = Object.entries(parameters).map(([key, value]) => const lines = Object.entries(parameters).map(([key, value]) =>
`${key}=${value}` `${key}=${value}`
@@ -198,12 +225,12 @@ export class DotAI {
// Write the parameters // Write the parameters
await this.fs.writeFile(parametersPath, content); await this.fs.writeFile(parametersPath, content);
} catch (error) { } catch (error) {
console.warn(`Failed to write .git/ai/PARAMETERS file: ${error}`); console.warn(`Failed to write .ai/PARAMETERS file: ${error}`);
} }
} }
/** /**
* Update a single parameter in .git/ai/PARAMETERS file * Update a single parameter in .ai/PARAMETERS file
*/ */
async updateAiParameter(key: string, value: string): Promise<void> { async updateAiParameter(key: string, value: string): Promise<void> {
const currentParameters = await this.readAiParameters(); const currentParameters = await this.readAiParameters();
@@ -274,4 +301,47 @@ export class DotAI {
return null; return null;
} }
} }
/**
* Ensures that .ai/ is gitignored at the project root level.
* Creates a .gitignore file if it doesn't exist, or adds the line if not already present.
*/
async ensureAiGitignored(): Promise<void> {
const gitignorePath = join(this.workingDir, ".gitignore");
const aiPattern = ".ai/";
try {
// Try to read existing .gitignore
let gitignoreContent = "";
try {
gitignoreContent = await this.fs.readFile(gitignorePath, "utf8");
} catch {
// .gitignore doesn't exist, will create it
}
// Check if .ai/ is already gitignored
const lines = gitignoreContent.split("\n").map((line) => line.trim());
const hasAiPattern = lines.some((line) => {
if (line.startsWith("#") || line === "") {
return false;
}
// Check for various .ai patterns
return line === ".ai" || line === ".ai/" || line === "/.ai" ||
line === "/.ai/" ||
line === ".ai/*" || line === "/.ai/*";
});
if (!hasAiPattern) {
// Add .ai/ to .gitignore
const newContent = gitignoreContent.trim() === ""
? aiPattern
: gitignoreContent.trim() + "\n" + aiPattern;
await this.fs.writeFile(gitignorePath, newContent + "\n");
}
} catch (error) {
// Log error but don't fail the main operation
console.warn(`Failed to ensure .ai/ is gitignored: ${error}`);
}
}
} }
+4 -6
View File
@@ -5,13 +5,11 @@
export interface JSRuntimeFS { export interface JSRuntimeFS {
// Core file operations with proper overloads for type safety // Core file operations with proper overloads for type safety
readFile(path: string): Promise<Uint8Array>; readFile(path: string): Promise<Uint8Array>;
readFile(path: string, options: 'utf8'): Promise<string>; readFile(path: string, encoding: 'utf8'): Promise<string>;
readFile(path: string, options: string): Promise<string>; readFile(path: string, encoding: string): Promise<string>;
readFile(path: string, options: { encoding: 'utf8' }): Promise<string>; readFile(path: string, encoding?: string): Promise<string | Uint8Array>;
readFile(path: string, options: { encoding: string }): Promise<string>;
readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
writeFile(path: string, data: string | Uint8Array, options?: string | { encoding?: string }): Promise<void>; writeFile(path: string, data: string | Uint8Array, encoding?: string): Promise<void>;
// readdir overloads for different return types // readdir overloads for different return types
readdir(path: string): Promise<string[]>; readdir(path: string): Promise<string[]>;
+5 -9
View File
@@ -9,18 +9,14 @@ export class LightningFSAdapter implements JSRuntimeFS {
constructor(private lightningFS: LightningFS.PromisifiedFS) {} constructor(private lightningFS: LightningFS.PromisifiedFS) {}
async readFile(path: string): Promise<Uint8Array>; async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, options: 'utf8'): Promise<string>; async readFile(path: string, encoding: 'utf8'): Promise<string>;
async readFile(path: string, options: string): Promise<string>; async readFile(path: string, encoding: string): Promise<string>;
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>; async readFile(path: string, encoding?: string): Promise<string | Uint8Array>;
async readFile(path: string, options: { encoding: string }): Promise<string>; async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
const encoding = typeof options === 'string' ? options : options?.encoding;
return this.lightningFS.readFile(path, encoding); return this.lightningFS.readFile(path, encoding);
} }
async writeFile(path: string, data: string | Uint8Array, options?: string | { encoding?: string }): Promise<void> { async writeFile(path: string, data: string | Uint8Array, encoding?: string): Promise<void> {
const encoding = typeof options === 'string' ? options : options?.encoding;
return this.lightningFS.writeFile(path, data, encoding); return this.lightningFS.writeFile(path, data, encoding);
} }
+3 -68
View File
@@ -41,19 +41,15 @@ class MockFS implements JSRuntimeFS {
private dirs: Set<string> = new Set(); private dirs: Set<string> = new Set();
async readFile(path: string): Promise<Uint8Array>; async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, options: 'utf8'): Promise<string>; async readFile(path: string, encoding: "utf8"): Promise<string>;
async readFile(path: string, options: string): Promise<string>; async readFile(path: string, encoding: string): Promise<string | Uint8Array>;
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>; async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
async readFile(path: string, options: { encoding: string }): Promise<string>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
const content = this.files.get(path); const content = this.files.get(path);
if (content === undefined) { if (content === undefined) {
const error = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException; const error = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
error.code = 'ENOENT'; error.code = 'ENOENT';
throw error; throw error;
} }
const encoding = typeof options === 'string' ? options : options?.encoding;
if (encoding === 'utf8') { if (encoding === 'utf8') {
if (typeof content === 'string') { if (typeof content === 'string') {
return content; return content;
@@ -444,67 +440,6 @@ describe('ProjectsManager', () => {
}); });
}); });
describe('cloneProject', () => {
it('should clean up project directory when clone fails', async () => {
await projectsManager.init();
// Mock git.clone to fail
const mockGit = {
clone: vi.fn().mockRejectedValue(new Error('Clone failed')),
} as Partial<import('./git').Git>;
// Replace git instance
Object.assign(projectsManager, { git: mockGit });
// Attempt to clone a project
await expect(projectsManager.cloneProject('test-project', 'https://github.com/test/repo.git'))
.rejects.toThrow('Clone failed');
// Verify that the project directory was cleaned up
const project = await projectsManager.getProject('test-project');
expect(project).toBeNull();
// Verify directory doesn't exist in filesystem
await expect(fs.stat('/projects/test-project')).rejects.toThrow('ENOENT');
});
it('should handle cleanup errors gracefully', async () => {
await projectsManager.init();
// Mock git.clone to fail
const mockGit = {
clone: vi.fn().mockRejectedValue(new Error('Clone failed')),
} as Partial<import('./git').Git>;
// Replace git instance
Object.assign(projectsManager, { git: mockGit });
// Spy on console.warn to check for cleanup warnings
const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
// Mock fs.rmdir to fail (simulate cleanup error)
const originalRmdir = fs.rmdir;
fs.rmdir = vi.fn().mockRejectedValue(new Error('Cleanup failed'));
try {
// Attempt to clone a project
await expect(projectsManager.cloneProject('test-project', 'https://github.com/test/repo.git'))
.rejects.toThrow('Clone failed');
// Should have logged a cleanup warning
expect(consoleSpy).toHaveBeenCalledWith(
'Failed to clean up directory after clone failure:',
expect.any(Error)
);
} finally {
// Restore mocks
consoleSpy.mockRestore();
fs.rmdir = originalRmdir;
}
});
});
describe('renameProject', () => { describe('renameProject', () => {
it('should rename a project directory', async () => { it('should rename a project directory', async () => {
await projectsManager.init(); await projectsManager.init();
+47 -245
View File
@@ -17,19 +17,8 @@ export interface Project {
name: string; name: string;
path: string; path: string;
lastModified: Date; lastModified: Date;
type: 'project';
} }
export interface TextChat {
id: string;
name: string;
path: string;
lastModified: Date;
type: 'chat';
}
export type ChatItem = Project | TextChat;
export interface ProjectsManagerOptions { export interface ProjectsManagerOptions {
fs: JSRuntimeFS; fs: JSRuntimeFS;
git: Git; git: Git;
@@ -39,13 +28,11 @@ export class ProjectsManager {
fs: JSRuntimeFS; fs: JSRuntimeFS;
git: Git; git: Git;
dir: string; dir: string;
chatsDir: string;
constructor(options: ProjectsManagerOptions) { constructor(options: ProjectsManagerOptions) {
this.fs = options.fs; this.fs = options.fs;
this.git = options.git; this.git = options.git;
this.dir = '/projects'; this.dir = '/projects';
this.chatsDir = '/chats';
} }
async init() { async init() {
@@ -54,16 +41,17 @@ export class ProjectsManager {
} catch { } catch {
// Directory might already exist // Directory might already exist
} }
try {
await this.fs.mkdir(this.chatsDir);
} catch {
// Directory might already exist
}
} }
async createProject(name: string, customId?: string): Promise<Project> { async createProject(name: string, customId?: string): Promise<Project> {
const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId, { depth: 1 }); const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId, { depth: 1 });
try {
await this.fs.mkdir(this.dir + `/${project.id}/.ai/history`, { recursive: true });
} catch {
// Directory might already exist
}
// Delete README.md if it exists // Delete README.md if it exists
try { try {
await this.fs.unlink(`${project.path}/README.md`); await this.fs.unlink(`${project.path}/README.md`);
@@ -87,8 +75,8 @@ export class ProjectsManager {
// Add all files to git // Add all files to git
const files = await this.getAllFiles(project.path); const files = await this.getAllFiles(project.path);
for (const file of files) { for (const file of files) {
// Skip .git directory // Skip .git directory and other hidden files we don't want to track
if (!file.startsWith('.git/')) { if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
await this.git.add({ await this.git.add({
dir: project.path, dir: project.path,
filepath: file, filepath: file,
@@ -156,12 +144,12 @@ export class ProjectsManager {
// Create project directory (or ensure it exists for overwrite) // Create project directory (or ensure it exists for overwrite)
await this.fs.mkdir(projectPath, { recursive: true }); await this.fs.mkdir(projectPath, { recursive: true });
// If overwriting, delete existing files except .git directory // If overwriting, delete existing files except .ai directory and .git directory
if (projectExists && overwrite) { if (projectExists && overwrite) {
const existingFiles = await this.getAllFiles(projectPath); const existingFiles = await this.getAllFiles(projectPath);
for (const file of existingFiles) { for (const file of existingFiles) {
// Preserve .git directory // Preserve .ai directory and .git directory
if (!file.startsWith('.git/')) { if (!file.startsWith('.ai/') && !file.startsWith('.git/')) {
try { try {
await this.fs.unlink(`${projectPath}/${file}`); await this.fs.unlink(`${projectPath}/${file}`);
} catch { } catch {
@@ -224,8 +212,8 @@ export class ProjectsManager {
if (overwrite) { if (overwrite) {
const projectFiles = await this.getAllFiles(projectPath); const projectFiles = await this.getAllFiles(projectPath);
for (const file of projectFiles) { for (const file of projectFiles) {
// Skip .git directory // Skip .git directory and .ai directory
if (!file.startsWith('.git/')) { if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
try { try {
await this.git.add({ await this.git.add({
dir: projectPath, dir: projectPath,
@@ -254,11 +242,11 @@ export class ProjectsManager {
defaultBranch: 'main', defaultBranch: 'main',
}); });
// Add all files to git // Add all files to git (excluding .ai directory)
const projectFiles = await this.getAllFiles(projectPath); const projectFiles = await this.getAllFiles(projectPath);
for (const file of projectFiles) { for (const file of projectFiles) {
// Skip .git directory // Skip .git directory and .ai directory
if (!file.startsWith('.git/')) { if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
await this.git.add({ await this.git.add({
dir: projectPath, dir: projectPath,
filepath: file, filepath: file,
@@ -277,12 +265,18 @@ export class ProjectsManager {
}); });
} }
// Create .ai/history directory
try {
await this.fs.mkdir(`${projectPath}/.ai/history`, { recursive: true });
} catch {
// Directory might already exist
}
return { return {
id, id,
name: projectName, name: projectName,
path: projectPath, path: projectPath,
lastModified: timestamp, lastModified: timestamp,
type: 'project' as const,
}; };
} catch (error) { } catch (error) {
// Clean up on error (only if this was a new project creation) // Clean up on error (only if this was a new project creation)
@@ -309,46 +303,33 @@ export class ProjectsManager {
await this.fs.mkdir(projectPath); await this.fs.mkdir(projectPath);
// Clone the repository (Git class now handles Nostr URIs automatically)
await this.git.clone({
dir: projectPath,
url: repoUrl,
singleBranch: true,
depth: options?.depth, // Use depth if provided, otherwise clone full history
});
// Get filesystem stats for timestamps
const stats = await this.fs.stat(projectPath);
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
// Automatically request persistent storage after project cloning
try { try {
// Clone the repository (Git class now handles Nostr URIs automatically) await ensurePersistentStorage();
await this.git.clone({
dir: projectPath,
url: repoUrl,
singleBranch: true,
depth: options?.depth, // Use depth if provided, otherwise clone full history
});
// Get filesystem stats for timestamps
const stats = await this.fs.stat(projectPath);
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
// Automatically request persistent storage after project cloning
try {
await ensurePersistentStorage();
} catch (error) {
// Don't fail project cloning if persistent storage request fails
console.warn('Failed to request persistent storage after project cloning:', error);
}
// Return the full project object with dynamically generated properties
return {
id,
name: this.formatProjectName(id), // Use formatted directory name
path: projectPath,
lastModified: timestamp,
type: 'project' as const,
};
} catch (error) { } catch (error) {
// Clean up the directory that was created if cloning fails // Don't fail project cloning if persistent storage request fails
try { console.warn('Failed to request persistent storage after project cloning:', error);
await this.deleteDirectory(projectPath);
} catch (cleanupError) {
// Log cleanup error but don't mask the original clone error
console.warn('Failed to clean up directory after clone failure:', cleanupError);
}
// Re-throw the original clone error
throw error;
} }
// Return the full project object with dynamically generated properties
return {
id,
name: this.formatProjectName(id), // Use formatted directory name
path: projectPath,
lastModified: timestamp,
};
} }
async getProjects(): Promise<Project[]> { async getProjects(): Promise<Project[]> {
@@ -368,7 +349,6 @@ export class ProjectsManager {
name: this.formatProjectName(dir), // Convert directory name to readable format name: this.formatProjectName(dir), // Convert directory name to readable format
path: projectPath, path: projectPath,
lastModified: modifiedDate, lastModified: modifiedDate,
type: 'project' as const,
}; };
projects.push(project); projects.push(project);
@@ -396,7 +376,6 @@ export class ProjectsManager {
name: this.formatProjectName(id), // Convert directory name to readable format name: this.formatProjectName(id), // Convert directory name to readable format
path: projectPath, path: projectPath,
lastModified: modifiedDate, lastModified: modifiedDate,
type: 'project' as const,
}; };
} }
@@ -530,7 +509,6 @@ export class ProjectsManager {
name: this.formatProjectName(newId), name: this.formatProjectName(newId),
path: newPath, path: newPath,
lastModified: timestamp, lastModified: timestamp,
type: 'project' as const,
}; };
} }
@@ -681,180 +659,4 @@ export class ProjectsManager {
return '/' + normalized.join('/'); return '/' + normalized.join('/');
} }
// Text Chat Methods
async createTextChat(name: string): Promise<TextChat> {
const id = await this.generateUniqueChatId(name);
const chatPath = `${this.chatsDir}/${id}`;
// Create the chat directory
await this.fs.mkdir(chatPath, { recursive: true });
// Create a metadata file
const metadata = {
name,
createdAt: new Date().toISOString(),
};
await this.fs.writeFile(`${chatPath}/metadata.json`, JSON.stringify(metadata, null, 2));
const stats = await this.fs.stat(chatPath);
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
return {
id,
name,
path: chatPath,
lastModified: timestamp,
type: 'chat',
};
}
async getTextChats(): Promise<TextChat[]> {
try {
const chatDirs = await this.fs.readdir(this.chatsDir);
const chats: TextChat[] = [];
for (const dir of chatDirs) {
const chatPath = `${this.chatsDir}/${dir}`;
try {
const stats = await this.fs.stat(chatPath);
if (stats.isDirectory()) {
// Try to read metadata
let name = this.formatProjectName(dir);
try {
const metadataContent = await this.fs.readFile(`${chatPath}/metadata.json`, 'utf8');
const metadata = JSON.parse(metadataContent);
name = metadata.name || name;
} catch {
// If metadata doesn't exist, use formatted directory name
}
const modifiedDate = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
const chat: TextChat = {
id: dir,
name,
path: chatPath,
lastModified: modifiedDate,
type: 'chat',
};
chats.push(chat);
}
} catch {
// Skip if we can't stat the directory
}
}
return chats.sort((a, b) => b.lastModified.getTime() - a.lastModified.getTime());
} catch {
return [];
}
}
async getTextChat(id: string): Promise<TextChat | null> {
try {
const chatPath = `${this.chatsDir}/${id}`;
const stats = await this.fs.stat(chatPath);
if (stats.isDirectory()) {
// Try to read metadata
let name = this.formatProjectName(id);
try {
const metadataContent = await this.fs.readFile(`${chatPath}/metadata.json`, 'utf8');
const metadata = JSON.parse(metadataContent);
name = metadata.name || name;
} catch {
// If metadata doesn't exist, use formatted directory name
}
const modifiedDate = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
return {
id,
name,
path: chatPath,
lastModified: modifiedDate,
type: 'chat',
};
}
return null;
} catch {
return null;
}
}
async deleteTextChat(chatId: string): Promise<void> {
const chatPath = `${this.chatsDir}/${chatId}`;
await this.deleteDirectory(chatPath);
}
async renameTextChat(oldId: string, newName: string): Promise<TextChat> {
const oldChat = await this.getTextChat(oldId);
if (!oldChat) {
throw new Error(`Chat with ID "${oldId}" does not exist`);
}
const chatPath = `${this.chatsDir}/${oldId}`;
// Update metadata with new name
const metadata = {
name: newName,
createdAt: new Date().toISOString(),
};
await this.fs.writeFile(`${chatPath}/metadata.json`, JSON.stringify(metadata, null, 2));
// Use current timestamp for modification time
const timestamp = new Date();
return {
id: oldId,
name: newName,
path: chatPath,
lastModified: timestamp,
type: 'chat',
};
}
async getAllChatItems(): Promise<ChatItem[]> {
const [projects, textChats] = await Promise.all([
this.getProjects(),
this.getTextChats(),
]);
// Add type field to projects
const projectsWithType: Project[] = projects.map(p => ({ ...p, type: 'project' as const }));
// Combine and sort by lastModified
const allItems: ChatItem[] = [...projectsWithType, ...textChats];
return allItems.sort((a, b) => b.lastModified.getTime() - a.lastModified.getTime());
}
private async generateUniqueChatId(name: string): Promise<string> {
const baseSlug = name
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
let slug = baseSlug;
let counter = 1;
while (await this.chatExists(slug)) {
slug = `${baseSlug}-${counter}`;
counter++;
}
return slug;
}
private async chatExists(id: string): Promise<boolean> {
try {
const chatPath = `${this.chatsDir}/${id}`;
await this.fs.stat(chatPath);
return true;
} catch {
return false;
}
}
} }
+16 -48
View File
@@ -8,7 +8,6 @@ import type { NUser } from '@nostrify/react/login';
import type { AIProvider } from '@/contexts/AISettingsContext'; import type { AIProvider } from '@/contexts/AISettingsContext';
import { makeSystemPrompt } from './system'; import { makeSystemPrompt } from './system';
import { NostrMetadata } from '@nostrify/nostrify'; import { NostrMetadata } from '@nostrify/nostrify';
import { MalformedToolCallError } from './errors/MalformedToolCallError';
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | { export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
role: 'assistant'; role: 'assistant';
@@ -35,7 +34,6 @@ export interface SessionState {
abortController?: AbortController; abortController?: AbortController;
totalCost?: number; // Total cost in USD for this session totalCost?: number; // Total cost in USD for this session
lastInputTokens?: number; // Input tokens from the last AI request lastInputTokens?: number; // Input tokens from the last AI request
isTextChat?: boolean; // Whether this is a text chat (no tools) vs a project chat
} }
export interface SessionManagerEvents { export interface SessionManagerEvents {
@@ -73,23 +71,20 @@ export class SessionManager {
} }
/** /**
* Create a new session for a project or text chat * Create a new session for a project
*/ */
async loadSession( async loadSession(
projectId: string, projectId: string,
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>, tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>,
customTools: Record<string, Tool<unknown>>, customTools: Record<string, Tool<unknown>>,
maxSteps?: number, maxSteps?: number
isTextChat?: boolean
): Promise<SessionState> { ): Promise<SessionState> {
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = []; let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
let sessionName = DotAI.generateSessionName(); let sessionName = DotAI.generateSessionName();
// Try to load existing history // Try to load existing history
try { try {
const workingDir = isTextChat ? `/chats/${projectId}` : `/projects/${projectId}`; const dotAI = new DotAI(this.fs, `/projects/${projectId}`);
const historyDir = isTextChat ? `${workingDir}/history` : undefined;
const dotAI = new DotAI(this.fs, workingDir, historyDir);
const lastSession = await dotAI.readLastSessionHistory(); const lastSession = await dotAI.readLastSessionHistory();
if (lastSession) { if (lastSession) {
messages = lastSession.messages; messages = lastSession.messages;
@@ -108,7 +103,6 @@ export class SessionManager {
lastActivity: new Date(), lastActivity: new Date(),
totalCost: 0, totalCost: 0,
lastInputTokens: 0, lastInputTokens: 0,
isTextChat,
...this.sessions.get(projectId), ...this.sessions.get(projectId),
messages, messages,
sessionName, sessionName,
@@ -194,6 +188,10 @@ export class SessionManager {
throw new Error('No messages in session'); throw new Error('No messages in session');
} }
// Check if last message is from user
const lastMessage = session.messages[session.messages.length - 1];
if (lastMessage.role !== 'user') return;
session.isLoading = true; session.isLoading = true;
session.abortController = new AbortController(); session.abortController = new AbortController();
session.lastActivity = new Date(); session.lastActivity = new Date();
@@ -231,9 +229,8 @@ export class SessionManager {
tool_calls: undefined tool_calls: undefined
}; };
const cwd = session.isTextChat ? `/chats/${projectId}` : `/projects/${projectId}`;
const systemPrompt = await makeSystemPrompt({ const systemPrompt = await makeSystemPrompt({
cwd, cwd: `/projects/${projectId}`,
fs: this.fs, fs: this.fs,
mode: "agent", mode: "agent",
name: "Shakespeare", name: "Shakespeare",
@@ -253,6 +250,7 @@ export class SessionManager {
model, model,
messages, messages,
tools: session.tools && Object.keys(session.tools).length > 0 ? Object.values(session.tools) : undefined, tools: session.tools && Object.keys(session.tools).length > 0 ? Object.values(session.tools) : undefined,
tool_choice: session.tools && Object.keys(session.tools).length > 0 ? 'auto' : undefined,
stream: true, stream: true,
stream_options: { stream_options: {
include_usage: true, include_usage: true,
@@ -290,7 +288,7 @@ export class SessionManager {
// LiteLLM, Z.ai, etc. use 'reasoning_content' // LiteLLM, Z.ai, etc. use 'reasoning_content'
if (delta && 'reasoning_content' in delta && typeof delta.reasoning_content === 'string') { if (delta && 'reasoning_content' in delta && typeof delta.reasoning_content === 'string') {
reasoningContent = delta.reasoning_content; reasoningContent = delta.reasoning_content;
// ollama uses 'reasoning' // ollama uses 'reasoning'
} else if (delta && 'reasoning' in delta && typeof delta.reasoning === 'string') { } else if (delta && 'reasoning' in delta && typeof delta.reasoning === 'string') {
reasoningContent = delta.reasoning; reasoningContent = delta.reasoning;
} }
@@ -303,9 +301,9 @@ export class SessionManager {
} }
if (delta?.tool_calls) { if (delta?.tool_calls) {
for (let i = 0; i < delta.tool_calls.length; i++) { for (const toolCallDelta of delta.tool_calls) {
const toolCallDelta = delta.tool_calls[i]; const index = toolCallDelta.index;
const index = toolCallDelta.index ?? i; // Fix for Gemini models if (index === undefined) continue;
accumulatedToolCalls[index] ??= { accumulatedToolCalls[index] ??= {
id: '', id: '',
@@ -343,20 +341,10 @@ export class SessionManager {
} }
} }
// Fix tool calls with empty arguments or names // Fix tool calls with empty arguments
for (const toolCall of accumulatedToolCalls) { for (const toolCall of accumulatedToolCalls) {
if (toolCall.type === 'function') { if (toolCall.type === 'function') {
toolCall.function.arguments = toolCall.function.arguments || '{}'; toolCall.function.arguments = toolCall.function.arguments || '{}';
// Log and handle empty tool names (malformed AI response)
if (!toolCall.function.name || toolCall.function.name.trim() === '') {
console.error('Malformed tool call detected: missing function name', {
projectId,
providerModel,
toolCallId: toolCall.id,
toolCall: JSON.stringify(toolCall),
});
}
} }
} }
@@ -383,28 +371,10 @@ export class SessionManager {
const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall; const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
const toolName = functionToolCall.function.name; const toolName = functionToolCall.function.name;
// Check for missing/empty tool name (malformed AI response)
if (!toolName || toolName.trim() === '') {
// Add detailed technical error to tool message for debugging
await this.addToolMessage(
projectId,
functionToolCall.id,
`Error: Malformed tool call received from AI provider (missing function name). This is likely a provider-specific issue. Tool call ID: ${functionToolCall.id}`
);
// Throw custom error to trigger Quilly UI with user-friendly message
throw new MalformedToolCallError(
'The AI provider sent an incomplete response. This may be due to a network interruption or provider issue.',
functionToolCall.id,
providerModel
);
}
const tool = session.customTools[toolName]; const tool = session.customTools[toolName];
if (!tool) { if (!tool) {
await this.addToolMessage(projectId, functionToolCall.id, `Tool "${toolName}" not found`); await this.addToolMessage(projectId, functionToolCall.id, `Tool ${toolName} not found`);
continue; continue;
} }
@@ -555,9 +525,7 @@ export class SessionManager {
if (!session) return; if (!session) return;
try { try {
const workingDir = session.isTextChat ? `/chats/${session.projectId}` : `/projects/${session.projectId}`; const dotAI = new DotAI(this.fs, `/projects/${session.projectId}`);
const historyDir = session.isTextChat ? `${workingDir}/history` : undefined;
const dotAI = new DotAI(this.fs, workingDir, historyDir);
await dotAI.setHistory(session.sessionName, session.messages); await dotAI.setHistory(session.sessionName, session.messages);
} catch (error) { } catch (error) {
console.warn('Failed to save session history:', error); console.warn('Failed to save session history:', error);
+2 -2
View File
@@ -13,11 +13,11 @@ export function createAIClient(provider: AIProvider, user?: NUser): OpenAI {
baseURL: provider.baseURL, baseURL: provider.baseURL,
apiKey: provider.apiKey ?? '', apiKey: provider.apiKey ?? '',
dangerouslyAllowBrowser: true, dangerouslyAllowBrowser: true,
defaultHeaders: provider.id === 'openrouter' ? { defaultHeaders: {
// https://openrouter.ai/docs/app-attribution // https://openrouter.ai/docs/app-attribution
'HTTP-Referer': 'https://shakespeare.diy', 'HTTP-Referer': 'https://shakespeare.diy',
'X-Title': 'Shakespeare', 'X-Title': 'Shakespeare',
} : {}, },
}; };
let openai: OpenAI; let openai: OpenAI;
-62
View File
@@ -1,62 +0,0 @@
import { describe, it, expect } from 'vitest';
import { AI_PROVIDER_PRESETS, getPresetProvider, getShakespeareProvider } from './aiProviderPresets';
describe('AI Provider Presets', () => {
it('should export preset providers array', () => {
expect(AI_PROVIDER_PRESETS).toBeDefined();
expect(Array.isArray(AI_PROVIDER_PRESETS)).toBe(true);
expect(AI_PROVIDER_PRESETS.length).toBeGreaterThan(0);
});
it('should include Shakespeare provider', () => {
const shakespeare = AI_PROVIDER_PRESETS.find(p => p.id === 'shakespeare');
expect(shakespeare).toBeDefined();
expect(shakespeare?.name).toBe('Shakespeare AI');
expect(shakespeare?.nostr).toBe(true);
});
it('should include other major providers', () => {
const providerIds = AI_PROVIDER_PRESETS.map(p => p.id);
expect(providerIds).toContain('openai');
expect(providerIds).toContain('anthropic');
expect(providerIds).toContain('openrouter');
});
it('should get preset provider by id', () => {
const openai = getPresetProvider('openai');
expect(openai).toBeDefined();
expect(openai?.name).toBe('OpenAI');
const nonExistent = getPresetProvider('non-existent');
expect(nonExistent).toBeUndefined();
});
it('should get Shakespeare provider', () => {
const shakespeare = getShakespeareProvider();
expect(shakespeare).toBeDefined();
expect(shakespeare.id).toBe('shakespeare');
expect(shakespeare.name).toBe('Shakespeare AI');
expect(shakespeare.nostr).toBe(true);
});
it('should have valid preset structure', () => {
AI_PROVIDER_PRESETS.forEach(preset => {
expect(preset.id).toBeDefined();
expect(typeof preset.id).toBe('string');
expect(preset.name).toBeDefined();
expect(typeof preset.name).toBe('string');
expect(preset.baseURL).toBeDefined();
expect(typeof preset.baseURL).toBe('string');
expect(preset.baseURL).toMatch(/^https?:\/\//);
// Optional fields
if (preset.apiKeysURL) {
expect(typeof preset.apiKeysURL).toBe('string');
expect(preset.apiKeysURL).toMatch(/^https?:\/\//);
}
if (preset.nostr !== undefined) {
expect(typeof preset.nostr).toBe('boolean');
}
});
});
});
-88
View File
@@ -1,88 +0,0 @@
export interface PresetProvider {
id: string;
name: string;
baseURL: string;
apiKeysURL?: string;
nostr?: boolean;
tosURL?: string;
}
export const AI_PROVIDER_PRESETS: PresetProvider[] = [
{
id: "shakespeare",
name: "Shakespeare AI",
baseURL: "https://ai.shakespeare.diy/v1",
tosURL: "https://ai.shakespeare.diy/terms",
nostr: true,
},
{
id: "openrouter",
name: "OpenRouter",
baseURL: "https://openrouter.ai/api/v1",
apiKeysURL: "https://openrouter.ai/settings/keys",
tosURL: "https://openrouter.ai/terms",
},
{
id: "ppq",
name: "PayPerQ",
baseURL: "https://api.ppq.ai",
apiKeysURL: "https://ppq.ai/api-docs",
tosURL: "https://ppq.ai/terms",
},
{
id: "routstr",
name: "Routstr",
baseURL: "https://api.routstr.com/v1",
apiKeysURL: "https://chat.routstr.com/",
tosURL: "https://routstr.com/terms",
},
{
id: "zai",
name: "Z.ai",
baseURL: "https://api.z.ai/api/paas/v4",
apiKeysURL: "https://z.ai/manage-apikey/apikey-list",
tosURL: "https://docs.z.ai/legal-agreement/terms-of-use",
},
{
id: "openai",
name: "OpenAI",
baseURL: "https://api.openai.com/v1",
apiKeysURL: "https://platform.openai.com/api-keys",
tosURL: "https://openai.com/policies/",
},
{
id: "anthropic",
name: "Anthropic",
baseURL: "https://api.anthropic.com/v1",
apiKeysURL: "https://console.anthropic.com/settings/keys",
tosURL: "https://www.anthropic.com/legal/",
},
{
id: "xai",
name: "xAI",
baseURL: "https://api.x.ai/v1",
apiKeysURL: "https://console.x.ai",
tosURL: "https://x.ai/legal",
},
{
id: "deepseek",
name: "Deepseek",
baseURL: "https://api.deepseek.com/v1",
apiKeysURL: "https://platform.deepseek.com/api_keys",
tosURL: "https://cdn.deepseek.com/policies/en-US/deepseek-open-platform-terms-of-service.html",
},
];
// Helper function to get a specific preset by ID
export function getPresetProvider(id: string): PresetProvider | undefined {
return AI_PROVIDER_PRESETS.find(preset => preset.id === id);
}
// Helper function to get the Shakespeare provider preset
export function getShakespeareProvider(): PresetProvider {
const shakespeare = getPresetProvider("shakespeare");
if (!shakespeare) {
throw new Error("Shakespeare provider preset not found");
}
return shakespeare;
}
-135
View File
@@ -1,135 +0,0 @@
/**
* Utility to convert ANSI color codes to HTML spans with appropriate CSS classes
*/
// ANSI color code mapping to Tailwind CSS classes
const colorMap: Record<string, string> = {
'30': 'text-black',
'31': 'text-red-500',
'32': 'text-green-500',
'33': 'text-yellow-500',
'34': 'text-blue-500',
'35': 'text-purple-500',
'36': 'text-cyan-500',
'37': 'text-gray-200',
'90': 'text-gray-400',
'91': 'text-red-400',
'92': 'text-green-400',
'93': 'text-yellow-400',
'94': 'text-blue-400',
'95': 'text-purple-400',
'96': 'text-cyan-400',
'97': 'text-white',
};
// Background color mapping
const bgColorMap: Record<string, string> = {
'40': 'bg-black',
'41': 'bg-red-500',
'42': 'bg-green-500',
'43': 'bg-yellow-500',
'44': 'bg-blue-500',
'45': 'bg-purple-500',
'46': 'bg-cyan-500',
'47': 'bg-gray-200',
};
// Style mapping
const styleMap: Record<string, string> = {
'1': 'font-bold',
'2': 'opacity-75',
'3': 'italic',
'4': 'underline',
'9': 'line-through',
};
/**
* Convert ANSI escape sequences to HTML with appropriate CSS classes
*/
export function ansiToHtml(text: string): string {
// Regular expression to match ANSI escape sequences
const ansiRegex = /\u001b\[((?:\d+;)*\d+)m/g;
// Initialize result and current style classes
let result = '';
let currentClasses: string[] = [];
// Find all matches and their positions
const matches: Array<{index: number, length: number, codes: string}> = [];
let match;
while ((match = ansiRegex.exec(text)) !== null) {
matches.push({
index: match.index,
length: match[0].length,
codes: match[1]
});
}
// If no ANSI codes found, return the original text
if (matches.length === 0) {
return text;
}
// Process the text with ANSI codes
let lastIndex = 0;
for (const match of matches) {
// Add text before this match with current styling
if (match.index > lastIndex) {
const textSegment = text.substring(lastIndex, match.index);
if (currentClasses.length > 0) {
result += `<span class="${currentClasses.join(' ')}">${textSegment}</span>`;
} else {
result += textSegment;
}
}
// Update current classes based on ANSI codes
const codes = match.codes.split(';');
for (const code of codes) {
if (code === '0') {
// Reset all styles
currentClasses = [];
} else if (colorMap[code]) {
// Remove any existing text color classes
currentClasses = currentClasses.filter(cls => !Object.values(colorMap).includes(cls));
// Add the new text color
currentClasses.push(colorMap[code]);
} else if (bgColorMap[code]) {
// Remove any existing background color classes
currentClasses = currentClasses.filter(cls => !Object.values(bgColorMap).includes(cls));
// Add the new background color
currentClasses.push(bgColorMap[code]);
} else if (styleMap[code]) {
// Add style if it doesn't exist yet
if (!currentClasses.includes(styleMap[code])) {
currentClasses.push(styleMap[code]);
}
}
}
// Update lastIndex to after this match
lastIndex = match.index + match.length;
}
// Add any remaining text
if (lastIndex < text.length) {
const textSegment = text.substring(lastIndex);
if (currentClasses.length > 0) {
result += `<span class="${currentClasses.join(' ')}">${textSegment}</span>`;
} else {
result += textSegment;
}
}
return result;
}
/**
* Check if a string contains ANSI escape sequences
*/
export function containsAnsiCodes(text: string): boolean {
return /\u001b\[(?:\d+;)*\d+m/.test(text);
}
+8 -49
View File
@@ -5,7 +5,6 @@ interface PackageLock {
[key: string]: { [key: string]: {
name?: string; name?: string;
version: string; version: string;
peerDependencies?: { [key: string]: string };
} | undefined; } | undefined;
}; };
} }
@@ -62,14 +61,6 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
} }
}); });
// Legacy (Internet Explorer) "behavior" syntax
build.onResolve({ filter: /^#default#/, namespace: "esm" }, (args) => {
return {
path: args.path,
external: true,
};
});
// Handle bare imports like "react" // Handle bare imports like "react"
build.onResolve({ filter: /^[^./].*/ }, (args) => { build.onResolve({ filter: /^[^./].*/ }, (args) => {
const packageName = args.path.startsWith("@") const packageName = args.path.startsWith("@")
@@ -78,18 +69,10 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
// Handle transitive dependency versions // Handle transitive dependency versions
const keys: string[] = []; const keys: string[] = [];
let importerPkg: string | undefined;
let importerVersion: string | undefined;
try { try {
const { pathname } = new URL(args.importer); const importerPackage = extractPackageName(args.importer);
if (/\.css$/.test(pathname)) {
return; // CSS imports don't have external dependencies
}
const result = extractPackageName(args.importer);
importerPkg = result.pkg;
importerVersion = result.version;
keys.push( keys.push(
`node_modules/${importerPkg}/node_modules/${packageName}`, `node_modules/${importerPackage}/node_modules/${packageName}`,
); );
} catch { } catch {
// fallthrough // fallthrough
@@ -106,20 +89,12 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
.find((info) => info); .find((info) => info);
const packagePath = args.path.slice(packageName.length); const packagePath = args.path.slice(packageName.length);
const version = packageInfo?.version;
let version: string | undefined; if (!version) return;
if (importerPkg === packageName && importerVersion) { const name = packageInfo.name ?? packageName;
version = importerVersion; const specifier = `${name}@${version}${packagePath}`;
} else {
version = packageInfo?.version
|| packageLock.packages[`node_modules/${importerPkg}`]?.peerDependencies?.[packageName];
}
const name = packageInfo?.name ?? packageName;
const specifier = version
? `${name}@${version}${packagePath}`
: `${name}${packagePath}`;
const url = new URL(`https://esm.sh/*${specifier}`); const url = new URL(`https://esm.sh/*${specifier}`);
@@ -156,14 +131,6 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
} }
} }
// Skip static assets
if (/\.(woff2?|ttf|otf|eot)$/.test(fullURL.pathname)) {
return {
path: fullURL.toString(),
external: true,
};
}
return { return {
path: fullURL.toString(), path: fullURL.toString(),
namespace: "esm", namespace: "esm",
@@ -207,7 +174,7 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
} }
/** Extract package name from esm.sh-style URL */ /** Extract package name from esm.sh-style URL */
function extractPackageName(esmShURL: string): { pkg?: string; version?: string } { function extractPackageName(esmShURL: string): string {
const full = new URL(esmShURL) const full = new URL(esmShURL)
.pathname .pathname
.slice(1) .slice(1)
@@ -217,15 +184,7 @@ function extractPackageName(esmShURL: string): { pkg?: string; version?: string
? full.split("/").slice(0, 2).join("/") ? full.split("/").slice(0, 2).join("/")
: full.split("/")[0]; : full.split("/")[0];
const pkg = full.startsWith("@") return full.startsWith("@")
? base.split("@").splice(0, 2).join("@") ? base.split("@").splice(0, 2).join("@")
: base.split("@")[0]; : base.split("@")[0];
let version: string | undefined;
if (full.slice(pkg.length).startsWith("@")) {
version = full.slice(pkg.length + 1).split("/")[0];
}
return { pkg, version };
} }
+12 -45
View File
@@ -1,4 +1,4 @@
import { join, dirname, extname } from "path-browserify"; import path from "path-browserify";
import type { Loader, Plugin } from "esbuild-wasm"; import type { Loader, Plugin } from "esbuild-wasm";
import type { JSRuntimeFS } from '@/lib/JSRuntime'; import type { JSRuntimeFS } from '@/lib/JSRuntime';
@@ -8,49 +8,27 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin {
name: "fs", name: "fs",
setup(build) { setup(build) {
build.onResolve({ filter: /^data:/ }, (args) => {
return {
path: args.path,
external: true,
};
});
build.onResolve({ filter: /.*/ }, async (args) => { build.onResolve({ filter: /.*/ }, async (args) => {
// Skip resolving paths from external URLs
if (/^https?:\/\//.test(args.importer)) {
return;
}
let resolved: string; let resolved: string;
if (args.path.startsWith("/")) {
resolved = args.path; if (args.path.startsWith("@/")) {
} else if (args.path.startsWith("@/")) { resolved = path.join(cwd, args.path.slice(2));
resolved = join(cwd, args.path.slice(2));
} else if (args.kind === "entry-point") { } else if (args.kind === "entry-point") {
resolved = join(cwd, args.path); resolved = path.join(cwd, args.path);
} else if (args.importer) { } else if (args.importer) {
resolved = join(dirname(args.importer), args.path); resolved = path.join(path.dirname(args.importer), args.path);
} else { } else {
return; return;
} }
// Security: prevent accessing files outside the project directory
const projectDir = join(cwd, "..");
if (resolved.startsWith("/") && !resolved.startsWith(projectDir)) {
throw new Error(`Access to files outside the project directory is not allowed: ${resolved}`);
}
// Vite query parameters https://vite.dev/guide/assets
const [cleaned, query] = resolved.split("?");
try { try {
resolved = await tryFileVariants(fs, cleaned); resolved = await tryFileVariants(fs, resolved);
} catch { } catch {
return; // Let other plugins handle this return; // Let other plugins handle this
} }
return { return {
path: resolved + (typeof query === "string" ? "?" + query : ""), path: resolved,
namespace: "fs", namespace: "fs",
}; };
}); });
@@ -58,25 +36,14 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin {
build.onLoad( build.onLoad(
{ filter: /.*/, namespace: "fs" }, { filter: /.*/, namespace: "fs" },
async (args) => { async (args) => {
const [path, query] = args.path.split("?"); const ext = path.extname(args.path).slice(1);
const params = new URLSearchParams(query);
// https://vite.dev/guide/assets.html#importing-asset-as-string if (!["ts", "tsx", "js", "jsx", "css"].includes(ext)) {
if (params.has("raw")) {
return {
contents: await fs.readFile(path, "utf8"),
loader: "text",
};
}
const ext = extname(path).slice(1);
if (!["ts", "tsx", "js", "jsx", "css", "json"].includes(ext)) {
return; return;
} }
return { return {
contents: await fs.readFile(path, "utf8"), contents: await fs.readFile(args.path, "utf8"),
loader: ext as Loader, loader: ext as Loader,
}; };
}, },
@@ -100,7 +67,7 @@ async function tryFileVariants(
// If it's a directory, try index files // If it's a directory, try index files
if (stat.isDirectory()) { if (stat.isDirectory()) {
for (const ext of extensions) { for (const ext of extensions) {
const indexFile = join(basePath, "index" + ext); const indexFile = path.join(basePath, "index" + ext);
const indexStat = await statSafe(fs, indexFile); const indexStat = await statSafe(fs, indexFile);
if (indexStat.isFile()) { if (indexStat.isFile()) {
return indexFile; return indexFile;
+16 -52
View File
@@ -9,28 +9,14 @@ vi.mock('../esbuild', () => ({
build: vi.fn(() => ({ build: vi.fn(() => ({
outputFiles: [ outputFiles: [
{ {
path: '/stdin-abc123.js', path: '/stdin.js',
contents: new Uint8Array([1, 2, 3]), contents: new Uint8Array([1, 2, 3]),
text: '',
hash: 'abc123',
}, },
{ {
path: '/stdin-def456.css', path: '/stdin.css',
contents: new Uint8Array([4, 5, 6]), contents: new Uint8Array([4, 5, 6]),
text: 'body { margin: 0; }',
hash: 'def456',
}, },
], ],
metafile: {
outputs: {
'stdin-abc123.js': {
entryPoint: 'fs:/test/project/src/main.tsx',
},
'stdin-def456.css': {
entryPoint: undefined,
},
},
},
})), })),
})), })),
})); }));
@@ -66,25 +52,9 @@ describe('buildProject', () => {
documentElement: { documentElement: {
outerHTML: '<html><head></head><body><script src="/src/main.tsx"></script></body></html>', outerHTML: '<html><head></head><body><script src="/src/main.tsx"></script></body></html>',
}, },
querySelector: vi.fn((selector: string) => { querySelector: vi.fn(() => ({
if (selector === 'meta[http-equiv="content-security-policy"]') { setAttribute: vi.fn(),
// Return null for CSP meta tag (no CSP present in test) })),
return null;
}
return {
setAttribute: vi.fn(),
getAttribute: vi.fn(),
};
}),
scripts: [
{
getAttribute: vi.fn((attr: string) => {
if (attr === 'src') return '/src/main.tsx';
return null;
}),
type: 'module',
},
],
head: { head: {
appendChild: vi.fn(), appendChild: vi.fn(),
}, },
@@ -163,13 +133,11 @@ describe('buildProject', () => {
domParser: mockDOMParser, domParser: mockDOMParser,
}); });
// Should include built files with hashed names // Should include built files
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3])); expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3]));
expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6]));
expect(result.files['index.html']).toBeDefined(); expect(result.files['index.html']).toBeDefined();
// CSS should be embedded in HTML, not as separate file
expect(Object.keys(result.files)).not.toContain('stdin-def456.css');
// Public files should be copied to filesystem, not included in files object // Public files should be copied to filesystem, not included in files object
// Verify copyFiles was called for public directory // Verify copyFiles was called for public directory
expect(mockFS.stat).toHaveBeenCalledWith('/test/project/public'); expect(mockFS.stat).toHaveBeenCalledWith('/test/project/public');
@@ -222,13 +190,11 @@ describe('buildProject', () => {
domParser: mockDOMParser, domParser: mockDOMParser,
}); });
// Should still include built files with hashed names // Should still include built files
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3])); expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3]));
expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6]));
expect(result.files['index.html']).toBeDefined(); expect(result.files['index.html']).toBeDefined();
// CSS should be embedded in HTML, not as separate file
expect(Object.keys(result.files)).not.toContain('stdin-def456.css');
// Should not include any public files in bundle // Should not include any public files in bundle
expect(Object.keys(result.files)).not.toContain('favicon.ico'); expect(Object.keys(result.files)).not.toContain('favicon.ico');
@@ -280,15 +246,13 @@ describe('buildProject', () => {
domParser: mockDOMParser, domParser: mockDOMParser,
}); });
// Should include built files with hashed names // Should include built files
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3])); expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3]));
expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6]));
expect(result.files['index.html']).toBeDefined(); expect(result.files['index.html']).toBeDefined();
// CSS should be embedded in HTML, not as separate file // Should have exactly 3 files (main.js, main.css, index.html)
expect(Object.keys(result.files)).not.toContain('stdin-def456.css'); expect(Object.keys(result.files)).toHaveLength(3);
// Should have exactly 2 files (stdin-abc123.js, index.html)
expect(Object.keys(result.files)).toHaveLength(2);
// Should try to copy public files but directory is empty // Should try to copy public files but directory is empty
expect(copyFiles).toHaveBeenCalledWith(mockFS, mockFS, '/test/project/public', '/test/project/dist'); expect(copyFiles).toHaveBeenCalledWith(mockFS, mockFS, '/test/project/public', '/test/project/dist');
+27 -87
View File
@@ -1,9 +1,6 @@
import { join } from "path-browserify";
import { getEsbuild } from "@/lib/esbuild"; import { getEsbuild } from "@/lib/esbuild";
import { copyFiles } from "@/lib/copyFiles"; import { copyFiles } from "@/lib/copyFiles";
import { addDomainToCSP } from "@/lib/csp";
import { shakespearePlugin } from "./shakespearePlugin";
import { esmPlugin } from "./esmPlugin"; import { esmPlugin } from "./esmPlugin";
import { fsPlugin } from "./fsPlugin"; import { fsPlugin } from "./fsPlugin";
@@ -34,51 +31,24 @@ async function bundle(
); );
const doc = domParser.parseFromString(indexHtmlText, "text/html"); const doc = domParser.parseFromString(indexHtmlText, "text/html");
const entryPoints: string[] = [];
const entryScripts: Record<string, HTMLScriptElement> = {};
// Find all module scripts with relative paths in index.html
for (const script of doc.scripts) {
const scriptSrc = script.getAttribute("src");
if (scriptSrc && script.type === "module" && /^[./]/.test(scriptSrc)) {
const path = join(projectPath, scriptSrc);
// Files in the public directory take precedence over source files
if (scriptSrc.startsWith("/")) {
if (await fileExists(fs, join(projectPath, "public", scriptSrc))) {
continue;
}
}
entryPoints.push(path);
entryScripts[path] = script;
}
}
// Enable Tailwind CSS if a config file is present
for (const path of ["tailwind.config.ts", "tailwind.config.js"]) {
if (await fileExists(fs, join(projectPath, path))) {
entryPoints.push(`shakespeare:${path}`);
break;
}
}
const results = await esbuild.build({ const results = await esbuild.build({
entryPoints, stdin: {
contents: `
import "@/main.tsx";
import tailwindConfig from "@/../tailwind.config.ts";
import "https://esm.sh/tailwindcss-cdn@3";
tailwind.config = tailwindConfig;
`,
loader: "tsx",
},
bundle: true, bundle: true,
write: false, write: false,
format: "esm", format: "esm",
target, target,
outdir: "/", outdir: "/",
jsx: "automatic", jsx: "automatic",
metafile: true,
sourcemap: true,
entryNames: "[name]-[hash]",
chunkNames: "[name]-[hash]",
assetNames: "[name]-[hash]",
plugins: [ plugins: [
shakespearePlugin(),
fsPlugin(fs, `${projectPath}/src`), fsPlugin(fs, `${projectPath}/src`),
esmPlugin(JSON.parse(packageLockText), target), esmPlugin(JSON.parse(packageLockText), target),
], ],
@@ -90,40 +60,18 @@ async function bundle(
const dist: Record<string, Uint8Array> = {}; const dist: Record<string, Uint8Array> = {};
for (const file of results.outputFiles) { for (const file of results.outputFiles) {
const ext = file.path.split('.').pop(); const relativePath = file.path.replace(/^\//, "");
const filename = `${file.path.slice(1)}`; if (relativePath === "stdin.js") {
const entryPoint = results.metafile.outputs[filename]?.entryPoint?.replace(/^fs:/, ''); dist["main.js"] = file.contents;
const script = entryPoint ? entryScripts[entryPoint] : null; } else if (relativePath === "stdin.css") {
dist["main.css"] = file.contents;
if (script) {
script.setAttribute("src", "/" + filename);
dist[filename] = file.contents;
} else if (ext === "js") {
const script = document.createElement("script");
script.type = "module";
script.src = "/" + filename;
doc.head.appendChild(script);
dist[filename] = file.contents;
} else if (ext === "css") {
// Embed stylesheets as Tailwind CSS styles
const style = doc.createElement("style");
style.setAttribute("type", "text/tailwindcss");
style.textContent = file.text;
doc.head.appendChild(style);
} else { } else {
dist[filename] = file.contents; dist[relativePath] = file.contents;
} }
} }
// Parse CSP and ensure esm.sh is allowed for necessary directives // Update index.html with proper script and link tags
const cspMeta = doc.querySelector("meta[http-equiv=\"content-security-policy\"]"); updateIndexHtml(doc);
if (cspMeta) {
const cspContent = cspMeta.getAttribute("content");
if (cspContent) {
const updatedCSP = updateCSPForEsmSh(cspContent);
cspMeta.setAttribute("content", updatedCSP);
}
}
const updatedHtml = "<!DOCTYPE html>\n" + doc.documentElement.outerHTML; const updatedHtml = "<!DOCTYPE html>\n" + doc.documentElement.outerHTML;
dist["index.html"] = new TextEncoder().encode(updatedHtml); dist["index.html"] = new TextEncoder().encode(updatedHtml);
@@ -206,25 +154,17 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
}; };
} }
async function fileExists(fs: JSRuntimeFS, path: string): Promise<boolean> { function updateIndexHtml(doc: Document): void {
try { const entrypoint = doc.querySelector('script[src="/src/main.tsx"]');
const stat = await fs.stat(path);
return stat.isFile(); if (!entrypoint) {
} catch { throw new Error("No entrypoint script found in index.html");
return false;
} }
}
/** Updates CSP to allow esm.sh for scripts, assets, fonts, and CSS */ entrypoint.setAttribute("src", "/main.js");
export function updateCSPForEsmSh(csp: string): string {
const esmShDirectives = [
'script-src', // For JavaScript modules
'img-src', // For images
'media-src', // For video/audio
'font-src', // For fonts
'style-src', // For CSS
'connect-src' // For fetch/XHR requests to esm.sh
];
return addDomainToCSP(csp, 'https://esm.sh', esmShDirectives); const style = doc.createElement("link");
style.setAttribute("rel", "stylesheet");
style.setAttribute("href", "/main.css");
doc.head.appendChild(style);
} }
-188
View File
@@ -1,188 +0,0 @@
import type { Plugin } from "esbuild-wasm";
/**
* Shakespeare plugin for dependency polyfills and workarounds.
* This plugin handles specific dependencies that need custom implementations
* or dummy APIs to work correctly in the browser environment.
*/
export function shakespearePlugin(): Plugin {
return {
name: "shakespeare",
setup(build) {
// Handle Tailwind CSS configuration files
build.onResolve({ filter: /^shakespeare:tailwind\.config\.(js|ts)$/ }, (args) => {
return {
path: args.path,
namespace: "shakespeare-tailwind",
};
});
build.onLoad({ filter: /.*/, namespace: "shakespeare-tailwind" }, async (args) => {
const { pathname } = new URL(args.path);
return {
contents: `
import tailwindConfig from "@/../${pathname}";
import "https://esm.sh/tailwindcss-cdn@3";
tailwind.config = tailwindConfig;
`,
loader: "js",
};
});
// Handle "sonner" imports with a dummy API
build.onResolve({ filter: /^sonner$/ }, (args) => {
return {
path: args.path,
namespace: "shakespeare-sonner",
};
});
// Provide dummy sonner implementation
build.onLoad({ filter: /.*/, namespace: "shakespeare-sonner" }, () => {
return {
contents: `
// Dummy implementation of sonner toast library
// Toast function that does nothing
const toast = (message, options) => {
console.log('[Shakespeare Sonner Mock]:', message, options);
return { id: Math.random().toString(36) };
};
// Add common toast methods
toast.success = (message, options) => {
console.log('[Shakespeare Sonner Mock] Success:', message, options);
return { id: Math.random().toString(36) };
};
toast.error = (message, options) => {
console.log('[Shakespeare Sonner Mock] Error:', message, options);
return { id: Math.random().toString(36) };
};
toast.info = (message, options) => {
console.log('[Shakespeare Sonner Mock] Info:', message, options);
return { id: Math.random().toString(36) };
};
toast.warning = (message, options) => {
console.log('[Shakespeare Sonner Mock] Warning:', message, options);
return { id: Math.random().toString(36) };
};
toast.loading = (message, options) => {
console.log('[Shakespeare Sonner Mock] Loading:', message, options);
return { id: Math.random().toString(36) };
};
toast.promise = (promise, options) => {
console.log('[Shakespeare Sonner Mock] Promise:', promise, options);
return promise;
};
toast.dismiss = (id) => {
console.log('[Shakespeare Sonner Mock] Dismiss:', id);
};
// Toaster component (dummy React component)
const Toaster = (props) => {
console.log('[Shakespeare Sonner Mock] Toaster component rendered:', props);
return null;
};
// Export both named and default exports to match sonner API
export { toast, Toaster };
export default toast;
`,
loader: "js",
};
});
// Handle "next-themes" imports with a dummy API
build.onResolve({ filter: /^next-themes$/ }, (args) => {
return {
path: args.path,
namespace: "shakespeare-next-themes",
};
});
// Provide dummy next-themes implementation
build.onLoad({ filter: /.*/, namespace: "shakespeare-next-themes" }, () => {
return {
contents: `
// Dummy implementation of next-themes
// useTheme hook that returns system theme
const useTheme = () => {
return { theme: "system" };
};
// ThemeProvider component (dummy React component)
const ThemeProvider = ({ children, ...props }) => {
console.log('[Shakespeare next-themes Mock] ThemeProvider rendered:', props);
return children;
};
// Export both named and default exports to match next-themes API
export { useTheme, ThemeProvider };
`,
loader: "js",
};
});
// Handle "virtual:pwa-register/react" imports with a dummy API
build.onResolve({ filter: /^virtual:pwa-register\/react$/ }, (args) => {
return {
path: args.path,
namespace: "shakespeare-pwa-register",
};
});
// Provide dummy PWA register implementation
build.onLoad({ filter: /.*/, namespace: "shakespeare-pwa-register" }, () => {
return {
contents: `
// Dummy implementation of virtual:pwa-register/react
// useRegisterSW hook that returns dummy functions
const useRegisterSW = (options = {}) => {
console.log('[Shakespeare PWA Mock] useRegisterSW called:', options);
return {
needRefresh: [false, () => {}],
offlineReady: [false, () => {}],
updateServiceWorker: (reloadPage) => {
console.log('[Shakespeare PWA Mock] updateServiceWorker called:', reloadPage);
if (reloadPage) {
window.location.reload();
}
},
};
};
// Export the hook
export { useRegisterSW };
`,
loader: "js",
};
});
// Add more dependency polyfills here as needed
// Example structure for future dependencies:
// build.onResolve({ filter: /^some-other-package$/ }, (args) => {
// return {
// path: args.path,
// namespace: "shakespeare-other-package",
// };
// });
//
// build.onLoad({ filter: /.*/, namespace: "shakespeare-other-package" }, () => {
// return {
// contents: `// Custom implementation for some-other-package`,
// loader: "js",
// };
// });
},
};
}
-3
View File
@@ -11,9 +11,6 @@ export interface ShellCommand {
/** Usage syntax for the command */ /** Usage syntax for the command */
usage: string; usage: string;
/** If true, this command is hidden from help and command listings (for easter eggs) */
isEasterEgg?: boolean;
/** /**
* Execute the command with the given arguments * Execute the command with the given arguments
* @param args Array of command arguments (excluding the command name itself) * @param args Array of command arguments (excluding the command name itself)
+33 -33
View File
@@ -41,41 +41,41 @@ export class CutCommand implements ShellCommand {
} else { } else {
// Read all files // Read all files
for (const file of files) { for (const file of files) {
try { try {
// Handle absolute paths // Handle absolute paths
if (file.startsWith('/') || file.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(file)) { if (file.startsWith('/') || file.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(file)) {
return createErrorResult(`${this.name}: absolute paths are not supported: ${file}`); return createErrorResult(`${this.name}: absolute paths are not supported: ${file}`);
}
const absolutePath = join(cwd, file);
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: ${file}: Is a directory`);
}
const content = await this.fs.readFile(absolutePath, 'utf8');
const fileLines = content.split('\n');
// Remove the last empty line if the file ends with a newline
if (fileLines.length > 0 && fileLines[fileLines.length - 1] === '') {
fileLines.pop();
}
lines.push(...fileLines);
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
return createErrorResult(`${this.name}: ${file}: No such file or directory`);
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
return createErrorResult(`${this.name}: ${file}: Permission denied`);
} else {
return createErrorResult(`${this.name}: ${file}: ${error.message}`);
}
} else {
return createErrorResult(`${this.name}: ${file}: Unknown error`);
}
} }
const absolutePath = join(cwd, file);
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: ${file}: Is a directory`);
}
const content = await this.fs.readFile(absolutePath, 'utf8');
const fileLines = content.split('\n');
// Remove the last empty line if the file ends with a newline
if (fileLines.length > 0 && fileLines[fileLines.length - 1] === '') {
fileLines.pop();
}
lines.push(...fileLines);
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
return createErrorResult(`${this.name}: ${file}: No such file or directory`);
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
return createErrorResult(`${this.name}: ${file}: Permission denied`);
} else {
return createErrorResult(`${this.name}: ${file}: ${error.message}`);
}
} else {
return createErrorResult(`${this.name}: ${file}: Unknown error`);
}
}
} }
} }
-6
View File
@@ -14,14 +14,12 @@ import { GitCheckoutCommand } from "./git/checkout";
import { GitRemoteCommand } from "./git/remote"; import { GitRemoteCommand } from "./git/remote";
import { GitPushCommand } from "./git/push"; import { GitPushCommand } from "./git/push";
import { GitPullCommand } from "./git/pull"; import { GitPullCommand } from "./git/pull";
import { GitFetchCommand } from "./git/fetch";
import { GitCloneCommand } from "./git/clone"; import { GitCloneCommand } from "./git/clone";
import { GitConfigCommand } from "./git/config"; import { GitConfigCommand } from "./git/config";
import { GitResetCommand } from "./git/reset"; import { GitResetCommand } from "./git/reset";
import { GitDiffCommand } from "./git/diff"; import { GitDiffCommand } from "./git/diff";
import { GitTagCommand } from "./git/tag"; import { GitTagCommand } from "./git/tag";
import { GitShowCommand } from "./git/show"; import { GitShowCommand } from "./git/show";
import { GitStashCommand } from "./git/stash";
export interface GitSubcommand { export interface GitSubcommand {
name: string; name: string;
@@ -79,14 +77,12 @@ export class GitCommand implements ShellCommand {
this.registerSubcommand(new GitRemoteCommand(subcommandOptions)); this.registerSubcommand(new GitRemoteCommand(subcommandOptions));
this.registerSubcommand(new GitPushCommand(subcommandOptions)); this.registerSubcommand(new GitPushCommand(subcommandOptions));
this.registerSubcommand(new GitPullCommand(subcommandOptions)); this.registerSubcommand(new GitPullCommand(subcommandOptions));
this.registerSubcommand(new GitFetchCommand(subcommandOptions));
this.registerSubcommand(new GitCloneCommand(subcommandOptions)); this.registerSubcommand(new GitCloneCommand(subcommandOptions));
this.registerSubcommand(new GitConfigCommand(subcommandOptions)); this.registerSubcommand(new GitConfigCommand(subcommandOptions));
this.registerSubcommand(new GitResetCommand(subcommandOptions)); this.registerSubcommand(new GitResetCommand(subcommandOptions));
this.registerSubcommand(new GitDiffCommand(subcommandOptions)); this.registerSubcommand(new GitDiffCommand(subcommandOptions));
this.registerSubcommand(new GitTagCommand(subcommandOptions)); this.registerSubcommand(new GitTagCommand(subcommandOptions));
this.registerSubcommand(new GitShowCommand(subcommandOptions)); this.registerSubcommand(new GitShowCommand(subcommandOptions));
this.registerSubcommand(new GitStashCommand(subcommandOptions));
} }
private registerSubcommand(subcommand: GitSubcommand): void { private registerSubcommand(subcommand: GitSubcommand): void {
@@ -134,7 +130,6 @@ start a working area (see also: git help tutorial)
work on the current change (see also: git help everyday) work on the current change (see also: git help everyday)
add Add file contents to the index add Add file contents to the index
reset Reset current HEAD to the specified state reset Reset current HEAD to the specified state
stash Stash the changes in a dirty working directory away
examine the history and state (see also: git help revisions) examine the history and state (see also: git help revisions)
log Show commit logs log Show commit logs
@@ -149,7 +144,6 @@ grow, mark and tweak your common history
tag Create, list, delete or verify a tag object tag Create, list, delete or verify a tag object
collaborate (see also: git help workflows) collaborate (see also: git help workflows)
fetch Download objects and refs from another repository
pull Fetch from and integrate with another repository or a local branch pull Fetch from and integrate with another repository or a local branch
push Update remote refs along with associated objects push Update remote refs along with associated objects
remote Manage set of tracked repositories remote Manage set of tracked repositories
-275
View File
@@ -1,275 +0,0 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { GitAddCommand } from './add';
import type { JSRuntimeFS } from '../../JSRuntime';
import type { Git } from '../../git';
// Mock filesystem
const createMockFS = (): JSRuntimeFS => ({
readFile: vi.fn().mockResolvedValue('mock content'),
writeFile: vi.fn().mockResolvedValue(undefined),
readdir: vi.fn().mockResolvedValue([]),
mkdir: vi.fn().mockResolvedValue(undefined),
stat: vi.fn().mockImplementation((path: string) => {
if (path.endsWith('/.git')) {
return Promise.resolve({
isDirectory: () => true,
isFile: () => false,
size: 0,
mtimeMs: Date.now(),
});
}
return Promise.resolve({
isDirectory: () => false,
isFile: () => true,
size: 100,
mtimeMs: Date.now(),
});
}),
lstat: vi.fn().mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
size: 100,
mtimeMs: Date.now(),
}),
unlink: vi.fn().mockResolvedValue(undefined),
rmdir: vi.fn().mockResolvedValue(undefined),
rename: vi.fn().mockResolvedValue(undefined),
readlink: vi.fn().mockResolvedValue('mock link'),
symlink: vi.fn().mockResolvedValue(undefined),
});
// Mock Git
const createMockGit = (): Git => ({
statusMatrix: vi.fn(),
add: vi.fn(),
remove: vi.fn(),
} as unknown as Git);
describe('GitAddCommand', () => {
let addCommand: GitAddCommand;
let mockFS: JSRuntimeFS;
let mockGit: Git;
const testCwd = '/test';
beforeEach(() => {
mockFS = createMockFS();
mockGit = createMockGit();
addCommand = new GitAddCommand({
git: mockGit,
fs: mockFS,
pwd: testCwd,
});
});
it('should have correct command properties', () => {
expect(addCommand.name).toBe('add');
expect(addCommand.description).toBe('Add file contents to the index');
expect(addCommand.usage).toBe('git add [--all | -A] [--] [<pathspec>...]');
});
it('should return error when not in a git repository', async () => {
// Mock stat to throw error for .git directory
vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT'));
const result = await addCommand.execute(['file.txt']);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('fatal: not a git repository');
});
it('should return error when no files specified', async () => {
const result = await addCommand.execute([]);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('Nothing specified, nothing added');
expect(result.stderr).toContain('Maybe you wanted to say \'git add .\'?');
});
it('should add all modified files with --all flag', async () => {
// Mock status matrix with modified and untracked files
// [filepath, headStatus, workdirStatus, stageStatus]
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
['modified.txt', 1, 2, 1], // Modified file (not staged)
['untracked.txt', 0, 2, 0], // Untracked file
['unchanged.txt', 1, 1, 1], // Unchanged file
['staged.txt', 1, 2, 2], // Already staged file
]);
const result = await addCommand.execute(['--all']);
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe(''); // Git add is silent on success
// Should add modified and untracked files, but not unchanged or already staged
expect(mockGit.add).toHaveBeenCalledWith({
dir: testCwd,
filepath: 'modified.txt',
});
expect(mockGit.add).toHaveBeenCalledWith({
dir: testCwd,
filepath: 'untracked.txt',
});
expect(mockGit.add).toHaveBeenCalledTimes(2);
});
it('should handle deleted files with --all flag', async () => {
// Mock status matrix with deleted file
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
['deleted.txt', 1, 0, 1], // Deleted file (not staged)
]);
const result = await addCommand.execute(['--all']);
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
// Should remove the deleted file
expect(mockGit.remove).toHaveBeenCalledWith({
dir: testCwd,
filepath: 'deleted.txt',
});
expect(mockGit.remove).toHaveBeenCalledTimes(1);
});
it('should add specific file', async () => {
const result = await addCommand.execute(['file.txt']);
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
expect(mockGit.add).toHaveBeenCalledWith({
dir: testCwd,
filepath: 'file.txt',
});
});
it('should handle git add . (current directory)', async () => {
// Mock status matrix with various files
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
['file1.txt', 1, 2, 1], // Modified file
['file2.txt', 0, 2, 0], // Untracked file
['deleted.txt', 1, 0, 1], // Deleted file
]);
const result = await addCommand.execute(['.']);
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
// Should add modified and untracked files
expect(mockGit.add).toHaveBeenCalledWith({
dir: testCwd,
filepath: 'file1.txt',
});
expect(mockGit.add).toHaveBeenCalledWith({
dir: testCwd,
filepath: 'file2.txt',
});
// Should remove deleted file
expect(mockGit.remove).toHaveBeenCalledWith({
dir: testCwd,
filepath: 'deleted.txt',
});
});
it('should reject absolute paths', async () => {
const result = await addCommand.execute(['/absolute/path/file.txt']);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('absolute paths are not supported');
});
it('should handle non-existent files', async () => {
// Mock stat to throw error for non-existent file
vi.mocked(mockFS.stat).mockImplementation((path: string) => {
if (path.endsWith('/.git')) {
return Promise.resolve({
isDirectory: () => true,
isFile: () => false,
size: 0,
mtimeMs: Date.now(),
});
}
if (path.includes('nonexistent')) {
throw new Error('ENOENT');
}
return Promise.resolve({
isDirectory: () => false,
isFile: () => true,
size: 100,
mtimeMs: Date.now(),
});
});
// Mock git.remove to also throw error (file doesn't exist in git either)
vi.mocked(mockGit.remove).mockRejectedValueOnce(new Error('File not found'));
const result = await addCommand.execute(['nonexistent.txt']);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('pathspec \'nonexistent.txt\' did not match any files');
});
it('should handle -A flag (same as --all)', async () => {
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
['modified.txt', 1, 2, 1], // Modified file
]);
const result = await addCommand.execute(['-A']);
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
expect(mockGit.add).toHaveBeenCalledWith({
dir: testCwd,
filepath: 'modified.txt',
});
});
it('should handle mixed options and paths', async () => {
// Mock status matrix for --all to work
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
['modified.txt', 1, 2, 1], // Modified file
]);
const result = await addCommand.execute(['--all', 'specific.txt']);
expect(result.exitCode).toBe(0);
// When --all is specified, it should ignore specific paths and add all files
expect(mockGit.statusMatrix).toHaveBeenCalled();
});
it('should handle double dash separator', async () => {
const result = await addCommand.execute(['--', 'file.txt']);
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
expect(mockGit.add).toHaveBeenCalledWith({
dir: testCwd,
filepath: 'file.txt',
});
});
it('should continue with other files if one fails', async () => {
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
['good.txt', 1, 2, 1], // This should succeed
['bad.txt', 1, 2, 1], // This will fail
]);
// Mock git.add to fail for bad.txt but succeed for good.txt
vi.mocked(mockGit.add).mockImplementation(({ filepath }) => {
if (filepath === 'bad.txt') {
throw new Error('Permission denied');
}
return Promise.resolve();
});
const result = await addCommand.execute(['--all']);
expect(result.exitCode).toBe(0); // Should still succeed overall
expect(mockGit.add).toHaveBeenCalledTimes(2);
});
});
+39 -20
View File
@@ -77,22 +77,27 @@ export class GitAddCommand implements GitSubcommand {
dir: this.pwd, dir: this.pwd,
}); });
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) { let addedCount = 0;
let removedCount = 0;
for (const [filepath, headStatus, workdirStatus] of statusMatrix) {
try { try {
if (workdirStatus === 0 && headStatus === 1) { if (workdirStatus === 0 && headStatus === 1) {
// File was deleted in working directory // File was deleted
await this.git.remove({ await this.git.remove({
dir: this.pwd, dir: this.pwd,
filepath, filepath,
}); });
} else if (workdirStatus === 2 && stageStatus !== 2) { removedCount++;
// File exists and has changes that aren't staged yet } else if (workdirStatus === 1) {
// File exists (new or modified)
await this.git.add({ await this.git.add({
dir: this.pwd, dir: this.pwd,
filepath, filepath,
}); });
addedCount++;
} }
} catch { } catch {
// Continue with other files if one fails // Continue with other files if one fails
@@ -100,8 +105,19 @@ export class GitAddCommand implements GitSubcommand {
} }
} }
// Git add is typically silent on success, like real git const messages: string[] = [];
return createSuccessResult(''); if (addedCount > 0) {
messages.push(`Added ${addedCount} file${addedCount !== 1 ? 's' : ''}`);
}
if (removedCount > 0) {
messages.push(`Removed ${removedCount} file${removedCount !== 1 ? 's' : ''}`);
}
if (messages.length === 0) {
return createSuccessResult('');
}
return createSuccessResult(messages.join(', ') + '\n');
} catch (error) { } catch (error) {
return createErrorResult(`Failed to add all files: ${error instanceof Error ? error.message : 'Unknown error'}`); return createErrorResult(`Failed to add all files: ${error instanceof Error ? error.message : 'Unknown error'}`);
@@ -117,24 +133,24 @@ export class GitAddCommand implements GitSubcommand {
if (path === '.') { if (path === '.') {
// Add current directory (all files in it) // Add current directory (all files in it)
const statusMatrix = await this.git.statusMatrix({ const statusMatrix = await this.git.statusMatrix({
dir: this.pwd, dir: this.pwd,
}); });
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) { for (const [filepath, headStatus, workdirStatus] of statusMatrix) {
try { try {
if (workdirStatus === 0 && headStatus === 1) { if (workdirStatus === 0 && headStatus === 1) {
// File was deleted in working directory // File was deleted
await this.git.remove({ await this.git.remove({
dir: this.pwd, dir: this.pwd,
filepath, filepath,
}); });
addedFiles.push(filepath); addedFiles.push(filepath);
} else if (workdirStatus === 2 && stageStatus !== 2) { } else if (workdirStatus === 1) {
// File exists and has changes that aren't staged yet // File exists
await this.git.add({ await this.git.add({
dir: this.pwd, dir: this.pwd,
filepath, filepath,
}); });
@@ -163,7 +179,7 @@ export class GitAddCommand implements GitSubcommand {
} else { } else {
// Add single file // Add single file
await this.git.add({ await this.git.add({
dir: this.pwd, dir: this.pwd,
filepath: path, filepath: path,
}); });
@@ -173,7 +189,7 @@ export class GitAddCommand implements GitSubcommand {
// Check if it's a deleted file // Check if it's a deleted file
try { try {
await this.git.remove({ await this.git.remove({
dir: this.pwd, dir: this.pwd,
filepath: path, filepath: path,
}); });
@@ -192,8 +208,11 @@ export class GitAddCommand implements GitSubcommand {
return createErrorResult(errors.join('\n')); return createErrorResult(errors.join('\n'));
} }
// Git add is typically silent on success, like real git if (addedFiles.length === 0) {
return createSuccessResult(''); return createSuccessResult('');
}
return createSuccessResult(`Added ${addedFiles.length} file${addedFiles.length !== 1 ? 's' : ''}\n`);
} }
private async addDirectory(dirPath: string, addedFiles: string[]): Promise<void> { private async addDirectory(dirPath: string, addedFiles: string[]): Promise<void> {
@@ -212,7 +231,7 @@ export class GitAddCommand implements GitSubcommand {
} else { } else {
try { try {
await this.git.add({ await this.git.add({
dir: this.pwd, dir: this.pwd,
filepath: entryPath, filepath: entryPath,
}); });
-230
View File
@@ -1,230 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { GitCommitCommand } from './commit';
import type { Git } from '../../git';
import type { JSRuntimeFS } from '../../JSRuntime';
describe('GitCommitCommand', () => {
let commitCommand: GitCommitCommand;
let mockGit: Partial<Git>;
let mockFS: Partial<JSRuntimeFS>;
const mockPwd = '/projects/test';
beforeEach(() => {
// Mock the filesystem
mockFS = {
stat: vi.fn().mockResolvedValue({}),
};
// Mock Git methods
mockGit = {
statusMatrix: vi.fn().mockResolvedValue([
// filepath, HEAD status, workdir status, stage status
['file1.txt', 1, 2, 1], // modified in workdir
['file2.txt', 1, 1, 2], // modified in index
['file3.txt', 0, 2, 2], // new file
['file4.txt', 1, 0, 1], // deleted file
]),
currentBranch: vi.fn().mockResolvedValue('main'),
resolveRef: vi.fn().mockResolvedValue('headcommit'),
log: vi.fn().mockResolvedValue([
{
oid: 'headcommit',
commit: {
message: 'Previous commit',
parent: ['parentcommit'],
tree: 'tree1',
author: {
name: 'Test User',
email: '[email protected]',
timestamp: 1600000000,
},
},
},
{
oid: 'parentcommit',
commit: {
message: 'Parent commit',
parent: [],
tree: 'tree2',
author: {
name: 'Test User',
email: '[email protected]',
timestamp: 1599000000,
},
},
},
]),
getConfig: vi.fn().mockImplementation(({ path }) => {
if (path === 'user.name') return Promise.resolve('Test User');
if (path === 'user.email') return Promise.resolve('[email protected]');
return Promise.resolve(null);
}),
commit: vi.fn().mockResolvedValue('newcommit'),
add: vi.fn().mockResolvedValue(undefined),
remove: vi.fn().mockResolvedValue(undefined),
};
// Create the command instance with mocks
commitCommand = new GitCommitCommand({
git: mockGit as Git,
fs: mockFS as JSRuntimeFS,
pwd: mockPwd,
});
});
it('should commit with a message', async () => {
const result = await commitCommand.execute(['-m', 'Test commit']);
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
dir: mockPwd,
message: 'Test commit',
}));
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('Test commit');
});
it('should fail without a message', async () => {
const result = await commitCommand.execute([]);
expect(mockGit.commit).not.toHaveBeenCalled();
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('Aborting commit due to empty commit message');
});
it('should handle --amend flag', async () => {
const result = await commitCommand.execute(['--amend', '-m', 'Amended commit']);
expect(mockGit.log).toHaveBeenCalledWith({
dir: mockPwd,
depth: 2,
});
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
dir: mockPwd,
message: 'Amended commit',
parent: ['parentcommit'],
}));
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('Amended commit');
});
it('should handle --amend flag without message', async () => {
const result = await commitCommand.execute(['--amend']);
expect(mockGit.log).toHaveBeenCalledWith({
dir: mockPwd,
depth: 1,
});
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
dir: mockPwd,
message: 'Previous commit',
}));
expect(result.exitCode).toBe(0);
});
it('should handle -a flag to stage all tracked modified files', async () => {
const result = await commitCommand.execute(['-a', '-m', 'Commit with auto-stage']);
// Should call add for the modified tracked file
expect(mockGit.add).toHaveBeenCalledWith({
dir: mockPwd,
filepath: 'file1.txt',
});
// Should not call add for already staged files
expect(mockGit.add).not.toHaveBeenCalledWith({
dir: mockPwd,
filepath: 'file2.txt',
});
// Should call remove for deleted files
expect(mockGit.remove).toHaveBeenCalledWith({
dir: mockPwd,
filepath: 'file4.txt',
});
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
dir: mockPwd,
message: 'Commit with auto-stage',
}));
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('Commit with auto-stage');
});
it('should handle -am flag for combined auto-stage and message', async () => {
const result = await commitCommand.execute(['-am', 'Combined flag commit']);
// Should call add for the modified tracked file
expect(mockGit.add).toHaveBeenCalledWith({
dir: mockPwd,
filepath: 'file1.txt',
});
// Should call remove for deleted files
expect(mockGit.remove).toHaveBeenCalledWith({
dir: mockPwd,
filepath: 'file4.txt',
});
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
dir: mockPwd,
message: 'Combined flag commit',
}));
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('Combined flag commit');
});
it('should handle --allow-empty flag', async () => {
// Mock empty status
mockGit.statusMatrix = vi.fn().mockResolvedValue([]);
const result = await commitCommand.execute(['--allow-empty', '-m', 'Empty commit']);
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
dir: mockPwd,
message: 'Empty commit',
}));
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('Empty commit');
});
it('should fail if there are no staged changes', async () => {
// Mock status with only unstaged changes
mockGit.statusMatrix = vi.fn().mockResolvedValue([
['file1.txt', 1, 2, 1], // modified in workdir only
]);
const result = await commitCommand.execute(['-m', 'Should fail']);
expect(mockGit.commit).not.toHaveBeenCalled();
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('nothing to commit');
});
it('should handle not being in a git repository', async () => {
mockFS.stat = vi.fn().mockRejectedValue(new Error('Not a directory'));
const result = await commitCommand.execute(['-m', 'Test commit']);
expect(mockGit.commit).not.toHaveBeenCalled();
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('not a git repository');
});
});
+3 -51
View File
@@ -7,7 +7,7 @@ import type { Git } from "../../git";
export class GitCommitCommand implements GitSubcommand { export class GitCommitCommand implements GitSubcommand {
name = 'commit'; name = 'commit';
description = 'Record changes to the repository'; description = 'Record changes to the repository';
usage = 'git commit [-m <msg>] [-a | --all] [-am <msg>] [--amend] [--allow-empty]'; usage = 'git commit [-m <msg>] [--amend] [--allow-empty]';
private git: Git; private git: Git;
private fs: JSRuntimeFS; private fs: JSRuntimeFS;
@@ -33,11 +33,6 @@ export class GitCommitCommand implements GitSubcommand {
if (!message && !options.amend) { if (!message && !options.amend) {
return createErrorResult('Aborting commit due to empty commit message.'); return createErrorResult('Aborting commit due to empty commit message.');
} }
// If -a flag is provided, stage all tracked files with modifications
if (options.addAll) {
await this.stageTrackedChanges();
}
// Get current status // Get current status
const statusMatrix = await this.git.statusMatrix({ const statusMatrix = await this.git.statusMatrix({
@@ -174,46 +169,11 @@ export class GitCommitCommand implements GitSubcommand {
} }
} }
/**
* Stage all tracked files with modifications
* This is used when the -a flag is provided
*/
private async stageTrackedChanges(): Promise<void> {
try {
// Get the status matrix
const statusMatrix = await this.git.statusMatrix({
dir: this.pwd,
});
// Process each file based on its status
for (const [filepath, headStatus, workdirStatus] of statusMatrix) {
// Only process tracked files (headStatus === 1) with changes
if (headStatus === 1 && workdirStatus !== headStatus) {
if (workdirStatus === 0) {
// File was deleted, use remove
await this.git.remove({
dir: this.pwd,
filepath,
});
} else {
// File was modified, use add
await this.git.add({
dir: this.pwd,
filepath,
});
}
}
}
} catch (error) {
throw new Error(`Failed to stage tracked changes: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private parseArgs(args: string[]): { private parseArgs(args: string[]): {
options: { amend: boolean; allowEmpty: boolean; addAll: boolean }; options: { amend: boolean; allowEmpty: boolean };
message?: string message?: string
} { } {
const options = { amend: false, allowEmpty: false, addAll: false }; const options = { amend: false, allowEmpty: false };
let message: string | undefined; let message: string | undefined;
for (let i = 0; i < args.length; i++) { for (let i = 0; i < args.length; i++) {
@@ -232,14 +192,6 @@ export class GitCommitCommand implements GitSubcommand {
options.amend = true; options.amend = true;
} else if (arg === '--allow-empty') { } else if (arg === '--allow-empty') {
options.allowEmpty = true; options.allowEmpty = true;
} else if (arg === '-a' || arg === '--all') {
options.addAll = true;
} else if (arg === '-am') {
options.addAll = true;
if (i + 1 < args.length) {
message = args[i + 1];
i++; // Skip next argument as it's the message
}
} }
} }
-202
View File
@@ -1,202 +0,0 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { GitDiffCommand } from './diff';
import type { GitSubcommandOptions } from '../git';
import type { Git } from '../../git';
import type { JSRuntimeFS } from '../../JSRuntime';
// Mock implementations
const mockGit = {
statusMatrix: async () => [
// [filepath, headStatus, workdirStatus, stageStatus]
['modified.txt', 1, 2, 1], // Modified in working dir
['staged.txt', 1, 1, 2], // Modified in stage
['new.txt', 0, 2, 0], // Untracked file
['deleted.txt', 1, 0, 1], // Deleted in working dir
],
readBlob: async ({ filepath }: { filepath: string }) => {
const content = {
'modified.txt': 'original content\nline 2',
'staged.txt': 'original staged content',
'deleted.txt': 'deleted file content',
}[filepath] || '';
return { blob: new TextEncoder().encode(content) };
},
log: async () => [],
} as unknown as Git;
const mockFS = {
stat: async (path: string) => {
if (path.endsWith('/.git')) {
return { isDirectory: () => true };
}
throw new Error('File not found');
},
readFile: async (path: string) => {
const filename = path.split('/').pop();
const content = {
'modified.txt': 'modified content\nline 2\nnew line',
'staged.txt': 'staged content modified',
'new.txt': 'this is a new file',
// deleted.txt is not in working dir
}[filename || ''];
if (!content) {
throw new Error('File not found');
}
return content;
},
} as unknown as JSRuntimeFS;
const mockOptions: GitSubcommandOptions = {
git: mockGit,
fs: mockFS,
pwd: '/test/repo',
};
describe('GitDiffCommand', () => {
let command: GitDiffCommand;
beforeEach(() => {
command = new GitDiffCommand(mockOptions);
});
describe('parseArgs', () => {
type ParseArgsResult = {
commits: string[];
paths: string[];
options: { cached: boolean; staged: boolean };
};
it('should parse no arguments correctly', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs([]);
expect(result).toEqual({
commits: [],
paths: [],
options: { cached: false, staged: false },
});
});
it('should parse --cached option', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--cached']);
expect(result).toEqual({
commits: [],
paths: [],
options: { cached: true, staged: true },
});
});
it('should parse commits and paths', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['HEAD~1', 'HEAD', '--', 'file.txt']);
expect(result).toEqual({
commits: ['HEAD~1', 'HEAD'],
paths: ['file.txt'],
options: { cached: false, staged: false },
});
});
});
describe('execute', () => {
it('should fail when not in a git repository', async () => {
const commandWithoutGit = new GitDiffCommand({
...mockOptions,
fs: {
stat: async () => {
throw new Error('File not found');
},
} as unknown as JSRuntimeFS,
});
const result = await commandWithoutGit.execute([]);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('fatal: not a git repository');
});
it('should show working directory diff for modified files', async () => {
const result = await command.execute([]);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('diff --git a/modified.txt b/modified.txt');
expect(result.stdout).toContain('--- a/modified.txt');
expect(result.stdout).toContain('+++ b/modified.txt');
expect(result.stdout).toContain('-original content');
expect(result.stdout).toContain('+modified content');
expect(result.stdout).toContain('+new line');
});
it('should NOT show untracked files in diff', async () => {
const result = await command.execute([]);
expect(result.exitCode).toBe(0);
// Untracked files should not appear in git diff output
expect(result.stdout).not.toContain('diff --git a/new.txt b/new.txt');
expect(result.stdout).not.toContain('new file mode 100644');
expect(result.stdout).not.toContain('+this is a new file');
});
it('should show deleted files in diff', async () => {
const result = await command.execute([]);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('diff --git a/deleted.txt b/deleted.txt');
expect(result.stdout).toContain('deleted file mode 100644');
expect(result.stdout).toContain('--- a/deleted.txt');
expect(result.stdout).toContain('+++ /dev/null');
expect(result.stdout).toContain('-deleted file content');
});
it('should show staged diff with --cached option', async () => {
const result = await command.execute(['--cached']);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('diff --git a/staged.txt b/staged.txt');
expect(result.stdout).toContain('--- a/staged.txt');
expect(result.stdout).toContain('+++ b/staged.txt');
});
it('should show newly added files in staged diff', async () => {
// Test with a file that was added to the index (new file staged)
const commandWithStagedNew = new GitDiffCommand({
...mockOptions,
git: {
...mockGit,
statusMatrix: async () => [
['new-staged.txt', 0, 1, 2], // New file added to stage
],
} as unknown as Git,
});
const result = await commandWithStagedNew.execute(['--cached']);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('diff --git a/new-staged.txt b/new-staged.txt');
expect(result.stdout).toContain('new file mode 100644');
expect(result.stdout).toContain('--- /dev/null');
expect(result.stdout).toContain('+++ b/new-staged.txt');
});
it('should return empty output when no changes', async () => {
const commandWithNoChanges = new GitDiffCommand({
...mockOptions,
git: {
...mockGit,
statusMatrix: async () => [],
} as unknown as Git,
});
const result = await commandWithNoChanges.execute([]);
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
});
it('should filter by path when specified', async () => {
const result = await command.execute(['--', 'modified.txt']);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('diff --git a/modified.txt b/modified.txt');
expect(result.stdout).not.toContain('new.txt');
expect(result.stdout).not.toContain('deleted.txt');
});
});
});
+44 -71
View File
@@ -91,13 +91,10 @@ export class GitDiffCommand implements GitSubcommand {
// Filter for files with working directory changes // Filter for files with working directory changes
// Status matrix: [filepath, headStatus, workdirStatus, stageStatus] // Status matrix: [filepath, headStatus, workdirStatus, stageStatus]
// 0 = absent, 1 = same as previous stage, 2 = different from previous stage // 0 = absent, 1 = present, 2 = modified
const changedFiles = statusMatrix.filter(([filepath, _headStatus, workdirStatus, stageStatus]) => { const changedFiles = statusMatrix.filter(([filepath, _headStatus, workdirStatus, stageStatus]) => {
// Show files that have working directory changes (differ from index) // Show files that differ between index and working directory
// Exclude untracked files - git diff only shows changes to tracked files const hasWorkingDirChanges = stageStatus !== workdirStatus;
const hasWorkingDirChanges = (stageStatus !== workdirStatus && workdirStatus === 2 && stageStatus !== 0) ||
(stageStatus === 2 && workdirStatus === 0) ||
(stageStatus === 1 && workdirStatus === 0);
if (paths.length > 0) { if (paths.length > 0) {
return hasWorkingDirChanges && paths.some(path => filepath.includes(path)); return hasWorkingDirChanges && paths.some(path => filepath.includes(path));
@@ -113,87 +110,79 @@ export class GitDiffCommand implements GitSubcommand {
for (const [filepath, _headStatus, workdirStatus, stageStatus] of changedFiles) { for (const [filepath, _headStatus, workdirStatus, stageStatus] of changedFiles) {
try { try {
// Get staged/index content // Get staged content (index)
let indexContent = ''; let stagedContent = '';
if (stageStatus === 1 || stageStatus === 2) { if (stageStatus === 1) {
try { try {
// For files in the index, read from HEAD as the baseline // Try to read from HEAD first as a fallback for staged content
// This represents the last committed version for comparison
const headBlob = await this.git.readBlob({ const headBlob = await this.git.readBlob({
dir: this.pwd, dir: this.pwd,
oid: 'HEAD', oid: 'HEAD',
filepath, filepath,
}); });
indexContent = new TextDecoder().decode(headBlob.blob); stagedContent = new TextDecoder().decode(headBlob.blob);
} catch { } catch {
// File might be new or not in HEAD // File might be new
indexContent = ''; stagedContent = '';
} }
} }
// Get working directory content // Get working directory content
let workdirContent = ''; let workdirContent = '';
if (workdirStatus === 2) { if (workdirStatus === 1) {
try { try {
workdirContent = await this.fs.readFile(`${this.pwd}/${filepath}`, 'utf8'); workdirContent = await this.fs.readFile(`${this.pwd}/${filepath}`, 'utf8');
} catch { } catch {
// File might be deleted // File might be deleted
workdirContent = ''; workdirContent = '';
} }
} else if (workdirStatus === 0) {
// File is deleted in working directory
workdirContent = '';
} }
// Skip if contents are identical // Skip if contents are identical
if (indexContent === workdirContent) { if (stagedContent === workdirContent) {
continue; continue;
} }
// Generate diff header // Generate diff header
diffLines.push(`diff --git a/${filepath} b/${filepath}`); diffLines.push(`diff --git a/${filepath} b/${filepath}`);
if (workdirStatus === 0 && (stageStatus === 1 || stageStatus === 2)) { if (stageStatus === 0 && workdirStatus === 1) {
// New untracked file
diffLines.push('new file mode 100644');
diffLines.push(`index 0000000..${this.getShortHash(workdirContent)}`);
diffLines.push('--- /dev/null');
diffLines.push(`+++ b/${filepath}`);
} else if (stageStatus === 1 && workdirStatus === 0) {
// Deleted file // Deleted file
diffLines.push('deleted file mode 100644'); diffLines.push('deleted file mode 100644');
diffLines.push(`index ${this.getShortHash(indexContent)}..0000000`); diffLines.push(`index ${this.getShortHash(stagedContent)}..0000000`);
diffLines.push(`--- a/${filepath}`); diffLines.push(`--- a/${filepath}`);
diffLines.push('+++ /dev/null'); diffLines.push('+++ /dev/null');
} else { } else {
// Modified file // Modified file
diffLines.push(`index ${this.getShortHash(indexContent)}..${this.getShortHash(workdirContent)} 100644`); diffLines.push(`index ${this.getShortHash(stagedContent)}..${this.getShortHash(workdirContent)} 100644`);
diffLines.push(`--- a/${filepath}`); diffLines.push(`--- a/${filepath}`);
diffLines.push(`+++ b/${filepath}`); diffLines.push(`+++ b/${filepath}`);
} }
// Generate unified diff // Generate simple unified diff
const indexLines = indexContent.split('\n'); const stagedLines = stagedContent.split('\n');
const workdirLines = workdirContent.split('\n'); const workdirLines = workdirContent.split('\n');
// Simple hunk header // Simple hunk header
diffLines.push(`@@ -1,${indexLines.length} +1,${workdirLines.length} @@`); diffLines.push(`@@ -1,${stagedLines.length} +1,${workdirLines.length} @@`);
// Simple line-by-line diff // Show all old lines as removed
const maxLines = Math.max(indexLines.length, workdirLines.length); for (const line of stagedLines) {
for (let i = 0; i < maxLines; i++) { if (line || stagedLines.length > 0) {
const oldLine = indexLines[i]; diffLines.push(`-${line}`);
const newLine = workdirLines[i]; }
}
if (oldLine !== undefined && newLine !== undefined) { // Show all new lines as added
if (oldLine === newLine) { for (const line of workdirLines) {
// Unchanged line (show context) if (line || workdirLines.length > 0) {
diffLines.push(` ${oldLine}`); diffLines.push(`+${line}`);
} else {
// Changed line
diffLines.push(`-${oldLine}`);
diffLines.push(`+${newLine}`);
}
} else if (oldLine !== undefined) {
// Removed line
diffLines.push(`-${oldLine}`);
} else if (newLine !== undefined) {
// Added line
diffLines.push(`+${newLine}`);
} }
} }
@@ -259,9 +248,7 @@ export class GitDiffCommand implements GitSubcommand {
// Filter for files with staged changes (index differs from HEAD) // Filter for files with staged changes (index differs from HEAD)
const stagedFiles = statusMatrix.filter(([filepath, headStatus, _workdirStatus, stageStatus]) => { const stagedFiles = statusMatrix.filter(([filepath, headStatus, _workdirStatus, stageStatus]) => {
const hasStagedChanges = (headStatus === 0 && stageStatus === 2) || // Added to stage const hasStagedChanges = headStatus !== stageStatus;
(headStatus === 1 && stageStatus === 0) || // Deleted from stage
(headStatus === 1 && stageStatus === 2); // Modified in stage
if (paths.length > 0) { if (paths.length > 0) {
return hasStagedChanges && paths.some(path => filepath.includes(path)); return hasStagedChanges && paths.some(path => filepath.includes(path));
@@ -294,7 +281,7 @@ export class GitDiffCommand implements GitSubcommand {
// Get staged content (approximated by working directory for now) // Get staged content (approximated by working directory for now)
let stagedContent = ''; let stagedContent = '';
if (stageStatus === 1 || stageStatus === 2) { if (stageStatus === 1) {
try { try {
stagedContent = await this.fs.readFile(`${this.pwd}/${filepath}`, 'utf8'); stagedContent = await this.fs.readFile(`${this.pwd}/${filepath}`, 'utf8');
} catch { } catch {
@@ -305,7 +292,7 @@ export class GitDiffCommand implements GitSubcommand {
// Generate diff header // Generate diff header
diffLines.push(`diff --git a/${filepath} b/${filepath}`); diffLines.push(`diff --git a/${filepath} b/${filepath}`);
if (headStatus === 0 && stageStatus === 2) { if (headStatus === 0 && stageStatus === 1) {
// New file staged // New file staged
diffLines.push('new file mode 100644'); diffLines.push('new file mode 100644');
diffLines.push(`index 0000000..${this.getShortHash(stagedContent)}`); diffLines.push(`index 0000000..${this.getShortHash(stagedContent)}`);
@@ -330,28 +317,14 @@ export class GitDiffCommand implements GitSubcommand {
diffLines.push(`@@ -1,${headLines.length} +1,${stagedLines.length} @@`); diffLines.push(`@@ -1,${headLines.length} +1,${stagedLines.length} @@`);
// Simple line-by-line diff // Show removed lines
const maxLines = Math.max(headLines.length, stagedLines.length); for (const line of headLines) {
for (let i = 0; i < maxLines; i++) { diffLines.push(`-${line}`);
const oldLine = headLines[i]; }
const newLine = stagedLines[i];
if (oldLine !== undefined && newLine !== undefined) { // Show added lines
if (oldLine === newLine) { for (const line of stagedLines) {
// Unchanged line (show context) diffLines.push(`+${line}`);
diffLines.push(` ${oldLine}`);
} else {
// Changed line
diffLines.push(`-${oldLine}`);
diffLines.push(`+${newLine}`);
}
} else if (oldLine !== undefined) {
// Removed line
diffLines.push(`-${oldLine}`);
} else if (newLine !== undefined) {
// Added line
diffLines.push(`+${newLine}`);
}
} }
diffLines.push(''); diffLines.push('');
-227
View File
@@ -1,227 +0,0 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { GitFetchCommand } from './fetch';
import type { GitSubcommandOptions } from '../git';
import type { Git } from '../../git';
import type { JSRuntimeFS } from '../../JSRuntime';
// Mock implementations
const mockGit = {
listRemotes: async () => [
{ remote: 'origin', url: 'https://github.com/user/repo.git' },
{ remote: 'upstream', url: 'https://github.com/upstream/repo.git' }
],
fetch: async () => {},
resolveRef: async () => 'abc123def456',
} as unknown as Git;
const mockFS = {
stat: async (path: string) => {
if (path.endsWith('/.git')) {
return { isDirectory: () => true };
}
throw new Error('File not found');
},
} as unknown as JSRuntimeFS;
const mockOptions: GitSubcommandOptions = {
git: mockGit,
fs: mockFS,
pwd: '/test/repo',
};
describe('GitFetchCommand', () => {
let command: GitFetchCommand;
beforeEach(() => {
command = new GitFetchCommand(mockOptions);
});
describe('parseArgs', () => {
type ParseArgsResult = {
remote: string;
refs: string[];
options: {
all: boolean;
tags: boolean;
prune: boolean;
verbose: boolean;
};
};
it('should parse no arguments correctly', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs([]);
expect(result).toEqual({
remote: 'origin',
refs: [],
options: {
all: false,
tags: false,
prune: false,
verbose: false,
},
});
});
it('should parse remote only', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['upstream']);
expect(result).toEqual({
remote: 'upstream',
refs: [],
options: {
all: false,
tags: false,
prune: false,
verbose: false,
},
});
});
it('should parse remote and refs', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['origin', 'main', 'develop']);
expect(result).toEqual({
remote: 'origin',
refs: ['main', 'develop'],
options: {
all: false,
tags: false,
prune: false,
verbose: false,
},
});
});
it('should parse options correctly', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--all', '--tags', '--prune', '--verbose']);
expect(result).toEqual({
remote: 'origin',
refs: [],
options: {
all: true,
tags: true,
prune: true,
verbose: true,
},
});
});
it('should parse short options', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['-p', '-v']);
expect(result).toEqual({
remote: 'origin',
refs: [],
options: {
all: false,
tags: false,
prune: true,
verbose: true,
},
});
});
it('should parse mixed arguments and options', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['upstream', '--verbose', 'main', '--tags']);
expect(result).toEqual({
remote: 'upstream',
refs: ['main'],
options: {
all: false,
tags: true,
prune: false,
verbose: true,
},
});
});
});
describe('execute', () => {
it('should fail when not in a git repository', async () => {
const commandWithoutGit = new GitFetchCommand({
...mockOptions,
fs: {
stat: async () => {
throw new Error('File not found');
},
} as unknown as JSRuntimeFS,
});
const result = await commandWithoutGit.execute([]);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('fatal: not a git repository');
});
it('should fail when remote does not exist', async () => {
const result = await command.execute(['nonexistent']);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("fatal: 'nonexistent' does not appear to be a git repository");
});
it('should fetch from default remote successfully', async () => {
const result = await command.execute([]);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('From https://github.com/user/repo.git');
expect(result.stdout).toContain('refs/heads/* -> refs/remotes/origin/*');
});
it('should fetch from specific remote successfully', async () => {
const result = await command.execute(['upstream']);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('From https://github.com/upstream/repo.git');
expect(result.stdout).toContain('refs/heads/* -> refs/remotes/upstream/*');
});
it('should fetch specific refs successfully', async () => {
const result = await command.execute(['origin', 'main']);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('From https://github.com/user/repo.git');
expect(result.stdout).toContain('* branch main -> origin/main');
});
it('should fetch multiple specific refs successfully', async () => {
const result = await command.execute(['origin', 'main', 'develop']);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('From https://github.com/user/repo.git');
expect(result.stdout).toContain('* branch main -> origin/main');
expect(result.stdout).toContain('* branch develop -> origin/develop');
});
it('should handle authentication errors', async () => {
const commandWithAuthError = new GitFetchCommand({
...mockOptions,
git: {
...mockGit,
fetch: async () => {
throw new Error('authentication failed');
},
} as unknown as Git,
});
const result = await commandWithAuthError.execute([]);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('fatal: Authentication failed');
});
it('should handle network errors', async () => {
const commandWithNetworkError = new GitFetchCommand({
...mockOptions,
git: {
...mockGit,
fetch: async () => {
throw new Error('network error');
},
} as unknown as Git,
});
const result = await commandWithNetworkError.execute([]);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('fatal: unable to access remote repository');
});
});
});
-173
View File
@@ -1,173 +0,0 @@
import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
export class GitFetchCommand implements GitSubcommand {
name = 'fetch';
description = 'Download objects and refs from another repository';
usage = 'git fetch [<remote>] [<refspec>...]';
private git: Git;
private fs: JSRuntimeFS;
private pwd: string;
constructor(options: GitSubcommandOptions) {
this.git = options.git;
this.fs = options.fs;
this.pwd = options.pwd;
}
async execute(args: string[]): Promise<ShellCommandResult> {
try {
// Check if we're in a git repository
try {
await this.fs.stat(`${this.pwd}/.git`);
} catch {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
const { remote, refs } = this.parseArgs(args);
// Get remote URL
let remoteUrl: string;
try {
const remotes = await this.git.listRemotes({
dir: this.pwd,
});
const targetRemote = remotes.find(r => r.remote === remote);
if (!targetRemote) {
return createErrorResult(`fatal: '${remote}' does not appear to be a git repository`);
}
remoteUrl = targetRemote.url;
} catch {
return createErrorResult(`fatal: '${remote}' does not appear to be a git repository`);
}
try {
// If specific refs are provided, fetch them; otherwise fetch all refs
if (refs.length > 0) {
// Fetch specific refs
for (const ref of refs) {
await this.git.fetch({
dir: this.pwd,
remote: remote,
ref: ref,
});
}
} else {
// Fetch all refs (default behavior)
await this.git.fetch({
dir: this.pwd,
remote: remote,
});
}
// Build output message
const lines: string[] = [];
lines.push(`From ${remoteUrl}`);
if (refs.length > 0) {
// Show specific refs that were fetched
for (const ref of refs) {
try {
await this.git.resolveRef({
dir: this.pwd,
ref: `refs/remotes/${remote}/${ref}`,
});
lines.push(` * branch ${ref} -> ${remote}/${ref}`);
} catch {
// If we can't resolve the ref, it might be a tag or other ref type
lines.push(` * [new ref] ${ref} -> ${remote}/${ref}`);
}
}
} else {
// For fetch without specific refs, we'll show a generic message
lines.push(` * [new refs] refs/heads/* -> refs/remotes/${remote}/*`);
}
return createSuccessResult(lines.join('\n') + '\n');
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('authentication')) {
return createErrorResult('fatal: Authentication failed. Please configure git credentials.');
} else if (error.message.includes('network')) {
return createErrorResult('fatal: unable to access remote repository. Please check your network connection.');
} else if (error.message.includes('not found')) {
return createErrorResult(`fatal: remote ref not found`);
}
}
return createErrorResult(`Failed to fetch: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
} catch (error) {
return createErrorResult(`git fetch: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private parseArgs(args: string[]): {
remote: string;
refs: string[];
options: {
all: boolean;
tags: boolean;
prune: boolean;
verbose: boolean;
}
} {
let remote = 'origin'; // Default remote
const refs: string[] = [];
const options = {
all: false,
tags: false,
prune: false,
verbose: false,
};
const nonOptionArgs: string[] = [];
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg.startsWith('-')) {
// Handle options
switch (arg) {
case '--all':
options.all = true;
break;
case '--tags':
options.tags = true;
break;
case '--prune':
case '-p':
options.prune = true;
break;
case '--verbose':
case '-v':
options.verbose = true;
break;
default:
// Ignore unknown options for now
break;
}
} else {
nonOptionArgs.push(arg);
}
}
// Parse non-option arguments
if (nonOptionArgs.length >= 1) {
remote = nonOptionArgs[0];
}
if (nonOptionArgs.length >= 2) {
// All remaining args are refs/refspecs
refs.push(...nonOptionArgs.slice(1));
}
return { remote, refs, options };
}
}
-123
View File
@@ -1,123 +0,0 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { GitPullCommand } from './pull';
import type { GitSubcommandOptions } from '../git';
import type { Git } from '../../git';
import type { JSRuntimeFS } from '../../JSRuntime';
// Mock implementations
const mockGit = {
currentBranch: async () => 'main',
listRemotes: async () => [{ remote: 'origin', url: 'https://github.com/user/repo.git' }],
statusMatrix: async () => [],
fetch: async () => {},
resolveRef: async () => 'abc123',
merge: async () => {},
} as unknown as Git;
const mockFS = {
stat: async () => ({ isDirectory: () => true }),
} as unknown as JSRuntimeFS;
const mockOptions: GitSubcommandOptions = {
git: mockGit,
fs: mockFS,
pwd: '/test/repo',
};
describe('GitPullCommand', () => {
let command: GitPullCommand;
beforeEach(() => {
command = new GitPullCommand(mockOptions);
});
describe('parseArgs', () => {
it('should parse no arguments correctly', () => {
// Access the private method for testing
const result = (command as unknown as { parseArgs: (args: string[]) => { remote: string; branch?: string } }).parseArgs([]);
expect(result).toEqual({
remote: 'origin',
branch: undefined,
});
});
it('should parse remote only', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => { remote: string; branch?: string } }).parseArgs(['upstream']);
expect(result).toEqual({
remote: 'upstream',
branch: undefined,
});
});
it('should parse remote and branch correctly', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => { remote: string; branch?: string } }).parseArgs(['origin', 'main']);
expect(result).toEqual({
remote: 'origin',
branch: 'main',
});
});
it('should parse different remote and branch', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => { remote: string; branch?: string } }).parseArgs(['upstream', 'develop']);
expect(result).toEqual({
remote: 'upstream',
branch: 'develop',
});
});
it('should ignore option flags', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => { remote: string; branch?: string } }).parseArgs(['--rebase', 'origin', '--verbose', 'main']);
expect(result).toEqual({
remote: 'origin',
branch: 'main',
});
});
it('should handle extra arguments beyond remote and branch', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => { remote: string; branch?: string } }).parseArgs(['origin', 'main', 'extra', 'args']);
expect(result).toEqual({
remote: 'origin',
branch: 'main',
});
});
});
describe('execute', () => {
it('should list modified files when there are uncommitted changes', async () => {
// Mock statusMatrix to return some modified files
const mockGitWithChanges = {
...mockGit,
statusMatrix: async () => [
['src/index.ts', 1, 2, 1], // Modified file
['README.md', 1, 2, 2], // Modified and staged
['package.json', 0, 2, 0], // Untracked file
],
} as unknown as Git;
// Mock FS to ensure .git directory exists
const mockFSWithGit = {
stat: async (path: string) => {
if (path.endsWith('/.git')) {
return { isDirectory: () => true };
}
throw new Error('File not found');
},
} as unknown as JSRuntimeFS;
const commandWithChanges = new GitPullCommand({
git: mockGitWithChanges,
fs: mockFSWithGit,
pwd: '/test/repo',
});
const result = await commandWithChanges.execute(['origin', 'main']);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('error: Your local changes to the following files would be overwritten by merge:');
expect(result.stderr).toContain('\tsrc/index.ts');
expect(result.stderr).toContain('\tREADME.md');
expect(result.stderr).toContain('\tpackage.json');
expect(result.stderr).toContain('Please commit your changes or stash them before you merge.');
});
});
});
+22 -21
View File
@@ -35,7 +35,7 @@ export class GitPullCommand implements GitSubcommand {
let currentBranch: string | null = null; let currentBranch: string | null = null;
try { try {
currentBranch = await this.git.currentBranch({ currentBranch = await this.git.currentBranch({
dir: this.pwd, dir: this.pwd,
}) || null; }) || null;
if (!targetBranch) { if (!targetBranch) {
@@ -51,7 +51,7 @@ export class GitPullCommand implements GitSubcommand {
let remoteUrl: string; let remoteUrl: string;
try { try {
const remotes = await this.git.listRemotes({ const remotes = await this.git.listRemotes({
dir: this.pwd, dir: this.pwd,
}); });
@@ -69,16 +69,12 @@ export class GitPullCommand implements GitSubcommand {
dir: this.pwd, dir: this.pwd,
}); });
const modifiedFiles = statusMatrix const hasChanges = statusMatrix.some(([, headStatus, workdirStatus, stageStatus]) => {
.filter(([, headStatus, workdirStatus, stageStatus]) => { return headStatus !== workdirStatus || headStatus !== stageStatus;
// Check for any uncommitted changes (modified, staged, or untracked) });
return headStatus !== workdirStatus || headStatus !== stageStatus;
})
.map(([filepath]) => filepath);
if (modifiedFiles.length > 0) { if (hasChanges) {
const fileList = modifiedFiles.map(file => `\t${file}`).join('\n'); return createErrorResult('error: Your local changes to the following files would be overwritten by merge:\nPlease commit your changes or stash them before you merge.');
return createErrorResult(`error: Your local changes to the following files would be overwritten by merge:\n${fileList}\nPlease commit your changes or stash them before you merge.`);
} }
try { try {
@@ -94,7 +90,7 @@ export class GitPullCommand implements GitSubcommand {
let remoteOid: string; let remoteOid: string;
try { try {
remoteOid = await this.git.resolveRef({ remoteOid = await this.git.resolveRef({
dir: this.pwd, dir: this.pwd,
ref: remoteRef, ref: remoteRef,
}); });
@@ -106,14 +102,14 @@ export class GitPullCommand implements GitSubcommand {
let currentOid: string; let currentOid: string;
try { try {
currentOid = await this.git.resolveRef({ currentOid = await this.git.resolveRef({
dir: this.pwd, dir: this.pwd,
ref: 'HEAD', ref: 'HEAD',
}); });
} catch { } catch {
// Empty repository, just checkout the remote branch // Empty repository, just checkout the remote branch
await this.git.checkout({ await this.git.checkout({
dir: this.pwd, dir: this.pwd,
ref: targetBranch, ref: targetBranch,
}); });
@@ -127,7 +123,7 @@ export class GitPullCommand implements GitSubcommand {
// Perform fast-forward merge (simplified) // Perform fast-forward merge (simplified)
await this.git.merge({ await this.git.merge({
dir: this.pwd, dir: this.pwd,
ours: currentBranch || 'HEAD', ours: currentBranch || 'HEAD',
theirs: remoteRef, theirs: remoteRef,
@@ -161,13 +157,18 @@ export class GitPullCommand implements GitSubcommand {
let remote = 'origin'; // Default remote let remote = 'origin'; // Default remote
let branch: string | undefined; let branch: string | undefined;
const nonOptionArgs = args.filter(arg => !arg.startsWith('-')); for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (nonOptionArgs.length >= 1) { if (!arg.startsWith('-')) {
remote = nonOptionArgs[0]; if (remote === 'origin' && !branch) {
} // First non-option argument is remote
if (nonOptionArgs.length >= 2) { remote = arg;
branch = nonOptionArgs[1]; } else if (!branch) {
// Second non-option argument is branch
branch = arg;
}
}
} }
return { remote, branch }; return { remote, branch };
-245
View File
@@ -1,245 +0,0 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { GitResetCommand } from './reset';
import type { GitSubcommandOptions } from '../git';
import type { Git } from '../../git';
import type { JSRuntimeFS } from '../../JSRuntime';
// Mock implementations
const mockGit = {
statusMatrix: async () => [
// [filepath, headStatus, workdirStatus, stageStatus]
['staged.txt', 1, 1, 2], // Modified in stage
['new-staged.txt', 0, 1, 2], // New file staged
['modified.txt', 1, 2, 1], // Modified in working dir (not staged)
['unchanged.txt', 1, 1, 1], // No changes
],
resetIndex: async ({ filepath }: { filepath: string }) => {
// Mock successful reset
return { filepath };
},
resolveRef: async ({ ref }: { ref: string }) => {
const refs = {
'HEAD': 'abc123def456',
'HEAD~1': 'def456abc123',
};
if (refs[ref as keyof typeof refs]) {
return refs[ref as keyof typeof refs];
}
throw new Error(`Unknown ref: ${ref}`);
},
readCommit: async () => ({
oid: 'abc123def456',
commit: {
message: 'Test commit',
author: { name: 'Test', email: '[email protected]' },
},
}),
writeRef: async () => {},
checkout: async () => {},
} as unknown as Git;
const mockFS = {
stat: async (path: string) => {
if (path.endsWith('/.git')) {
return { isDirectory: () => true };
}
throw new Error('File not found');
},
} as unknown as JSRuntimeFS;
const mockOptions: GitSubcommandOptions = {
git: mockGit,
fs: mockFS,
pwd: '/test/repo',
};
describe('GitResetCommand', () => {
let command: GitResetCommand;
beforeEach(() => {
command = new GitResetCommand(mockOptions);
});
describe('parseArgs', () => {
type ParseArgsResult = {
mode: 'soft' | 'mixed' | 'hard';
target: string;
files: string[];
isFileReset: boolean;
};
it('should parse no arguments as file reset', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs([]);
expect(result).toEqual({
mode: 'mixed',
target: 'HEAD',
files: [],
isFileReset: true,
});
});
it('should parse HEAD as file reset', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['HEAD']);
expect(result).toEqual({
mode: 'mixed',
target: 'HEAD',
files: [],
isFileReset: true,
});
});
it('should parse HEAD with files as file reset', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['HEAD', 'file1.txt', 'file2.txt']);
expect(result).toEqual({
mode: 'mixed',
target: 'HEAD',
files: ['file1.txt', 'file2.txt'],
isFileReset: true,
});
});
it('should parse commit hash as commit reset', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['abc123def']);
expect(result).toEqual({
mode: 'mixed',
target: 'abc123def',
files: [],
isFileReset: false,
});
});
it('should parse mode flags correctly', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--hard', 'HEAD~1']);
expect(result).toEqual({
mode: 'hard',
target: 'HEAD~1',
files: [],
isFileReset: false,
});
});
it('should parse mixed mode with commit', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--mixed', 'HEAD~1']);
expect(result).toEqual({
mode: 'mixed',
target: 'HEAD~1',
files: [],
isFileReset: false,
});
});
});
describe('execute', () => {
it('should fail when not in a git repository', async () => {
const commandWithoutGit = new GitResetCommand({
...mockOptions,
fs: {
stat: async () => {
throw new Error('File not found');
},
} as unknown as JSRuntimeFS,
});
const result = await commandWithoutGit.execute([]);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('fatal: not a git repository');
});
it('should unstage all files when called without arguments', async () => {
const result = await command.execute([]);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('Unstaged changes after reset:');
expect(result.stdout).toContain('M\tstaged.txt');
expect(result.stdout).toContain('M\tnew-staged.txt');
// Should not include files that aren't staged
expect(result.stdout).not.toContain('modified.txt');
expect(result.stdout).not.toContain('unchanged.txt');
});
it('should unstage all files when called with HEAD', async () => {
const result = await command.execute(['HEAD']);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('Unstaged changes after reset:');
expect(result.stdout).toContain('M\tstaged.txt');
expect(result.stdout).toContain('M\tnew-staged.txt');
});
it('should unstage specific files when called with HEAD and file paths', async () => {
const result = await command.execute(['HEAD', 'staged.txt']);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('Unstaged changes after reset:');
expect(result.stdout).toContain('M\tstaged.txt');
expect(result.stdout).not.toContain('new-staged.txt');
});
it('should return empty output when no files are staged', async () => {
const commandWithNoStaged = new GitResetCommand({
...mockOptions,
git: {
...mockGit,
statusMatrix: async () => [
['modified.txt', 1, 2, 1], // Modified in working dir only
['unchanged.txt', 1, 1, 1], // No changes
],
} as unknown as Git,
});
const result = await commandWithNoStaged.execute([]);
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
});
it('should handle errors when resetting specific files', async () => {
const commandWithError = new GitResetCommand({
...mockOptions,
git: {
...mockGit,
resetIndex: async ({ filepath }: { filepath: string }) => {
if (filepath === 'nonexistent.txt') {
throw new Error('File not found');
}
return { filepath };
},
} as unknown as Git,
});
const result = await commandWithError.execute(['HEAD', 'nonexistent.txt']);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("error: pathspec 'nonexistent.txt' did not match any file(s) known to git");
});
it('should handle commit reset with hard mode', async () => {
const result = await command.execute(['--hard', 'HEAD~1']);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('HEAD is now at def456a');
});
it('should handle commit reset with mixed mode', async () => {
const result = await command.execute(['--mixed', 'HEAD~1']);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('HEAD is now at def456a');
});
it('should return error for soft reset (not implemented)', async () => {
const result = await command.execute(['--soft', 'HEAD~1']);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('--soft reset is not implemented');
});
it('should handle invalid commit reference', async () => {
const result = await command.execute(['abcdef12345']);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("fatal: ambiguous argument 'abcdef12345'");
});
});
});
+20 -71
View File
@@ -29,10 +29,10 @@ export class GitResetCommand implements GitSubcommand {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
} }
const { mode, target, files, isFileReset } = this.parseArgs(args); const { mode, target, files } = this.parseArgs(args);
if (isFileReset) { if (files.length > 0) {
// Reset specific files or all files (unstage) // Reset specific files (unstage)
return await this.resetFiles(files); return await this.resetFiles(files);
} else { } else {
// Reset to commit // Reset to commit
@@ -47,27 +47,22 @@ export class GitResetCommand implements GitSubcommand {
private parseArgs(args: string[]): { private parseArgs(args: string[]): {
mode: 'soft' | 'mixed' | 'hard'; mode: 'soft' | 'mixed' | 'hard';
target: string; target: string;
files: string[]; files: string[]
isFileReset: boolean;
} { } {
let mode: 'soft' | 'mixed' | 'hard' = 'mixed'; // Default mode let mode: 'soft' | 'mixed' | 'hard' = 'mixed'; // Default mode
let target = 'HEAD'; // Default target let target = 'HEAD'; // Default target
const files: string[] = []; const files: string[] = [];
let foundTarget = false; let foundTarget = false;
let hasMode = false;
for (const arg of args) { for (const arg of args) {
if (arg === '--soft') { if (arg === '--soft') {
mode = 'soft'; mode = 'soft';
hasMode = true;
} else if (arg === '--mixed') { } else if (arg === '--mixed') {
mode = 'mixed'; mode = 'mixed';
hasMode = true;
} else if (arg === '--hard') { } else if (arg === '--hard') {
mode = 'hard'; mode = 'hard';
hasMode = true;
} else if (!arg.startsWith('-')) { } else if (!arg.startsWith('-')) {
if (!foundTarget && (arg === 'HEAD' || arg.match(/^[a-f0-9]{7,40}$/) || arg.match(/^HEAD[~^]\d*$/))) { if (!foundTarget && (arg === 'HEAD' || arg.match(/^[a-f0-9]{7,40}$/))) {
target = arg; target = arg;
foundTarget = true; foundTarget = true;
} else { } else {
@@ -76,17 +71,7 @@ export class GitResetCommand implements GitSubcommand {
} }
} }
// Determine if this is a file reset operation return { mode, target, files };
// git reset without arguments = unstage all files
// git reset HEAD = unstage all files
// git reset HEAD <files> = unstage specific files
// git reset <commit> = reset to commit
// git reset --mode <commit> = reset to commit with mode
const isFileReset = (args.length === 0) ||
(target === 'HEAD' && !hasMode && files.length === 0) ||
(files.length > 0);
return { mode, target, files, isFileReset };
} }
private async resetFiles(files: string[]): Promise<ShellCommandResult> { private async resetFiles(files: string[]): Promise<ShellCommandResult> {
@@ -94,53 +79,17 @@ export class GitResetCommand implements GitSubcommand {
const resetFiles: string[] = []; const resetFiles: string[] = [];
const errors: string[] = []; const errors: string[] = [];
if (files.length === 0) { for (const file of files) {
// Reset all staged files (git reset or git reset HEAD)
try { try {
// Get the status matrix to find all staged files // Remove from staging area (reset to HEAD)
const statusMatrix = await this.git.statusMatrix({ await this.git.resetIndex({
dir: this.pwd, dir: this.pwd,
filepath: file,
}); });
resetFiles.push(file);
// Find files that are staged (differ from HEAD) } catch {
const stagedFiles = statusMatrix errors.push(`error: pathspec '${file}' did not match any file(s) known to git`);
.filter(([, headStatus, , stageStatus]) => {
return headStatus !== stageStatus;
})
.map(([filepath]) => filepath);
if (stagedFiles.length === 0) {
return createSuccessResult('');
}
// Reset each staged file
for (const file of stagedFiles) {
try {
await this.git.resetIndex({
dir: this.pwd,
filepath: file,
});
resetFiles.push(file);
} catch (error) {
errors.push(`error: failed to reset '${file}': ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
} catch (error) {
return createErrorResult(`Failed to get repository status: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
} else {
// Reset specific files
for (const file of files) {
try {
// Remove from staging area (reset to HEAD)
await this.git.resetIndex({
dir: this.pwd,
filepath: file,
});
resetFiles.push(file);
} catch {
errors.push(`error: pathspec '${file}' did not match any file(s) known to git`);
}
} }
} }
@@ -165,7 +114,7 @@ export class GitResetCommand implements GitSubcommand {
let targetOid: string; let targetOid: string;
try { try {
targetOid = await this.git.resolveRef({ targetOid = await this.git.resolveRef({
dir: this.pwd, dir: this.pwd,
ref: target, ref: target,
}); });
@@ -177,7 +126,7 @@ export class GitResetCommand implements GitSubcommand {
let currentOid: string; let currentOid: string;
try { try {
currentOid = await this.git.resolveRef({ currentOid = await this.git.resolveRef({
dir: this.pwd, dir: this.pwd,
ref: 'HEAD', ref: 'HEAD',
}); });
@@ -203,7 +152,7 @@ export class GitResetCommand implements GitSubcommand {
// Reset the index to match the target commit // Reset the index to match the target commit
try { try {
await this.git.checkout({ await this.git.checkout({
dir: this.pwd, dir: this.pwd,
ref: target, ref: target,
noCheckout: true, // Only update the index, not the working directory noCheckout: true, // Only update the index, not the working directory
@@ -223,14 +172,14 @@ export class GitResetCommand implements GitSubcommand {
// Get the commit object to ensure it exists // Get the commit object to ensure it exists
await this.git.readCommit({ await this.git.readCommit({
dir: this.pwd, dir: this.pwd,
oid: targetOid, oid: targetOid,
}); });
// Update HEAD to point to the target commit // Update HEAD to point to the target commit
await this.git.writeRef({ await this.git.writeRef({
dir: this.pwd, dir: this.pwd,
ref: 'HEAD', ref: 'HEAD',
value: targetOid, value: targetOid,
@@ -239,7 +188,7 @@ export class GitResetCommand implements GitSubcommand {
// Reset the working directory by checking out all files from the target commit // Reset the working directory by checking out all files from the target commit
// Use force to overwrite any local changes // Use force to overwrite any local changes
await this.git.checkout({ await this.git.checkout({
dir: this.pwd, dir: this.pwd,
ref: targetOid, ref: targetOid,
force: true, force: true,
Loaded 100 of 152 files, more files were not shown because too many files have changed in this diff. Show more