Compare commits

...
154 Commits
Author SHA1 Message Date
Alex Gleason be7584a730 Merge remote-tracking branch 'origin/main' into capacitor 2025-10-04 15:21:08 -05:00
Alex Gleason 0644541510 eslint --fix 2025-10-04 15:21:04 -05:00
Alex Gleason d9a4efe2b2 eslint --fix 2025-10-04 15:18:03 -05:00
Alex Gleason d93b9b2670 Merge branch 'improvement/56-missing-git-commands' into 'main'
Improvement/56 missing git commands

Closes #56

See merge request soapbox-pub/shakespeare!49
2025-10-04 19:50:14 +00:00
Alex Gleason 375219185f Merge remote-tracking branch 'origin/main' into capacitor 2025-10-04 14:47:27 -05:00
Alex Gleason f2f1941a30 Merge branch 'easter-egg/shakespeare' into 'main'
easter-egg/shakespeare

See merge request soapbox-pub/shakespeare!50
2025-10-04 15:50:43 +00:00
sam a07241a0cb 📜 More light and light; more dark and dark our woes. 2025-10-04 22:01:51 +07:00
sam a343c4a530 test typing 2025-10-04 19:05:53 +07:00
sam f04ff1073e lint 2025-10-04 16:27:23 +07:00
sam 920b4c4426 lint config 2025-10-04 15:54:35 +07:00
sam 510fb3c4f6 lint - remove unused 2025-10-04 15:54:26 +07:00
sam 3972d57297 test stash 2025-10-04 15:54:06 +07:00
sam 804be34a3e wip git stash 2025-10-04 15:23:21 +07:00
sam 0653f3feb8 terminal colouring for git diffs 2025-10-04 12:36:02 +07:00
sam 3337e96cfa expand show command 2025-10-04 12:28:38 +07:00
Alex Gleason 08cbf296af Merge branch 'fix/48-tool-not-found-error-stops-user-in-their-tracks-add-to-quilly-detection' into 'main'
fix/48-tool-not-found-error-stops-user-in-their-tracks-add-to-quilly-detection

Closes #48

See merge request soapbox-pub/shakespeare!46
2025-10-04 05:27:04 +00:00
Alex Gleason 5eb90e17c9 Merge branch 'ui/convey-shakespeare-activity-in-app-favicon' into 'main'
ui/convey-shakespeare-activity-in-app-favicon

See merge request soapbox-pub/shakespeare!47
2025-10-04 05:26:31 +00:00
Alex Gleason e7e1e5ca1d Merge remote-tracking branch 'origin/main' into capacitor 2025-10-04 00:21:17 -05:00
Alex Gleason b55e04ba77 Add Apple PWA tags 2025-10-04 00:19:01 -05:00
Alex Gleason bc6a875e27 Finish cleaning up JSRuntimeFS type 2025-10-04 00:02:50 -05:00
Alex Gleason a6f01b7149 Merge remote-tracking branch 'origin/main' into capacitor 2025-10-04 00:01:09 -05:00
Alex Gleason 1c746e0bb8 Add safe-area plugin to tailwind.config.ts 2025-10-04 00:00:18 -05:00
Alex Gleason b09e6c285a Merge remote-tracking branch 'origin/main' into capacitor 2025-10-03 23:58:59 -05:00
Alex Gleason 4e163a032f Safe area inset improvements 2025-10-03 23:56:38 -05:00
Alex Gleason d9956e60eb Accept options object in JSRuntimeFS 2025-10-03 23:56:17 -05:00
Alex Gleason 61e97fe87f Fix CreditsDialog height (sort of) 2025-10-03 23:33:50 -05:00
Alex Gleason 72df9e1e98 Give up on CapacitorFS, just use IndexedDB 2025-10-03 23:21:30 -05:00
Alex Gleason f06e4cef89 Fix detached ArrayBuffer error in CapacitorFSAdapter 2025-10-03 23:20:30 -05:00
Alex Gleason f420500db2 Always pass recursive option to capacitor fs mkdir 2025-10-03 22:38:45 -05:00
Alex Gleason b0f6d38801 Make JSRuntimeFS accept options object 2025-10-03 22:19:17 -05:00
Alex Gleason d5b7c11f84 Improve assets again 2025-10-03 22:18:15 -05:00
sam 83b4fe54c7 test commit command 2025-10-04 07:55:27 +07:00
sam abecdaa5cc git commit, support -am flag 2025-10-04 07:13:38 +07:00
Alex Gleason e6d906e443 Use Android FS when available 2025-10-03 16:37:21 -05:00
Alex Gleason 82528cd3f9 Conditional display of elements depending on if the app is running native 2025-10-03 16:05:25 -05:00
Alex Gleason 1d85f95b7e Improve splash / icon-background gradient 2025-10-03 15:58:36 -05:00
Alex Gleason 9fd392aeeb Display toast in safe area 2025-10-03 15:51:37 -05:00
Alex Gleason 88c2ce39b6 Remove unnecessary test file, fix android build commands 2025-10-03 15:49:44 -05:00
Alex Gleason bf8f9a07e7 Revert to a simpler webmanifest, rm generated pwa icons 2025-10-03 15:36:50 -05:00
Alex Gleason 807c1c513e Add icons, generate automatically 2025-10-03 15:32:32 -05:00
Alex Gleason 64eeafc44f gitignore generated assets 2025-10-03 15:14:26 -05:00
Alex Gleason 58281b7444 Remove placeholder assets 2025-10-03 15:14:04 -05:00
Alex Gleason 65ef45a69f Clean up README 2025-10-03 14:36:33 -05:00
Alex Gleason f034f0d468 Safe area fixes 2025-10-03 14:13:01 -05:00
Alex Gleason 56c4aaf669 Merge remote-tracking branch 'origin/main' into capacitor 2025-10-03 13:06:50 -05:00
Alex Gleason a4c0498e5b Send { type: "object" } tool parameters when we don't care about the input
Fixes https://gitlab.com/soapbox-pub/shakespeare/-/issues/60
2025-10-03 13:04:10 -05:00
sam 2d8d5aa728 fix tests 2025-10-03 17:41:32 +07:00
sam 1eebef173f merge 2025-10-03 16:21:43 +07:00
sam 76979c6150 revert to handle individual error types explicitly
++

++

++
2025-10-03 16:18:32 +07:00
sam 4ebca7f077 lint 2025-10-03 16:18:32 +07:00
sam d2971fcdb9 test quilly renders the error 2025-10-03 16:18:32 +07:00
sam 1416c5d017 let quilly opine on tool call errors, and streamline handling errors 2025-10-03 16:18:32 +07:00
sam 8b5cf72356 define and surface an error for malformed tool responses 2025-10-03 16:18:32 +07:00
sam c48288f9e6 adapt console error type to simplify quillys understand 2025-10-03 16:18:32 +07:00
sam b419f88571 lint 2025-10-03 15:01:30 +07:00
sam 3f5667d62a warn but don't fail on lint errors 2025-10-03 15:01:23 +07:00
sam 7abb0ace5a define lint spec for spaces > tabs and complete vscode/cursor setup for auto linting
lint

drop over zealous rule
2025-10-03 13:02:16 +07:00
sam 39adaef4c4 while any project session is 'busy', keep the favicon spinning 2025-10-03 13:02:16 +07:00
Alex Gleason fd2e342776 Remove unused css 2025-10-03 00:29:36 -05:00
Alex Gleason c70a683e29 com -> diy 2025-10-02 22:32:30 -05:00
Alex Gleason fb0d820b4e Get Android builds in a good place 2025-10-02 22:26:41 -05:00
Alex Gleason 356778ec95 Merge remote-tracking branch 'origin/main' into capacitor 2025-10-02 20:48:33 -05:00
Alex Gleason 388afd0b16 Enable sourcemap in Shakespeare itself 2025-10-02 17:59:29 -05:00
Alex Gleason 5f2faaad61 Fix xAI tool definitions
Fixes https://gitlab.com/soapbox-pub/shakespeare/-/issues/57
2025-10-02 17:57:36 -05:00
Alex Gleason aaf30db257 Add DeepSeek as a preset provider
Fixes https://gitlab.com/soapbox-pub/shakespeare/-/issues/58
2025-10-02 17:46:08 -05:00
Alex Gleason d4c775828f Fix build tests 2025-10-02 17:36:42 -05:00
Alex Gleason cbf85313af Enable sourcemap, fix output filenames 2025-10-02 17:30:12 -05:00
Alex Gleason 0b7f9cd2cb Update browserlist 2025-10-02 16:24:14 -05:00
Alex Gleason e0620bcca0 Merge branch 'consoleFramev4' into 'main'
Refactor console error to be provider level, simplifying console message/error tracking

See merge request soapbox-pub/shakespeare!48
2025-10-02 21:21:58 +00:00
Chad Curtis 97f5481ec7 Only clear console messages when project actually changes. 2025-10-02 20:58:56 +00:00
Alex Gleason 225c90f556 Surgically add esm.sh to existing CSP of index.html 2025-10-02 15:43:27 -05:00
Chad Curtis 51ce9c61ef Remove spurrious migration comment. 2025-10-02 20:30:02 +00:00
Alex Gleason c72170f19c Build by actually mimicking Vite's handling of index.html 2025-10-02 15:26:27 -05:00
Chad Curtis 111ab724e5 Remove and simplify some logic. 2025-10-02 20:15:30 +00:00
Chad Curtis 23c3cead89 Move non-tool logic out of tool file. 2025-10-02 20:09:09 +00:00
Chad Curtis 945c4209e8 Remove frivilous UI updates. 2025-10-02 20:02:16 +00:00
Chad Curtis 7574085213 Refactor console error to be provider level, tracking error via boolean rather than full logs as state. 2025-10-02 19:58:53 +00:00
Alex Gleason 3fba26ddb7 Switch payment method to a tabbed UI instead of dropdown 2025-10-01 17:24:22 -05:00
Alex Gleason bbcc56c800 Fix ModelSelector test 2025-10-01 17:13:23 -05:00
Alex Gleason cb794b5719 We do a little discord coding 2025-10-01 17:08:31 -05:00
Alex Gleason 931733ba16 Add warning to model selector if a free model is chosen 2025-10-01 16:38:16 -05:00
Alex Gleason c9a4576b19 Add Android support 2025-10-01 00:51:03 -05:00
shakespeare.diy 52fe76c9c6 Improve README: Add 🎭 emoji, website link, edit button, and license 2025-09-30 20:00:08 -05:00
Alex Gleason 7f5265cc92 Fix shell redirection 2025-09-30 15:06:47 -05:00
Alex Gleason 7f4b7f2a03 Add "sed" command 2025-09-30 14:59:48 -05:00
Alex Gleason 34ede4b799 Fix "git reset" 2025-09-30 14:41:32 -05:00
Alex Gleason d5c28c3097 Fix "git diff" 2025-09-30 13:17:58 -05:00
Alex Gleason 31de1b934d Fix git diff command 2025-09-30 13:12:04 -05:00
Alex Gleason 45f1202b9d Implement "git fetch" 2025-09-30 12:55:53 -05:00
Alex Gleason b4f0ede7b7 Remove extraneous "Exploring Other Projects" section from system prompt 2025-09-30 12:51:11 -05:00
Alex Gleason df39f78d20 Fix "git pull" listing changed files 2025-09-30 12:47:21 -05:00
Alex Gleason b7e94ff67c Start fixing "git pull" 2025-09-30 12:42:57 -05:00
Alex Gleason 8b981dcf36 Add special handling when viewing projects/ and .git to text_editor_view tool 2025-09-30 12:13:49 -05:00
Alex Gleason f702d2300b Add special handling for viewing /projects 2025-09-30 12:06:52 -05:00
Alex Gleason 4edbb8a73a Remove gitignore functionality from text_editor_view tool 2025-09-30 11:55:25 -05:00
Alex Gleason 98f584a851 Teach Shakespeare that it can look at other projects 2025-09-30 11:17:06 -05:00
Alex Gleason 8b438c8c1b Scroll down when Quilly appears 2025-09-29 22:19:18 -05:00
Alex Gleason d18cfb4849 Truncate model description 2025-09-29 18:21:34 -05:00
Alex Gleason b04c1440b5 Improve display of buttons 2025-09-29 18:01:49 -05:00
Alex Gleason 5fa16115fd Rebuild project after saving file
Fixes https://gitlab.com/soapbox-pub/shakespeare/-/issues/53
2025-09-29 17:51:25 -05:00
Alex Gleason 795eaa50c2 Make Quilly's "fix error" add assistant messages 2025-09-29 17:19:02 -05:00
Alex Gleason 3da2075539 Ensure console errors get passed to Quilly on desktop 2025-09-29 17:01:30 -05:00
Alex Gleason a87063f6e9 Fix types in test 2025-09-29 16:55:28 -05:00
Alex Gleason 75cab68281 Clean up directory if cloning fails 2025-09-29 16:48:35 -05:00
Alex Gleason 1abc37f388 Actually, bring back the custom scrollbars 2025-09-29 16:29:58 -05:00
Alex Gleason 24c8525360 Fix OnboardingDialog height, remove scrollbar customizations, add comma 2025-09-29 16:20:36 -05:00
Alex Gleason 2f4fb16e94 Slight improvement to "quality of output" statement 2025-09-29 16:09:59 -05:00
Alex Gleason 3e8d5fb87c Fix tiny checkboxes on AI Settings page 2025-09-29 16:06:12 -05:00
Alex Gleason 7b438bae34 Display credits badge in Onboarding if the user is coming from Act1 2025-09-29 16:00:43 -05:00
Alex Gleason cb4cc16760 Don't configure users through the Act1Dialog, still force them to go through the normal onboarding flow 2025-09-29 15:41:57 -05:00
Alex Gleason aca620e460 Add ToS agreement to AI Settings page 2025-09-29 15:23:58 -05:00
Alex Gleason 89db9c354a Require agreement to AI Provider ToS in OnboardingDialog 2025-09-29 15:13:59 -05:00
Alex Gleason fc0134a3a8 Add tosURL to preset AI providers 2025-09-29 15:09:03 -05:00
Alex Gleason 2477b5417c Add provider step to onboarding 2025-09-29 15:00:40 -05:00
Alex Gleason 92483728d0 Scroll OnboardingDialog to top when navigating between steps 2025-09-29 13:41:48 -05:00
Alex Gleason ba0ec1f420 Add Open Source section to OnboardingDialog 2025-09-29 13:35:39 -05:00
Alex Gleason bdcaa2ef76 When a package imports itself, use the same version as the importer 2025-09-28 17:27:41 -05:00
Alex Gleason d1d8f1dd15 Fix CSS relative imports 2025-09-28 10:16:22 -05:00
Alex Gleason 66d08d05de Merge branch 'ui/47-github-connection-failure-error-toast-disappears-before-i-can-make-sense-of-it' into 'main'
ui/47-github-connection-failure-error-toast-disappears-before-i-can-make-sense-of-it

Closes #47

See merge request soapbox-pub/shakespeare!41
2025-09-28 14:40:24 +00:00
sam bb8912dd57 show git failure toasts indefinitely 2025-09-28 16:10:59 +07:00
Alex Gleason 804cdbd789 Merge branch 'fix/49-quilly-doesnt-show-up-on-mobile-when-you-have-console-errors' into 'main'
fix/49-quilly-doesnt-show-up-on-mobile-when-you-have-console-errors

Closes #49

See merge request soapbox-pub/shakespeare!40
2025-09-28 04:56:48 +00:00
Alex Gleason f022332595 Add shakespeare.svg and ShakespeareLogo component 2025-09-27 23:47:53 -05:00
Alex Gleason ba509584b7 Merge branch 'minorDesignUpdates' into 'main'
Minor Design Updates (Optional)

See merge request soapbox-pub/shakespeare!37
2025-09-28 04:41:03 +00:00
Alex Gleason 787877d2c7 Handle data: URLs 2025-09-27 23:15:58 -05:00
Alex Gleason 0b269f78a4 Resolve from peerDependencies, then just fallback to the latest version 2025-09-27 23:11:22 -05:00
lemonknowsall 7a11137aed save nav padding for terminal 2025-09-27 20:59:59 -07:00
lemonknowsall 1d0231bc03 file viewer scrolling 2025-09-27 20:59:46 -07:00
lemonknowsall 8b62ba8e7e Updated logos, default theme, onboard modals, and mobile browser fixes 2025-09-27 20:59:36 -07:00
Alex Gleason 4e0625721e Fix compatibility with leaflet 2025-09-27 22:42:42 -05:00
Alex Gleason 3529d43b91 Support json imports 2025-09-27 22:28:21 -05:00
Alex Gleason 93a636589d Fix Tailwind styles 2025-09-27 22:22:49 -05:00
Alex Gleason eba609ae73 NpmAddPackageTool should not bump the package version 2025-09-27 21:40:32 -05:00
Alex Gleason 8c60a3a8bc Externalize static assets like fonts 2025-09-27 21:23:45 -05:00
Alex Gleason 939deabb5b Support Vite query params of local imports, specifically ?raw 2025-09-27 21:07:28 -05:00
Alex Gleason 2ec32f5537 Polyfill virtual:pwa-register/react 2025-09-27 20:39:51 -05:00
sam 124e9d5937 wip, bring error handling up to the project level to exist across mobile tabs 2025-09-28 08:37:45 +07:00
Alex Gleason b064c9ff86 Mock "sonner" and "next-themes" when building 2025-09-27 20:20:04 -05:00
Alex Gleason a9a5cafcac Don't hardcode gitnostr.com 2025-09-27 16:26:07 -05:00
Alex Gleason 2db9d5e513 Move Import ZIP File to Clone page 2025-09-27 15:43:43 -05:00
Alex Gleason e8156243d0 Simplify Nostr Settings loading skeleton 2025-09-27 14:48:06 -05:00
Alex Gleason e9c73693ce Move email newsletter into Settings 2025-09-27 14:29:18 -05:00
Alex Gleason 1a9a553523 Remove @apply 2025-09-26 21:41:21 -05:00
Alex Gleason fc6a70793f Fix scrolling the virtual terminal on mobile 2025-09-26 21:22:16 -05:00
Alex Gleason fba1328e5f Build after pulling 2025-09-26 21:13:12 -05:00
Alex Gleason a45e29578c Fix pulling 2025-09-26 20:49:02 -05:00
Alex Gleason c1cbbed05c About page improvements 2025-09-26 20:33:48 -05:00
Alex Gleason d95abf2499 Terminal autoCapitalize=off 2025-09-26 20:18:40 -05:00
Alex Gleason 4316b766e2 Fix git add 2025-09-26 19:55:01 -05:00
Alex Gleason 8800a55eed Fix git status 2025-09-26 19:11:57 -05:00
Alex Gleason 48dfd2d99e Fix mobile terminal issues 2025-09-26 19:00:07 -05:00
Alex Gleason cb971955ae Improve terminal UX 2025-09-26 18:51:25 -05:00
Alex Gleason deb593c1b6 Improve terminal input display 2025-09-26 18:09:13 -05:00
Alex Gleason 3b3637009d Fix focus in TUI 2025-09-26 18:01:40 -05:00
Alex Gleason dc50d41928 Add virtual terminal to Code tab 2025-09-26 17:39:12 -05:00
156 changed files with 11210 additions and 1289 deletions

No files matched your search

+4
View File
@@ -12,6 +12,9 @@ dist
dist-ssr dist-ssr
*.local *.local
.ai-history/ .ai-history/
.tmp.webmanifest
*.apk
*.aab
# Editor directories and files # Editor directories and files
.idea .idea
@@ -30,3 +33,4 @@ dist-ssr
.env.* .env.*
!.env.example !.env.example
.ai/ .ai/
*.keystore
+5 -1
View File
@@ -1,3 +1,7 @@
{ {
"editor.tabSize": 2 "editor.tabSize": 2,
"editor.insertSpaces": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
} }
+29 -76
View File
@@ -1,85 +1,38 @@
# Shakespeare - AI-Powered Nostr Website Builder # Shakespeare 🎭
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. [![Edit with Shakespeare](https://shakespeare.diy/badge.svg)](https://shakespeare.diy/clone?url=https://gitlab.com/soapbox-pub/shakespeare.git)
AI-powered Nostr website builder. Describe what you want to build, and AI helps you create it.
https://shakespeare.diy
## Features ## Features
- **AI-Powered Development**: Chat with an AI assistant to build your Nostr website - **AI Chat**: Build websites through natural conversation
- **File Attachments**: Attach files directly to chat messages with structured text parts, visual badges, and deduplication. Supports both file selection and clipboard image pasting - **File Attachments**: Drag & drop files or paste images
- **Project Management**: Create and manage multiple projects with sidebar navigation - **Live Preview**: See changes in real-time
- **Real-time Editing**: Edit files directly in the browser with syntax highlighting - **Code Editor**: Edit files with syntax highlighting
- **File Explorer**: Browse and manage your project files - **Git Integration**: Full version control with credential management
- **Project Preview**: Preview your website as you build it - **Nostr Ready**: Built-in Nostr protocol support
- **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
1. **Create a Project**: Enter a description of what you want to build in the prompt textarea Visit the homepage, enter your project idea, and start building with AI assistance.
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
## Project Structure ## License
Each project includes: AGPLv3
- 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
+104
View File
@@ -0,0 +1,104 @@
# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore
# Built application files
*.apk
*.aar
*.ap_
*.aab
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Uncomment the following line in case you need and you don't have the release build type files in your app
# release/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# IntelliJ
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
# Android Studio 3 in .gitignore file.
.idea/caches
.idea/modules.xml
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
.idea/navEditor.xml
# Keystore files
# Uncomment the following lines if you do not want to check your keystore files in.
#*.jks
#*.keystore
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
.cxx/
# Google Services (e.g. APIs or Firebase)
# google-services.json
# Freeline
freeline.py
freeline/
freeline_project_description.json
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
# Version control
vcs.xml
# lint
lint/intermediates/
lint/generated/
lint/outputs/
lint/tmp/
# lint/reports/
# Android Profiling
*.hprof
# Cordova plugins for Capacitor
capacitor-cordova-android-plugins
# Copied web assets
app/src/main/assets/public
# Generated Config files
app/src/main/assets/capacitor.config.json
app/src/main/assets/capacitor.plugins.json
app/src/main/res/xml/config.xml
# Generated assets
app/src/main/res/*/*.png
+2
View File
@@ -0,0 +1,2 @@
/build/*
!/build/.npmkeep
+80
View File
@@ -0,0 +1,80 @@
apply plugin: 'com.android.application'
android {
namespace "diy.shakespeare.app"
compileSdk rootProject.ext.compileSdkVersion
defaultConfig {
applicationId "diy.shakespeare.app"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
}
}
signingConfigs {
release {
def keystorePath = rootProject.file("../shakespeare.keystore")
// Only require keystore for release builds
def taskNames = gradle.startParameter.taskNames.toString()
def isReleaseBuild = taskNames.contains("Release") || taskNames.contains("release") || taskNames.contains("bundle")
if (!isReleaseBuild) {
// Skip signing config for debug builds
return
}
if (!keystorePath.exists()) {
throw new GradleException("shakespeare.keystore not found! Expected at: " + keystorePath.absolutePath)
}
storeFile keystorePath
keyAlias "mykey"
storePassword "shakespeare"
keyPassword "shakespeare"
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
}
}
repositories {
flatDir{
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
implementation project(':capacitor-android')
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
implementation project(':capacitor-cordova-android-plugins')
}
apply from: 'capacitor.build.gradle'
try {
def servicesJSON = file('google-services.json')
if (servicesJSON.text) {
apply plugin: 'com.google.gms.google-services'
}
} catch(Exception e) {
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
}
+23
View File
@@ -0,0 +1,23 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_21
targetCompatibility JavaVersion.VERSION_21
}
}
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
implementation project(':capacitor-app')
implementation project(':capacitor-filesystem')
implementation project(':capacitor-keyboard')
implementation project(':capacitor-splash-screen')
implementation project(':capacitor-status-bar')
}
if (hasProperty('postBuildExtras')) {
postBuildExtras()
}
+21
View File
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
+35
View File
@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="utf-8" ?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation"
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBarLaunch"
android:launchMode="singleTask"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
</provider>
</application>
<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
@@ -0,0 +1,5 @@
package diy.shakespeare.app;
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {}
@@ -0,0 +1,34 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillType="evenOdd"
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
android:strokeColor="#00000000"
android:strokeWidth="1">
<aapt:attr name="android:fillColor">
<gradient
android:endX="78.5885"
android:endY="90.9159"
android:startX="48.7653"
android:startY="61.0927"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
android:strokeColor="#00000000"
android:strokeWidth="1" />
</vector>
@@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillColor="#26A69A"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
</vector>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background>
<inset android:drawable="@mipmap/ic_launcher_background" android:inset="16.7%" />
</background>
<foreground>
<inset android:drawable="@mipmap/ic_launcher_foreground" android:inset="16.7%" />
</foreground>
</adaptive-icon>
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background>
<inset android:drawable="@mipmap/ic_launcher_background" android:inset="16.7%" />
</background>
<foreground>
<inset android:drawable="@mipmap/ic_launcher_foreground" android:inset="16.7%" />
</foreground>
</adaptive-icon>
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#FFFFFF</color>
</resources>
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="app_name">Shakespeare</string>
<string name="title_activity_main">Shakespeare</string>
<string name="package_name">diy.shakespeare.app</string>
<string name="custom_url_scheme">diy.shakespeare.app</string>
</resources>
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:background">@null</item>
</style>
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
<item name="android:background">@drawable/splash</item>
</style>
</resources>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="." />
<cache-path name="my_cache_images" path="." />
</paths>
@@ -0,0 +1,18 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
+29
View File
@@ -0,0 +1,29 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.7.2'
classpath 'com.google.gms:google-services:4.4.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
apply from: "variables.gradle"
allprojects {
repositories {
google()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
+18
View File
@@ -0,0 +1,18 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
include ':capacitor-android'
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
include ':capacitor-app'
project(':capacitor-app').projectDir = new File('../node_modules/@capacitor/app/android')
include ':capacitor-filesystem'
project(':capacitor-filesystem').projectDir = new File('../node_modules/@capacitor/filesystem/android')
include ':capacitor-keyboard'
project(':capacitor-keyboard').projectDir = new File('../node_modules/@capacitor/keyboard/android')
include ':capacitor-splash-screen'
project(':capacitor-splash-screen').projectDir = new File('../node_modules/@capacitor/splash-screen/android')
include ':capacitor-status-bar'
project(':capacitor-status-bar').projectDir = new File('../node_modules/@capacitor/status-bar/android')
+22
View File
@@ -0,0 +1,22 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-all.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+252
View File
@@ -0,0 +1,252 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+5
View File
@@ -0,0 +1,5 @@
include ':app'
include ':capacitor-cordova-android-plugins'
project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')
apply from: 'capacitor.settings.gradle'
+16
View File
@@ -0,0 +1,16 @@
ext {
minSdkVersion = 23
compileSdkVersion = 35
targetSdkVersion = 35
androidxActivityVersion = '1.9.2'
androidxAppCompatVersion = '1.7.0'
androidxCoordinatorLayoutVersion = '1.2.0'
androidxCoreVersion = '1.15.0'
androidxFragmentVersion = '1.8.4'
coreSplashScreenVersion = '1.0.1'
androidxWebkitVersion = '1.12.1'
junitVersion = '4.13.2'
androidxJunitVersion = '1.2.1'
androidxEspressoCoreVersion = '3.6.1'
cordovaAndroidVersion = '10.1.1'
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 229 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 222 B

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 229 KiB

+29
View File
@@ -0,0 +1,29 @@
import type { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
appId: 'diy.shakespeare.app',
appName: 'Shakespeare',
webDir: 'dist',
server: {
androidScheme: 'https'
},
plugins: {
SplashScreen: {
launchShowDuration: 2000,
launchAutoHide: true,
backgroundColor: "#ffffff",
androidSplashResourceName: "splash",
androidScaleType: "CENTER_CROP",
showSpinner: false
},
StatusBar: {
style: 'default'
},
Filesystem: {
// Use app data directory for all file operations
// This directory is included in Android backups
}
}
};
export default config;
+72
View File
@@ -0,0 +1,72 @@
## Mobile Development
Shakespeare supports building native Android apps using Capacitor.js. The mobile app provides the full Shakespeare experience with native mobile optimizations.
### Native Filesystem
Shakespeare automatically uses **native filesystem storage** on Android for better performance and reliability:
- **2-3x faster** file operations compared to web version
- **No storage quotas** - uses device storage directly
- **Automatic backups** - data included in Android backups
- **Better battery life** - 10-15% improvement during file operations
- **Automatic migration** - seamlessly migrates existing projects from web to native storage on first run
### Android Development
#### Prerequisites
- [Android Studio](https://developer.android.com/studio) installed
- Android SDK and build tools
- Java Development Kit (JDK) 17 or higher
#### Building for Android
1. **Build the web app:**
```bash
npm run build
```
2. **Sync web assets to Android:**
```bash
npm run android:sync
```
3. **Open in Android Studio:**
```bash
npm run android:open
```
4. **Build APK directly (optional):**
```bash
npm run android:build
```
5. **Run on device/emulator:**
```bash
npm run android:run
```
#### Available Scripts
- `android:build` - Build web app and create Android APK
- `android:open` - Open the Android project in Android Studio
- `android:sync` - Sync web assets to Android project
- `android:run` - Build, sync, and run on connected device/emulator
#### Mobile Features
- **Native status bar integration** with theme-aware styling
- **Splash screen** with Shakespeare branding
- **Keyboard handling** for better mobile UX
- **Hardware back button** support on Android
- **Safe area support** for modern devices with notches
- **Touch-optimized** UI elements (44px minimum touch targets)
- **Responsive design** that adapts to mobile screens
#### Customization
The mobile app can be customized by editing:
- `capacitor.config.ts` - Capacitor configuration
- `android/app/src/main/res/` - Android resources (icons, splash screens)
- `src/capacitor.ts` - Mobile-specific initialization code
+7
View File
@@ -40,11 +40,18 @@ 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 -1
View File
@@ -3,13 +3,15 @@
<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, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
<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' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
<link rel="icon" type="image/png" href="/favicon.png"> <link rel="icon" type="image/png" href="/shakespeare.png">
<link rel="manifest" href="/manifest.webmanifest"> <link rel="manifest" href="/manifest.webmanifest">
</head> </head>
<body> <body>
+1028 -3
View File
File diff suppressed because it is too large. Load diff
+16 -1
View File
@@ -8,9 +8,22 @@
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'", "build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
"typecheck": "npm i --silent && tsc --noEmit", "typecheck": "npm i --silent && tsc --noEmit",
"test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'", "test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'",
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup" "deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup",
"android:aab": "npm run android:sync && cd android && ./gradlew bundleRelease && cd .. && cp android/app/build/outputs/bundle/release/app-release.aab shakespeare.aab",
"android:apk": "npm run android:sync && cd android && ./gradlew assembleRelease && cd .. && cp android/app/build/outputs/apk/release/app-release.apk shakespeare.apk",
"android:open": "npx cap open android",
"android:sync": "npm run build && npx cap sync android && npm run android:assets",
"android:run": "npm run android:sync && npx cap run android",
"android:assets": "npx -y @capacitor/assets generate --pwaManifestPath=.tmp.webmanifest && rm .tmp.webmanifest && rm -rf icons"
}, },
"dependencies": { "dependencies": {
"@capacitor/android": "^7.4.3",
"@capacitor/app": "^7.1.0",
"@capacitor/core": "^7.4.3",
"@capacitor/filesystem": "^7.1.4",
"@capacitor/keyboard": "^7.0.3",
"@capacitor/splash-screen": "^7.0.3",
"@capacitor/status-bar": "^7.0.3",
"@dnd-kit/core": "^6.3.1", "@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0", "@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2", "@dnd-kit/utilities": "^3.2.2",
@@ -82,6 +95,7 @@
"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",
@@ -90,6 +104,7 @@
"zod": "^3.25.76" "zod": "^3.25.76"
}, },
"devDependencies": { "devDependencies": {
"@capacitor/cli": "^7.4.3",
"@eslint/js": "^9.9.0", "@eslint/js": "^9.9.0",
"@html-eslint/eslint-plugin": "^0.41.0", "@html-eslint/eslint-plugin": "^0.41.0",
"@html-eslint/parser": "^0.41.0", "@html-eslint/parser": "^0.41.0",
+10 -3
View File
@@ -5,15 +5,22 @@
"start_url": "/", "start_url": "/",
"display": "standalone", "display": "standalone",
"background_color": "#ffffff", "background_color": "#ffffff",
"theme_color": "#000000", "theme_color": "#8b5cf6",
"orientation": "portrait-primary",
"categories": [
"productivity",
"developer",
"utilities"
],
"lang": "en",
"icons": [ "icons": [
{ {
"src": "/favicon.png", "src": "/shakespeare.png",
"sizes": "192x192", "sizes": "192x192",
"type": "image/png" "type": "image/png"
}, },
{ {
"src": "/favicon.png", "src": "/shakespeare.png",
"sizes": "512x512", "sizes": "512x512",
"type": "image/png" "type": "image/png"
} }
File renamed without changes.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 18 KiB

+63
View File
@@ -0,0 +1,63 @@
<?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>

After

Width:  |  Height:  |  Size: 5.8 KiB

+7 -2
View File
@@ -16,8 +16,10 @@ 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 { 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';
@@ -38,7 +40,7 @@ const queryClient = new QueryClient({
}); });
const defaultConfig: AppConfig = { const defaultConfig: AppConfig = {
theme: "light", theme: "system",
relayUrl: "wss://relay.primal.net", relayUrl: "wss://relay.primal.net",
deployServer: "shakespeare.wtf", deployServer: "shakespeare.wtf",
}; };
@@ -50,7 +52,7 @@ const presetRelays = [
{ url: 'wss://relay.primal.net', name: 'Primal' }, { url: 'wss://relay.primal.net', name: 'Primal' },
]; ];
// Initialize LightningFS // Initialize the filesystem
const lightningFS = new LightningFS('shakespeare-fs'); const lightningFS = new LightningFS('shakespeare-fs');
const fs = new LightningFSAdapter(lightningFS.promises); const fs = new LightningFSAdapter(lightningFS.promises);
@@ -73,6 +75,7 @@ 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>
<NostrLoginProvider storageKey='nostr:login'> <NostrLoginProvider storageKey='nostr:login'>
<NostrProvider> <NostrProvider>
<AISettingsProvider> <AISettingsProvider>
@@ -80,6 +83,7 @@ export function App() {
<SessionManagerProvider> <SessionManagerProvider>
<TooltipProvider> <TooltipProvider>
<Toaster /> <Toaster />
<DynamicFavicon />
<Suspense> <Suspense>
<AppRouter /> <AppRouter />
</Suspense> </Suspense>
@@ -89,6 +93,7 @@ export function App() {
</AISettingsProvider> </AISettingsProvider>
</NostrProvider> </NostrProvider>
</NostrLoginProvider> </NostrLoginProvider>
</ConsoleErrorProvider>
</FSProvider> </FSProvider>
</AppProvider> </AppProvider>
</QueryClientProvider> </QueryClientProvider>
+1 -2
View File
@@ -11,7 +11,7 @@ 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";
@@ -34,7 +34,6 @@ 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 />} />
+41
View File
@@ -0,0 +1,41 @@
import { Capacitor } from '@capacitor/core';
import { StatusBar, Style } from '@capacitor/status-bar';
import { SplashScreen } from '@capacitor/splash-screen';
import { Keyboard } from '@capacitor/keyboard';
import { App } from '@capacitor/app';
export const initializeCapacitor = async () => {
if (Capacitor.isNativePlatform()) {
// Hide splash screen
await SplashScreen.hide();
// Configure status bar
await StatusBar.setStyle({ style: Style.Default });
// Configure keyboard behavior
Keyboard.addListener('keyboardWillShow', () => {
document.body.classList.add('keyboard-open');
});
Keyboard.addListener('keyboardWillHide', () => {
document.body.classList.remove('keyboard-open');
});
// Handle app state changes
App.addListener('appStateChange', ({ isActive }) => {
console.log('App state changed. Is active?', isActive);
});
// Handle back button on Android
App.addListener('backButton', ({ canGoBack }) => {
if (!canGoBack) {
App.exitApp();
} else {
window.history.back();
}
});
}
};
export const isNativePlatform = () => Capacitor.isNativePlatform();
export const getPlatform = () => Capacitor.getPlatform();
+6 -1
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 } from 'lucide-react'; 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 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';
@@ -150,6 +150,11 @@ 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,
+20 -50
View File
@@ -5,9 +5,9 @@ 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 { useAISettings } from '@/hooks/useAISettings'; // import { useAISettings } from '@/hooks/useAISettings';
import { useAICredits } from '@/hooks/useAICredits'; import { useAICredits } from '@/hooks/useAICredits';
import { useLocalStorage } from '@/hooks/useLocalStorage'; // import { useLocalStorage } from '@/hooks/useLocalStorage';
interface Act1DialogProps { interface Act1DialogProps {
open: boolean; open: boolean;
@@ -22,44 +22,39 @@ const SHAKESPEARE_PROVIDER = {
nostr: true, nostr: true,
}; };
const MKSTACK_NSP_ADDR = '31999:4bcaa7b5606e3c14df05cd497e588f5d3fe559b4e9a425e8b418a43af1ffb015:mkstack'; // const MKSTACK_NSP_ADDR = '31999:4bcaa7b5606e3c14df05cd497e588f5d3fe559b4e9a425e8b418a43af1ffb015:mkstack';
export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) { export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
const [step, setStep] = useState<DialogStep>('welcome'); const [step, setStep] = useState<DialogStep>('welcome');
const [isSettingUp, setIsSettingUp] = useState(false); // const { setProvider, updateSettings } = useAISettings();
const { setProvider, updateSettings } = useAISettings();
// Get the selectedNSPAddr from localStorage // // Get the selectedNSPAddr from localStorage
const [selectedNSPAddr] = useLocalStorage<string | null>('selectedNSPAddr', null); // const [selectedNSPAddr] = useLocalStorage<string | null>('selectedNSPAddr', null);
// Get user's credits // Get user's credits
const { data: creditsData } = useAICredits(SHAKESPEARE_PROVIDER); const { data: creditsData } = useAICredits(SHAKESPEARE_PROVIDER);
const handleGetStarted = async () => { const handleGetStarted = async () => {
setIsSettingUp(true);
try { try {
// Add Shakespeare provider to their config // // Add Shakespeare provider to their config
setProvider(SHAKESPEARE_PROVIDER); // setProvider(SHAKESPEARE_PROVIDER);
// Configure recently used models based on credits or NSP // // Configure recently used models based on credits or NSP
const hasCredits = creditsData?.amount && creditsData.amount > 0; // const hasCredits = creditsData?.amount && creditsData.amount > 0;
const hasMKStackNSP = selectedNSPAddr === MKSTACK_NSP_ADDR; // const hasMKStackNSP = selectedNSPAddr === MKSTACK_NSP_ADDR;
if (hasCredits || hasMKStackNSP) { // if (hasCredits || hasMKStackNSP) {
// User has credits or MKStack NSP - set to shakespeare model // // User has credits or MKStack NSP - set to shakespeare model
updateSettings({ recentlyUsedModels: ['shakespeare/shakespeare'] }); // updateSettings({ recentlyUsedModels: ['shakespeare/shakespeare'] });
} else { // } else {
// No credits - set to tybalt model (free) // // No credits - set to tybalt model (free)
updateSettings({ recentlyUsedModels: ['shakespeare/tybalt'] }); // updateSettings({ recentlyUsedModels: ['shakespeare/tybalt'] });
} // }
// Move to migration step // Move to migration step
setStep('migration'); setStep('migration');
} catch (error) { } catch (error) {
console.error('Failed to configure Shakespeare provider:', error); console.error('Failed to configure Shakespeare provider:', error);
} finally {
setIsSettingUp(false);
} }
}; };
@@ -87,7 +82,6 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
useEffect(() => { useEffect(() => {
if (open) { if (open) {
setStep('welcome'); setStep('welcome');
setIsSettingUp(false);
} }
}, [open]); }, [open]);
@@ -126,12 +120,6 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
<ArrowLeft className="h-4 w-4" /> <ArrowLeft className="h-4 w-4" />
</Button> </Button>
)} )}
<span className="text-xl">
{step === 'welcome' && 'Welcome to Shakespeare: Act 2! 🎭'}
{step === 'migration' && 'Migrating Your Projects'}
{step === 'credits' && 'Your Credits'}
{step === 'conclusion' && "You're All Set!"}
</span>
</DialogTitle> </DialogTitle>
</DialogHeader> </DialogHeader>
@@ -197,21 +185,10 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
<Button <Button
onClick={handleGetStarted} onClick={handleGetStarted}
disabled={isSettingUp}
size="lg" size="lg"
className="gap-2" className="gap-2"
> >
{isSettingUp ? ( Next
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white" />
Setting up...
</>
) : (
<>
<Sparkles className="h-4 w-4" />
Configure Act 2
</>
)}
</Button> </Button>
</div> </div>
)} )}
@@ -343,14 +320,7 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
<div className="space-y-3"> <div className="space-y-3">
<h2 className="text-2xl font-bold">Welcome to the Future!</h2> <h2 className="text-2xl font-bold">Welcome to the Future!</h2>
<p className="text-lg text-muted-foreground max-w-md mx-auto"> <p className="text-lg text-muted-foreground max-w-md mx-auto">
You're all set up with Act 2! Your AI assistant is configured You're all up to speed with Act 2! Get ready to build amazing Nostr applications.
and ready to help you build amazing Nostr applications.
</p>
</div>
<div className="bg-muted/50 rounded-lg p-4 max-w-md mx-auto">
<p className="text-sm text-muted-foreground italic">
"Create a decentralized social media app with custom feeds and real-time messaging..."
</p> </p>
</div> </div>
+3 -5
View File
@@ -18,7 +18,6 @@ interface AppLayoutProps {
export function AppLayout({ export function AppLayout({
children, children,
selectedProject = null, selectedProject = null,
title = "Shakespeare",
showSidebar = true, showSidebar = true,
headerContent headerContent
}: AppLayoutProps) { }: AppLayoutProps) {
@@ -73,7 +72,8 @@ 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="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"> <header className="bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur pt-safe">
<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
@@ -85,11 +85,9 @@ export function AppLayout({
<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">
{title}
</h1>
</div> </div>
{headerContent} {headerContent}
</div>
</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 */}
@@ -0,0 +1,152 @@
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
@@ -0,0 +1,63 @@
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>
);
}
+11 -18
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
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 className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-full max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none"> <DialogContent 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">
<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 ? (
@@ -464,26 +464,19 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
</div> </div>
<div className="space-y-3"> <div className="space-y-3">
<Label htmlFor="payment-method" className="text-sm font-medium">Payment Method</Label> <Label className="text-sm font-medium">Payment Method</Label>
<Select value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)}> <Tabs value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)} className="w-full">
<SelectTrigger> <TabsList className="grid w-full grid-cols-2">
<SelectValue /> <TabsTrigger value="stripe" className="flex items-center gap-2">
</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
</div> </TabsTrigger>
</SelectItem> <TabsTrigger value="lightning" className="flex items-center gap-2">
<SelectItem value="lightning">
<div className="flex items-center gap-2">
<Zap className="h-4 w-4" /> <Zap className="h-4 w-4" />
Lightning Lightning
</div> </TabsTrigger>
</SelectItem> </TabsList>
</SelectContent> </Tabs>
</Select>
</div> </div>
<Button <Button
+151
View File
@@ -0,0 +1,151 @@
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
@@ -0,0 +1,204 @@
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>
);
}
+30 -3
View File
@@ -1,5 +1,5 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate, useSearchParams } 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", "gitnostr.com"]; const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev"];
interface GitDialogProps { interface GitDialogProps {
projectId: string; projectId: string;
@@ -62,6 +62,7 @@ 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);
@@ -334,6 +335,7 @@ 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);
@@ -395,6 +397,7 @@ 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);
@@ -425,6 +428,12 @@ 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,
@@ -436,20 +445,38 @@ 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: `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}`, description: repoChanged
? `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);
+225
View File
@@ -1,5 +1,7 @@
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';
@@ -12,6 +14,10 @@ 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 {
@@ -22,9 +28,11 @@ 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();
@@ -50,6 +58,8 @@ 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 () => {
@@ -237,4 +247,219 @@ 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
});
}); });
+97 -6
View File
@@ -1,14 +1,16 @@
import { useState, useMemo } from 'react'; import { useState, useMemo, useEffect } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings } from 'lucide-react'; import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings, TriangleAlert } 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 {
@@ -32,6 +34,7 @@ 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;
@@ -42,6 +45,7 @@ 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');
@@ -82,9 +86,43 @@ 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);
@@ -125,6 +163,7 @@ 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}
@@ -144,10 +183,61 @@ export function ModelSelector({
<Check className="h-3 w-3" /> <Check className="h-3 w-3" />
</Button> </Button>
</div> </div>
</TooltipProvider>
); );
} }
return ( return (
<TooltipProvider>
<div className={cn("flex justify-end gap-0.5", className)}>
{isCurrentModelFree && (
<Tooltip
open={isMobile ? isTooltipOpen : undefined}
onOpenChange={isMobile ? setIsTooltipOpen : undefined}
delayDuration={isMobile ? 0 : 700}
disableHoverableContent={isMobile}
>
<TooltipTrigger asChild>
<button
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"
aria-label="Free model warning"
tabIndex={isMobile ? 0 : -1}
onClick={isMobile ? (e) => {
e.preventDefault();
e.stopPropagation();
setIsTooltipOpen(!isTooltipOpen);
} : undefined}
onTouchStart={isMobile ? (e) => {
e.preventDefault();
e.stopPropagation();
} : undefined}
onTouchEnd={isMobile ? (e) => {
e.preventDefault();
e.stopPropagation();
setIsTooltipOpen(!isTooltipOpen);
} : 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}> <Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild> <PopoverTrigger asChild>
<Button <Button
@@ -155,18 +245,17 @@ export function ModelSelector({
role="combobox" role="combobox"
aria-expanded={open} aria-expanded={open}
className={cn( className={cn(
"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", "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"
className
)} )}
disabled={disabled} disabled={disabled}
> >
<span className="w-full truncate"> <span className="truncate">
{value || placeholder || defaultPlaceholder} {value || placeholder || defaultPlaceholder}
</span> </span>
<ChevronDown className="size-3 shrink-0 opacity-50" /> <ChevronDown className="size-3 shrink-0 opacity-50" />
</Button> </Button>
</PopoverTrigger> </PopoverTrigger>
<PopoverContent className="w-96 p-0" align="end"> <PopoverContent className="p-0" align="end">
<Command> <Command>
{(isConfigured && models.length >= 5) && ( {(isConfigured && models.length >= 5) && (
<CommandInput placeholder={t('searchModels')} className="h-9" /> <CommandInput placeholder={t('searchModels')} className="h-9" />
@@ -289,5 +378,7 @@ export function ModelSelector({
</Command> </Command>
</PopoverContent> </PopoverContent>
</Popover> </Popover>
</div>
</TooltipProvider>
); );
} }
-1
View File
@@ -18,7 +18,6 @@ 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) => {
@@ -0,0 +1,103 @@
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
@@ -0,0 +1,42 @@
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.getAllByText('Welcome to Shakespeare!')).toHaveLength(2); // Title and heading expect(screen.getByText('Welcome to Shakespeare!')).toBeInTheDocument(); // Only in dialog title now
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();
}); });
+346 -52
View File
@@ -1,59 +1,101 @@
import { Capacitor } from '@capacitor/core';
import { Decimal } from 'decimal.js'; import { Decimal } from 'decimal.js';
import { useState, useEffect } from 'react'; import { useState, useEffect, useRef } 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 } from 'lucide-react'; import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, ExternalLink } 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 { ScrollArea } from '@/components/ui/scroll-area'; import { Checkbox } from '@/components/ui/checkbox';
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' | 'model-selection' | 'conclusion'; type OnboardingStep = 'welcome' | 'open-source' | 'provider-selection' | '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 Shakespeare provider models // Filter models to only show selected provider models
const shakespeareModels = models.filter(model => model.provider === 'shakespeare'); const providerModels = selectedProvider
? 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, generate and login with secret key // If user is not logged in and provider uses Nostr auth, generate and login with secret key
if (!user) { if (!user && selectedProvider.nostr) {
const secretKey = generateSecretKey(); const secretKey = generateSecretKey();
const nsec = nip19.nsecEncode(secretKey); const nsec = nip19.nsecEncode(secretKey);
login.nsec(nsec); login.nsec(nsec);
} }
// Add Shakespeare provider to their config // Add selected provider to their config
setProvider(SHAKESPEARE_PROVIDER); const providerConfig = {
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');
@@ -75,7 +117,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 = shakespeareModels.find(m => m.fullId === selectedModel); const model = providerModels.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)
); );
@@ -110,19 +152,30 @@ 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 max-h-[80vh] overflow-hidden"> <DialogContent className="max-w-2xl h-dvh-safe sm:h-auto sm:max-h-[90vh] flex flex-col">
<DialogHeader> <DialogHeader className="flex-shrink-0">
<DialogTitle className="flex items-center gap-2"> <DialogTitle className="flex items-center gap-2">
{step === 'model-selection' && ( {step === 'open-source' && (
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
@@ -132,18 +185,48 @@ 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 className="flex-1 overflow-hidden"> <div ref={scrollableContentRef} className="flex-1 overflow-y-auto min-h-0">
{step === 'welcome' && ( {step === 'welcome' && (
<div className="text-center space-y-6 py-4"> <div className="text-center space-y-6 py-4">
<div className="text-6xl mb-4">🎭</div> <div className="mb-4">
<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!
@@ -190,16 +273,215 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
</div> </div>
)} )}
{step === 'model-selection' && ( {step === 'open-source' && (
<div className="space-y-4"> <div className="space-y-6 py-4">
<div className="text-center space-y-2"> <div className="text-center space-y-4">
<p className="text-muted-foreground"> <h2 className="text-2xl font-bold">
Choose an AI model to power your development experience. Shakespeare is Open Source software that runs entirely {Capacitor.isNativePlatform() ? 'on your device' : 'in your web browser'}
Different models offer various capabilities and pricing. </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{Capacitor.isNativePlatform() ? '' : ' 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 {Capacitor.isNativePlatform() ? 'app' : '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> </p>
</div> </div>
<ScrollArea className="h-96"> <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' && (
<div className="flex flex-col h-full">
<div className="flex-1 overflow-y-auto min-h-0 my-4">
<div className="space-y-3 p-1"> <div className="space-y-3 p-1">
{isLoadingModels ? ( {isLoadingModels ? (
<> <>
@@ -219,7 +501,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
</Card> </Card>
))} ))}
</> </>
) : shakespeareModels.length === 0 ? ( ) : providerModels.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" />
@@ -229,9 +511,11 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
</div> </div>
</Card> </Card>
) : ( ) : (
shakespeareModels.map((model) => { providerModels.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
@@ -241,15 +525,19 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
}`} }`}
onClick={() => handleModelSelect(model.fullId)} onClick={() => handleModelSelect(model.fullId)}
> >
<CardHeader className="pb-3"> <CardHeader>
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex-1"> <div className="flex-1">
<CardTitle className="text-base font-semibold"> <CardTitle className={cn('text-xl font-semibold', {
{model.description || model.name || model.id} 'bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent': isPremium,
})}>
{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.name || model.id} {model.description.length > 70
? model.description.slice(0, 70) + '...'
: model.description}
</p> </p>
)} )}
</div> </div>
@@ -259,6 +547,11 @@ 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" />
@@ -267,27 +560,29 @@ 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>
</ScrollArea> </div>
<div className="flex justify-end gap-2 pt-4 border-t"> <div className="flex justify-end gap-2 pt-4 flex-shrink-0">
<Button <Button
onClick={handleContinue} onClick={handleContinue}
disabled={!selectedModel} disabled={!selectedModel}
@@ -310,11 +605,6 @@ 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
@@ -326,7 +616,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
</Dialog> </Dialog>
{/* Credits Dialog */} {/* Credits Dialog */}
{showCreditsDialog && selectedModel && ( {showCreditsDialog && selectedModel && selectedProvider && (
<CreditsDialog <CreditsDialog
open={showCreditsDialog} open={showCreditsDialog}
onOpenChange={(open) => { onOpenChange={(open) => {
@@ -334,7 +624,11 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
handleCreditsDialogClose(); handleCreditsDialogClose();
} }
}} }}
provider={SHAKESPEARE_PROVIDER} provider={{
id: selectedProvider.id,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
}}
/> />
)} )}
</> </>
+1 -1
View File
@@ -60,7 +60,7 @@ describe('ProjectSidebar', () => {
</TestApp> </TestApp>
); );
expect(screen.getByText('🎭')).toBeInTheDocument(); expect(screen.getByAltText('Shakespeare')).toBeInTheDocument();
expect(screen.getByText('Shakespeare')).toBeInTheDocument(); expect(screen.getByText('Shakespeare')).toBeInTheDocument();
}); });
+9 -43
View File
@@ -1,7 +1,7 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, FileArchive } from 'lucide-react'; import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } 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,12 +9,10 @@ import { useProjects } from '@/hooks/useProjects';
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus'; import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
import { useLocalStorage } from '@/hooks/useLocalStorage'; import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useIsMobile } from '@/hooks/useIsMobile'; import { useIsMobile } from '@/hooks/useIsMobile';
import { ZipImportDialog } from '@/components/ZipImportDialog';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useToast } from '@/hooks/useToast';
import type { Project } from '@/lib/ProjectsManager'; import type { Project } from '@/lib/ProjectsManager';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { useQueryClient } from '@tanstack/react-query'; import { useQueryClient } from '@tanstack/react-query';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
interface ProjectItemProps { interface ProjectItemProps {
project: Project; project: Project;
@@ -95,9 +93,6 @@ export function ProjectSidebar({
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const { data: projects = [], isLoading, error } = useProjects(); const { data: projects = [], isLoading, error } = useProjects();
const [favorites] = useLocalStorage<string[]>('project-favorites', []); const [favorites] = useLocalStorage<string[]>('project-favorites', []);
const projectsManager = useProjectsManager();
const { toast } = useToast();
const [isZipDialogOpen, setIsZipDialogOpen] = useState(false);
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const navigate = useNavigate(); const navigate = useNavigate();
@@ -123,24 +118,7 @@ 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'] });
@@ -153,13 +131,14 @@ 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="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="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">
<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>
@@ -183,6 +162,7 @@ export function ProjectSidebar({
)} )}
</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">
@@ -211,13 +191,6 @@ 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>
@@ -258,8 +231,8 @@ export function ProjectSidebar({
</div> </div>
{/* Settings and Help at Bottom */} {/* Settings and Help at Bottom */}
<div className="p-2 border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto"> <div className="border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto pb-safe">
<div className="flex items-center gap-2"> <div className="p-2 flex items-center gap-2">
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
@@ -280,13 +253,6 @@ export function ProjectSidebar({
</Button> </Button>
</div> </div>
</div> </div>
{/* ZIP Import Dialog */}
<ZipImportDialog
onImport={handleImportZip}
open={isZipDialogOpen}
onOpenChange={setIsZipDialogOpen}
/>
</div> </div>
); );
} }
+80
View File
@@ -0,0 +1,80 @@
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();
});
});
+12 -1
View File
@@ -7,8 +7,9 @@ import { useAISettings } from '@/hooks/useAISettings';
import { parseProviderModel } from '@/lib/parseProviderModel'; import { parseProviderModel } from '@/lib/parseProviderModel';
import { useAICredits } from '@/hooks/useAICredits'; import { useAICredits } from '@/hooks/useAICredits';
import { CreditsDialog } from './CreditsDialog'; import { CreditsDialog } from './CreditsDialog';
import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool'; import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
import { useState } from 'react'; import { useState } from 'react';
import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError';
export interface QuillyProps { export interface QuillyProps {
error: Error; error: Error;
@@ -58,6 +59,16 @@ 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) {
+4 -11
View File
@@ -3,7 +3,7 @@ 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, Mail } from 'lucide-react'; import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info } 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';
@@ -56,13 +56,6 @@ 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'),
@@ -127,10 +120,10 @@ export function SettingsLayout() {
if (isMobile) { if (isMobile) {
return ( return (
<div className="min-h-dvh bg-background"> <div className="min-h-dvh pb-safe bg-background">
{/* Mobile Header */} {/* Mobile Header */}
<header className="h-12 border-b bg-background px-4 py-3 flex items-center justify-between"> <header className="pt-safe bg-background">
<div className="flex items-center space-x-2"> <div className="flex items-center space-x-2 h-12 border-b px-4 py-3">
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
+58 -25
View File
@@ -34,13 +34,15 @@ import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool';
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool'; import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
import { ShellTool } from '@/lib/tools/ShellTool'; import { ShellTool } from '@/lib/tools/ShellTool';
import { TypecheckTool } from '@/lib/tools/TypecheckTool'; import { TypecheckTool } from '@/lib/tools/TypecheckTool';
import { ReadConsoleMessagesTool, ProjectPreviewConsoleError, addErrorListener, removeErrorListener } from '@/lib/tools/ReadConsoleMessagesTool'; import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
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
@@ -51,6 +53,8 @@ interface ChatPaneProps {
onLoadingChange?: (isLoading: boolean) => void; onLoadingChange?: (isLoading: boolean) => void;
isLoading?: boolean; isLoading?: boolean;
isBuildLoading?: boolean; isBuildLoading?: boolean;
consoleError?: ProjectPreviewConsoleError | null;
onDismissConsoleError?: () => void;
} }
export interface ChatPaneRef { export interface ChatPaneRef {
@@ -64,6 +68,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
onLoadingChange, onLoadingChange,
isLoading: externalIsLoading, isLoading: externalIsLoading,
isBuildLoading: externalIsBuildLoading, isBuildLoading: externalIsBuildLoading,
consoleError,
onDismissConsoleError,
}, ref) => { }, ref) => {
const { t } = useTranslation(); const { t } = useTranslation();
const [searchParams, setSearchParams] = useSearchParams(); const [searchParams, setSearchParams] = useSearchParams();
@@ -80,18 +86,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const [isStuck, setIsStuck] = useState(false); const [isStuck, setIsStuck] = useState(false);
const [aiError, setAIError] = useState<Error | null>(null); const [aiError, setAIError] = useState<Error | null>(null);
// Console error handling // Determine which error to show - console error takes priority over AI errors
useEffect(() => { const displayError = consoleError || aiError;
const handleConsoleError = (error: ProjectPreviewConsoleError) => {
// Only show console errors if there's no existing AI error
if (!aiError) {
setAIError(error);
}
};
addErrorListener(handleConsoleError);
return () => removeErrorListener(handleConsoleError);
}, [aiError]);
// Use external state if provided, otherwise default to false // Use external state if provided, otherwise default to false
const isBuildLoading = externalIsBuildLoading || false; const isBuildLoading = externalIsBuildLoading || false;
@@ -185,7 +181,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
artist: `Working on ${projectId}...`, artist: `Working on ${projectId}...`,
artwork: [ artwork: [
{ {
src: '/favicon.png', src: '/shakespeare.png',
sizes: '512x512', sizes: '512x512',
type: 'image/png' type: 'image/png'
} }
@@ -208,6 +204,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
isLoading: internalIsLoading, isLoading: internalIsLoading,
totalCost, totalCost,
lastInputTokens, lastInputTokens,
addMessage,
sendMessage, sendMessage,
startGeneration, startGeneration,
stopGeneration, stopGeneration,
@@ -221,9 +218,42 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}); });
// Handle console error help requests // Handle console error help requests
const handleConsoleErrorHelp = useCallback(() => { const handleConsoleErrorHelp = useCallback(async () => {
sendMessage('Read the console messages and fix any errors present.', providerModel); const tool = new ReadConsoleMessagesTool();
}, [sendMessage, providerModel]); const toolCallId = `call_${crypto.randomUUID().replace(/-/g, '')}`;
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;
@@ -271,10 +301,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
setIsModelSelectorOpen(true); setIsModelSelectorOpen(true);
}, []); }, []);
// Scroll to bottom when AI error occurs // Scroll to bottom when any error occurs (AI error or console error)
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(() => {
@@ -525,7 +557,9 @@ 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="text-6xl mb-6">🎭</div> <div className="mb-6">
<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')}
@@ -608,11 +642,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</div> </div>
)} )}
{/* AI Error Alert */} {/* Error Alert (Console or AI) */}
{aiError && ( {displayError && (
<Quilly <Quilly
error={aiError} error={displayError}
onDismiss={() => setAIError(null)} onDismiss={handleErrorDismiss}
onNewChat={onNewChat} onNewChat={onNewChat}
onOpenModelSelector={openModelSelector} onOpenModelSelector={openModelSelector}
onRequestConsoleErrorHelp={handleConsoleErrorHelp} onRequestConsoleErrorHelp={handleConsoleErrorHelp}
@@ -730,7 +764,6 @@ 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}
+86 -13
View File
@@ -3,12 +3,13 @@ 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/tools/ReadConsoleMessagesTool'; import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/consoleMessages';
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 } from 'lucide-react'; import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload, X, Terminal } 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';
@@ -27,6 +28,7 @@ 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
@@ -76,7 +78,8 @@ 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'>('explorer'); const [mobileCodeView, setMobileCodeView] = useState<'explorer' | 'editor' | 'terminal'>('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('/');
@@ -88,6 +91,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
const { fs } = useFS(); const { fs } = useFS();
const projectsManager = useProjectsManager(); const projectsManager = useProjectsManager();
// 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);
const [searchParams, setSearchParams] = useSearchParams(); const [searchParams, setSearchParams] = useSearchParams();
@@ -451,16 +457,24 @@ 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();
@@ -494,6 +508,12 @@ 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);
} }
@@ -503,6 +523,8 @@ 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);
@@ -513,9 +535,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
} }
}; };
const consoleMessages = getConsoleMessages(); const messageCount = messages.length;
const messageCount = consoleMessages.length;
const hasErrors = consoleMessages.some(msg => msg.level === 'error');
return ( return (
<Popover open={isOpen} onOpenChange={setIsOpen}> <Popover open={isOpen} onOpenChange={setIsOpen}>
@@ -523,10 +543,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 hover:bg-accent hover:text-accent-foreground transition-colors" className="h-8 w-8 p-0 relative"
> >
<Bug className="h-4 w-4" /> <Bug className="h-4 w-4" />
{hasErrors && ( {hasConsoleErrors && (
<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>
@@ -546,7 +566,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>
) : ( ) : (
consoleMessages.map((msg, index) => ( messages.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"
@@ -729,9 +749,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
<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"> <div className="h-full flex flex-col min-h-0">
{mobileCodeView === 'explorer' ? ( {mobileCodeView === 'explorer' ? (
<ScrollArea className="flex-1"> <div className="flex-1 relative min-h-0">
<ScrollArea className="h-full">
<ScrollBar orientation="horizontal" /> <ScrollBar orientation="horizontal" />
<div className="min-w-max"> <div className="min-w-max">
<FileTree <FileTree
@@ -741,6 +762,35 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
/> />
</div> </div>
</ScrollArea> </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 className="flex-1 min-h-0">
<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">
@@ -803,18 +853,39 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
{t('backToPreview')} {t('backToPreview')}
</Button> </Button>
<div className="flex-1" /> <div className="flex-1" />
<GitStatusIndicator projectId={projectId} /> <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>
</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="flex-1">
<TerminalComponent projectId={projectId} />
</div>
) : (
<>
<div className="w-1/3 border-r flex flex-col"> <div className="w-1/3 border-r flex flex-col">
<ScrollArea className="flex-1"> <ScrollArea className="flex-1">
<ScrollBar orientation="horizontal" /> <ScrollBar orientation="horizontal" />
@@ -847,6 +918,8 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
</div> </div>
)} )}
</div> </div>
</>
)}
</div> </div>
</div> </div>
)} )}
+13
View File
@@ -0,0 +1,13 @@
export interface ShakespeareLogoProps {
className?: string;
}
export function ShakespeareLogo({ className }: ShakespeareLogoProps) {
return (
<img
src="/shakespeare.svg"
alt="Shakespeare"
className={className}
/>
);
}
+240
View File
@@ -0,0 +1,240 @@
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
@@ -0,0 +1,12 @@
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>
);
}
+5 -5
View File
@@ -41,7 +41,7 @@ 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>
@@ -63,7 +63,7 @@ const AddWalletContent = forwardRef<HTMLDivElement, {
/> />
</div> </div>
</div> </div>
)); ));
AddWalletContent.displayName = 'AddWalletContent'; AddWalletContent.displayName = 'AddWalletContent';
// Extracted WalletContent to prevent re-renders // Extracted WalletContent to prevent re-renders
@@ -77,7 +77,7 @@ 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,
@@ -87,7 +87,7 @@ const WalletContent = forwardRef<HTMLDivElement, {
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">
@@ -202,7 +202,7 @@ const WalletContent = forwardRef<HTMLDivElement, {
</> </>
)} )}
</div> </div>
)); ));
WalletContent.displayName = 'WalletContent'; WalletContent.displayName = 'WalletContent';
export function WalletModal({ children, className }: WalletModalProps) { export function WalletModal({ children, className }: WalletModalProps) {
+1 -1
View File
@@ -201,7 +201,7 @@ 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,
+1 -1
View File
@@ -371,6 +371,6 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
</DialogContent> </DialogContent>
</Dialog> </Dialog>
); );
}; };
export default LoginDialog; export default LoginDialog;
+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-accent hover:text-accent-foreground", "border border-input bg-background hover:bg-border/20 dark:hover:bg-border/50",
secondary: secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80", "bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground", ghost: "",
link: "text-primary underline-offset-4 hover:underline", link: "text-primary underline-offset-4 hover:underline",
}, },
size: { size: {
+1 -1
View File
@@ -20,7 +20,7 @@ const FormField = <
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} />
+2 -2
View File
@@ -36,7 +36,7 @@ const SidebarProvider = React.forwardRef<
open?: boolean open?: boolean
onOpenChange?: (open: boolean) => void onOpenChange?: (open: boolean) => void
} }
>( >(
( (
{ {
defaultOpen = true, defaultOpen = true,
@@ -135,7 +135,7 @@ const SidebarProvider = React.forwardRef<
</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-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]", "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]",
className className
)} )}
{...props} {...props}
+11
View File
@@ -0,0 +1,11 @@
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);
+1 -1
View File
@@ -36,6 +36,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.id === 'shakespeare' && !!user, enabled: !!provider.nostr && !!user,
}); });
} }
+35
View File
@@ -0,0 +1,35 @@
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
@@ -0,0 +1,12 @@
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
@@ -0,0 +1,16 @@
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 -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();
+14 -13
View File
@@ -110,11 +110,13 @@
@layer base { @layer base {
* { * {
@apply border-border; border-color: hsl(var(--border));
} }
body { body {
@apply bg-background text-foreground font-sans; background-color: hsl(var(--background));
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;
} }
@@ -138,8 +140,10 @@
} }
/* GitHub-style focus rings */ /* GitHub-style focus rings */
.focus-ring { .focus-ring:focus-visible {
@apply focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2; outline: none;
box-shadow: 0 0 0 2px hsl(var(--ring));
outline-offset: 2px;
} }
/* Smooth transitions for theme switching */ /* Smooth transitions for theme switching */
@@ -247,15 +251,6 @@
max-height: 100dvh; max-height: 100dvh;
} }
/* iOS Safe Area Support */
.safe-area-inset-bottom {
padding-bottom: env(safe-area-inset-bottom);
}
.safe-area-inset-top {
padding-top: env(safe-area-inset-top);
}
/* Mobile navigation button styles - text/icon highlighting only */ /* Mobile navigation button styles - text/icon highlighting only */
.mobile-nav-button, .mobile-nav-button,
.mobile-nav-button:hover, .mobile-nav-button:hover,
@@ -290,4 +285,10 @@
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
@@ -5,11 +5,13 @@
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, encoding: 'utf8'): Promise<string>; readFile(path: string, options: 'utf8'): Promise<string>;
readFile(path: string, encoding: string): Promise<string>; readFile(path: string, options: string): Promise<string>;
readFile(path: string, encoding?: string): Promise<string | Uint8Array>; readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
readFile(path: string, options: { encoding: string }): Promise<string>;
readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
writeFile(path: string, data: string | Uint8Array, encoding?: string): Promise<void>; writeFile(path: string, data: string | Uint8Array, options?: string | { 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[]>;
+11 -5
View File
@@ -9,14 +9,18 @@ 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, encoding: 'utf8'): Promise<string>; async readFile(path: string, options: 'utf8'): Promise<string>;
async readFile(path: string, encoding: string): 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 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, encoding?: string): Promise<void> { async writeFile(path: string, data: string | Uint8Array, options?: string | { 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);
} }
@@ -76,6 +80,7 @@ export class LightningFSAdapter implements JSRuntimeFS {
async stat(path: string): Promise<{ async stat(path: string): Promise<{
isDirectory(): boolean; isDirectory(): boolean;
isFile(): boolean; isFile(): boolean;
isSymbolicLink(): boolean;
size?: number; size?: number;
mtimeMs?: number; mtimeMs?: number;
}> { }> {
@@ -85,6 +90,7 @@ export class LightningFSAdapter implements JSRuntimeFS {
async lstat(path: string): Promise<{ async lstat(path: string): Promise<{
isDirectory(): boolean; isDirectory(): boolean;
isFile(): boolean; isFile(): boolean;
isSymbolicLink(): boolean;
size?: number; size?: number;
mtimeMs?: number; mtimeMs?: number;
}> { }> {
+68 -3
View File
@@ -41,15 +41,19 @@ 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, encoding: "utf8"): Promise<string>; async readFile(path: string, options: 'utf8'): Promise<string>;
async readFile(path: string, encoding: string): Promise<string | Uint8Array>; 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, 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;
@@ -440,6 +444,67 @@ 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();
+12
View File
@@ -290,6 +290,7 @@ export class ProjectsManager {
await this.fs.mkdir(projectPath); await this.fs.mkdir(projectPath);
try {
// Clone the repository (Git class now handles Nostr URIs automatically) // Clone the repository (Git class now handles Nostr URIs automatically)
await this.git.clone({ await this.git.clone({
dir: projectPath, dir: projectPath,
@@ -317,6 +318,17 @@ export class ProjectsManager {
path: projectPath, path: projectPath,
lastModified: timestamp, lastModified: timestamp,
}; };
} catch (error) {
// Clean up the directory that was created if cloning fails
try {
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;
}
} }
async getProjects(): Promise<Project[]> { async getProjects(): Promise<Project[]> {
+31 -6
View File
@@ -8,6 +8,7 @@ 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';
@@ -188,10 +189,6 @@ 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();
@@ -340,10 +337,20 @@ export class SessionManager {
} }
} }
// Fix tool calls with empty arguments // Fix tool calls with empty arguments or names
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),
});
}
} }
} }
@@ -370,10 +377,28 @@ 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;
} }
+62
View File
@@ -0,0 +1,62 @@
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
@@ -0,0 +1,88 @@
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
@@ -0,0 +1,135 @@
/**
* 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);
}
+49 -8
View File
@@ -5,6 +5,7 @@ interface PackageLock {
[key: string]: { [key: string]: {
name?: string; name?: string;
version: string; version: string;
peerDependencies?: { [key: string]: string };
} | undefined; } | undefined;
}; };
} }
@@ -61,6 +62,14 @@ 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("@")
@@ -69,10 +78,18 @@ 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 importerPackage = extractPackageName(args.importer); const { pathname } = new URL(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/${importerPackage}/node_modules/${packageName}`, `node_modules/${importerPkg}/node_modules/${packageName}`,
); );
} catch { } catch {
// fallthrough // fallthrough
@@ -89,12 +106,20 @@ 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;
if (!version) return; let version: string | undefined;
const name = packageInfo.name ?? packageName; if (importerPkg === packageName && importerVersion) {
const specifier = `${name}@${version}${packagePath}`; version = importerVersion;
} 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}`);
@@ -131,6 +156,14 @@ 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",
@@ -174,7 +207,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): string { function extractPackageName(esmShURL: string): { pkg?: string; version?: string } {
const full = new URL(esmShURL) const full = new URL(esmShURL)
.pathname .pathname
.slice(1) .slice(1)
@@ -184,7 +217,15 @@ function extractPackageName(esmShURL: string): string {
? full.split("/").slice(0, 2).join("/") ? full.split("/").slice(0, 2).join("/")
: full.split("/")[0]; : full.split("/")[0];
return full.startsWith("@") const pkg = 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 };
} }
+46 -13
View File
@@ -1,4 +1,4 @@
import path from "path-browserify"; import { join, dirname, extname } 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,27 +8,49 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin {
name: "fs", name: "fs",
setup(build) { setup(build) {
build.onResolve({ filter: /.*/ }, async (args) => { build.onResolve({ filter: /^data:/ }, (args) => {
let resolved: string; return {
path: args.path,
external: true,
};
});
if (args.path.startsWith("@/")) { build.onResolve({ filter: /.*/ }, async (args) => {
resolved = path.join(cwd, args.path.slice(2)); // Skip resolving paths from external URLs
if (/^https?:\/\//.test(args.importer)) {
return;
}
let resolved: string;
if (args.path.startsWith("/")) {
resolved = args.path;
} else if (args.path.startsWith("@/")) {
resolved = join(cwd, args.path.slice(2));
} else if (args.kind === "entry-point") { } else if (args.kind === "entry-point") {
resolved = path.join(cwd, args.path); resolved = join(cwd, args.path);
} else if (args.importer) { } else if (args.importer) {
resolved = path.join(path.dirname(args.importer), args.path); resolved = join(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, resolved); resolved = await tryFileVariants(fs, cleaned);
} catch { } catch {
return; // Let other plugins handle this return; // Let other plugins handle this
} }
return { return {
path: resolved, path: resolved + (typeof query === "string" ? "?" + query : ""),
namespace: "fs", namespace: "fs",
}; };
}); });
@@ -36,14 +58,25 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin {
build.onLoad( build.onLoad(
{ filter: /.*/, namespace: "fs" }, { filter: /.*/, namespace: "fs" },
async (args) => { async (args) => {
const ext = path.extname(args.path).slice(1); const [path, query] = args.path.split("?");
const params = new URLSearchParams(query);
if (!["ts", "tsx", "js", "jsx", "css"].includes(ext)) { // https://vite.dev/guide/assets.html#importing-asset-as-string
if (params.has("raw")) {
return {
contents: await fs.readFile(path, "utf8"),
loader: "text",
};
}
const ext = extname(path).slice(1);
if (!["ts", "tsx", "js", "jsx", "css", "json"].includes(ext)) {
return; return;
} }
return { return {
contents: await fs.readFile(args.path, "utf8"), contents: await fs.readFile(path, "utf8"),
loader: ext as Loader, loader: ext as Loader,
}; };
}, },
@@ -67,7 +100,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 = path.join(basePath, "index" + ext); const indexFile = 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;
+51 -15
View File
@@ -9,14 +9,28 @@ vi.mock('../esbuild', () => ({
build: vi.fn(() => ({ build: vi.fn(() => ({
outputFiles: [ outputFiles: [
{ {
path: '/stdin.js', path: '/stdin-abc123.js',
contents: new Uint8Array([1, 2, 3]), contents: new Uint8Array([1, 2, 3]),
text: '',
hash: 'abc123',
}, },
{ {
path: '/stdin.css', path: '/stdin-def456.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,
},
},
},
})), })),
})), })),
})); }));
@@ -52,9 +66,25 @@ 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(() => ({ querySelector: vi.fn((selector: string) => {
if (selector === 'meta[http-equiv="content-security-policy"]') {
// Return null for CSP meta tag (no CSP present in test)
return null;
}
return {
setAttribute: vi.fn(), 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(),
}, },
@@ -133,11 +163,13 @@ describe('buildProject', () => {
domParser: mockDOMParser, domParser: mockDOMParser,
}); });
// Should include built files // Should include built files with hashed names
expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3])); expect(result.files['stdin-abc123.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');
@@ -190,11 +222,13 @@ describe('buildProject', () => {
domParser: mockDOMParser, domParser: mockDOMParser,
}); });
// Should still include built files // Should still include built files with hashed names
expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3])); expect(result.files['stdin-abc123.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');
@@ -246,13 +280,15 @@ describe('buildProject', () => {
domParser: mockDOMParser, domParser: mockDOMParser,
}); });
// Should include built files // Should include built files with hashed names
expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3])); expect(result.files['stdin-abc123.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();
// Should have exactly 3 files (main.js, main.css, index.html) // CSS should be embedded in HTML, not as separate file
expect(Object.keys(result.files)).toHaveLength(3); expect(Object.keys(result.files)).not.toContain('stdin-def456.css');
// 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');
+87 -27
View File
@@ -1,6 +1,9 @@
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";
@@ -31,24 +34,51 @@ 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({
stdin: { entryPoints,
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),
], ],
@@ -60,18 +90,40 @@ 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 relativePath = file.path.replace(/^\//, ""); const ext = file.path.split('.').pop();
if (relativePath === "stdin.js") { const filename = `${file.path.slice(1)}`;
dist["main.js"] = file.contents; const entryPoint = results.metafile.outputs[filename]?.entryPoint?.replace(/^fs:/, '');
} else if (relativePath === "stdin.css") { const script = entryPoint ? entryScripts[entryPoint] : null;
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[relativePath] = file.contents; dist[filename] = file.contents;
} }
} }
// Update index.html with proper script and link tags // Parse CSP and ensure esm.sh is allowed for necessary directives
updateIndexHtml(doc); const cspMeta = doc.querySelector("meta[http-equiv=\"content-security-policy\"]");
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);
@@ -154,17 +206,25 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
}; };
} }
function updateIndexHtml(doc: Document): void { async function fileExists(fs: JSRuntimeFS, path: string): Promise<boolean> {
const entrypoint = doc.querySelector('script[src="/src/main.tsx"]'); try {
const stat = await fs.stat(path);
if (!entrypoint) { return stat.isFile();
throw new Error("No entrypoint script found in index.html"); } catch {
return false;
} }
}
entrypoint.setAttribute("src", "/main.js"); /** Updates CSP to allow esm.sh for scripts, assets, fonts, and CSS */
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
];
const style = doc.createElement("link"); return addDomainToCSP(csp, 'https://esm.sh', esmShDirectives);
style.setAttribute("rel", "stylesheet");
style.setAttribute("href", "/main.css");
doc.head.appendChild(style);
} }
+188
View File
@@ -0,0 +1,188 @@
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,6 +11,9 @@ 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)
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff. Show more