Compare commits

..
Author SHA1 Message Date
Chad Curtis 764319223a Prioritize git.shakespeare.diy by default. 2025-09-30 23:56:59 +00: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
Alex Gleason ca334d7585 Hide model search input unless there are >= 5 models 2025-09-26 17:18:00 -05:00
Alex Gleason 57a80ad33d Fix Gemini model tool_calls 2025-09-26 14:38:38 -05:00
Alex Gleason a05ad13e67 Don't send tool_choice param 2025-09-26 14:14:10 -05:00
Alex Gleason 247919a24b Remove AboutSettings test 2025-09-26 12:36:30 -05:00
Alex Gleason 9b43f07372 Make email configuration more manageable 2025-09-26 12:31:52 -05:00
Alex Gleason af8fb22438 Display license in accordion on About page, use html version of AGPL 2025-09-26 12:12:24 -05:00
Alex Gleason fc4e82c26d Remove legacy migrations from configUtils, parse with zod 2025-09-26 12:01:02 -05:00
Alex Gleason 3b305b5b86 Remove OpenRouter credits parsing (their responses are not accurate anyway) 2025-09-26 11:38:20 -05:00
Alex Gleason 456ea946e7 Refetch credits when AI providers change 2025-09-26 11:37:20 -05:00
Alex Gleason 6c770630d8 Merge branch 'uploadKeyFile' into 'main'
Upload key file

See merge request soapbox-pub/shakespeare!34
2025-09-26 06:23:04 +00:00
Alex Gleason 8f4598b9b8 Merge branch 'iOS-updates' into 'main'
iOS Safe Inset Navigation & Accessibility Zoom

See merge request soapbox-pub/shakespeare!35
2025-09-26 06:21:45 +00:00
lemonknowsall 64c06ec430 upload key file 2025-09-25 22:03:44 -07:00
lemonknowsall 29aae4f55b user scalable no for mobile accessibility 2025-09-25 21:35:09 -07:00
lemonknowsall fb12bda5fa nav safe inset and text highlight 2025-09-25 21:29:26 -07:00
Alex Gleason 7348aaf9ce Don't autofocus project name in ProjectDetailsDialog 2025-09-25 20:22:29 -05:00
Alex Gleason 8948507b6f Fix autostart and model params being removed from URL after project start 2025-09-25 20:00:08 -05:00
Alex Gleason 2dbb9a23e3 Fix CSP for esbuild-wasm 2025-09-25 19:59:49 -05:00
Alex Gleason 11867b3bb2 Add Quilly to the homepage 2025-09-25 19:37:27 -05:00
Alex Gleason 0f82ab15ec Only send X-Title and HTTP-Referer to OpenRouter 2025-09-25 19:13:04 -05:00
Alex Gleason 80ae098323 Re-enable CSP 2025-09-25 18:51:05 -05:00
Alex Gleason fa64a5ce52 Remove Act1Dialog tests 2025-09-25 18:14:51 -05:00
Alex Gleason 870e2f6b9b Mark that the user is a previous Act 1 user 2025-09-25 18:14:31 -05:00
Alex Gleason 26c09733f8 Improve Act1Dialog copy 2025-09-25 18:09:04 -05:00
Alex Gleason 2a80e586ba Add a separate Credits screen to Act1Dialog 2025-09-25 17:53:14 -05:00
Alex Gleason 9f20fd6196 Fix scrolling in Act1Dialog 2025-09-25 17:45:33 -05:00
Alex Gleason 94bcc7eccb Start adding Act 1 dialog 2025-09-25 17:34:38 -05:00
Alex Gleason f62b2f807c .ai -> .git/ai 2025-09-25 15:11:01 -05:00
Alex Gleason 374d2804ad Merge branch 'consoleFramev2' into 'main'
Add tool to read console messages in chat, improve console output presentation, clear console between projects

See merge request soapbox-pub/act2!32
2025-09-25 18:27:08 +00:00
Alex Gleason c0f906ae7e Merge branch 'zipImport' into 'main'
Add zip import option for new projects

See merge request soapbox-pub/act2!20
2025-09-25 17:31:44 +00:00
Chad Curtis 92e2ac1ce5 further reduction and removal. 2025-09-25 16:16:01 +00:00
Chad Curtis e81fb33ffe Add light/dark theme awareness to console output popover. 2025-09-25 05:27:52 +00:00
Chad Curtis 9a65d5d086 clean up remaining id reference + space 2025-09-25 05:25:02 +00:00
Chad Curtis 61d5a5fefc Further simplify console messages 2025-09-25 05:19:06 +00:00
Chad Curtis 75e961d281 Simplify error handling and fix message. 2025-09-25 05:12:18 +00:00
Chad Curtis 93e992f128 Attempt peace with Quilly once more. 2025-09-25 05:06:11 +00:00
Chad Curtis 7ab30af944 Simplify console message handling and reduce code complexity
- Remove unused useErrorDetection.ts hook (154 lines)
- Remove separate console.ts type file, consolidate into ReadConsoleMessagesTool
- Simplify console message state management in PreviewPane
- Remove redundant console clearing logic in ProjectView
- Streamline copy functionality in console UI
- Clean up imports and formatting

Preserves all functionality while reducing code complexity and maintenance burden.
2025-09-25 04:46:47 +00:00
Chad Curtis 6296fc4366 Merge branch 'main' of gitlab.com:soapbox-pub/act2 into consoleFramev2 2025-09-25 04:42:50 +00:00
Chad Curtis 147c7cdf3a Heavily reduce console log detection. v2 2025-09-25 04:41:24 +00:00
Chad Curtis 18a276a44e Heavily reduce console log detection. 2025-09-25 04:32:11 +00:00
Alex Gleason a20bbfdf29 Request persistent storage when creating a project 2025-09-24 23:13:29 -05:00
Alex Gleason 980cb60f1b Add Persist Data toggle to Data Settings 2025-09-24 22:59:37 -05:00
Alex Gleason 2956c86f88 Merge branch 'navigationBar' into 'main'
Add functional navigation to preview pane navbar (url, forward, back, refresh)

Closes #5

See merge request soapbox-pub/act2!21
2025-09-25 03:22:41 +00:00
Chad Curtis c46077af67 Merge in from upstream and resolve conflicts 2025-09-25 03:21:38 +00:00
Chad Curtis e5ca49962e Reset iframe browser history on project change. 2025-09-25 03:15:51 +00:00
Chad Curtis f5c5684ac8 Merge branch 'main' of gitlab.com:soapbox-pub/act2 into navigationBar 2025-09-25 03:13:32 +00:00
Chad Curtis 6a72711aa0 Fix force re-render on url change in preview pane. 2025-09-25 03:13:04 +00:00
Chad Curtis 1ed4a5abd4 Properly block actions based on build status 2025-09-25 02:56:01 +00:00
Alex Gleason db57619bca Allow refilling Shakespeare credits from Quilly 2025-09-24 21:55:28 -05:00
Chad Curtis 0f4075ce38 Merge in from upstream and resolve conflicts 2025-09-25 02:53:08 +00:00
Chad Curtis ad5902cdc6 test fix 2025-09-25 02:48:32 +00:00
Chad Curtis ce4a602270 Add check to verify extracted zip paths are within project directory. 2025-09-25 02:42:46 +00:00
Chad Curtis 5e352e60e9 Merge in from upstream and resolve conflicts 2025-09-25 02:33:26 +00:00
Chad Curtis 37147a69d4 Remove unused file + remove consolemessages from dependency array, store messages in ref. 2025-09-25 02:24:34 +00:00
Alex Gleason ec5d84d3f7 Disconnect Quilly from console errors temporarily 2025-09-24 21:23:31 -05:00
Alex Gleason 0b949d55b9 Remove Quilly tests (for now) 2025-09-24 21:14:41 -05:00
Alex Gleason 25f14ee2b3 Clean up Quilly 2025-09-24 21:06:52 -05:00
Alex Gleason 7057c34f01 Consolidate action logic into Quilly 2025-09-24 20:53:24 -05:00
Alex Gleason d932f05d04 Make Quilly intercept actual Error objects 2025-09-24 20:19:20 -05:00
Alex Gleason e9f8e99ac5 Surface AI Errors to ChatPane 2025-09-24 20:00:02 -05:00
Alex Gleason 0bdc9fa6a3 Don't display an error in the chat when the user cancels their own generation 2025-09-24 15:34:15 -05:00
Alex Gleason 688b35fa41 Start adding special rendering to tool results 2025-09-24 15:24:10 -05:00
Alex Gleason 2e38591943 Prevent duplicate sessions when starting a new project 2025-09-24 15:10:09 -05:00
Alex Gleason 568ea5dc04 Fix missing linebreaks in system prompt 2025-09-24 14:22:55 -05:00
Chad Curtis 4f9d3ae1d1 Remove config object pattern. 2025-09-24 19:09:19 +00:00
Alex Gleason 9bd7e36597 Display loading skeleton when generation is stuck (not streaming tool calls, eg GLM) 2025-09-24 14:04:20 -05:00
Chad Curtis fdfdcb4b16 Tidy 2025-09-24 18:23:59 +00:00
Chad Curtis 50e16e1b57 Merge in from upstream and fix conflicts. 2025-09-24 18:18:39 +00:00
Alex Gleason 77d8cdddad Merge branch 'email-signup' into 'main'
Add email signup page to Settings

See merge request soapbox-pub/act2!33
2025-09-24 16:55:58 +00:00
Chad Curtis 662f95d35d Merge console messaging systems - resolve conflicts between parallel console log implementations
- Unified the global console message system with local state passing
- Maintained backward compatibility for external systems
- Added proper synchronization between global and local console states
- Resolved conflicts in PreviewPane.tsx and ProjectView.tsx
- Both console messaging systems now co-exist peacefully
2025-09-24 16:30:50 +00:00
Alex Gleason ecb74cd31e Allow rollback for current change if there are uncommitted changes
Fixes https://gitlab.com/soapbox-pub/act2/-/issues/42
2025-09-24 11:15:33 -05:00
Mary Kate Fain f40ef03b58 Fix email signup page styling
- Add 'Email Updates' header to thank you page for consistency
- Remove mx-auto centering from forms to make them left-aligned
- Maintain responsive layout for both mobile and desktop
2025-09-24 11:11:28 -05:00
Chad Curtis 458eec0e27 Iniitial console output redesign v2 2025-09-24 16:09:25 +00:00
Mary Kate Fain 3751cb23fc Add localStorage to remember email subscription status
- Check localStorage on component mount to show thank you screen if already subscribed
- Save subscription status after successful signup
- Add 'Subscribe with different email' button to reset localStorage
- Prevents duplicate subscription attempts and improves UX
2025-09-24 11:08:47 -05:00
Mary Kate Fain 399e9a0262 Add email signup page to Settings
- Add new Email Updates page under Settings menu
- Simple form for Shakespeare newsletter subscription
- Uses same Mailchimp setup as soapbox2 with tag ID 8982396
- Automatically includes user's npub if signed in to Nostr
- Added to both mobile and desktop settings layouts
- Includes translations for all supported languages
- Clean success/error handling with opt-out messaging
2025-09-24 11:05:17 -05:00
Alex Gleason d6124119f7 Build project after rollback
Fixes https://gitlab.com/soapbox-pub/act2/-/issues/46
2025-09-24 10:50:27 -05:00
Chad Curtis 74e472338d Iniitial console output redesign 2025-09-24 15:12:57 +00:00
Alex Gleason e93a60be2c Fix tool calls with empty arguments 2025-09-24 00:47:36 -05:00
Alex Gleason 71f4397880 Make clicking "Fix error" send the message automatically 2025-09-24 00:25:47 -05:00
Alex Gleason a1328cb321 Immediately build when a new project is started, too 2025-09-24 00:03:06 -05:00
Alex Gleason f8b8f8e61b Put Quilly action inline 2025-09-23 23:56:22 -05:00
Alex Gleason 6facf72998 Fix type errors 2025-09-23 23:49:57 -05:00
Alex Gleason 77508ea2fc Enlarge Quilly 2025-09-23 23:45:37 -05:00
Alex Gleason 0df1ef1e9d Merge branch 'main' of gitlab.com:soapbox-pub/act2 2025-09-23 23:34:59 -05:00
Alex Gleason 289caff882 Generate system prompt dynamically in SessionManager 2025-09-23 23:29:02 -05:00
Alex Gleason bdb3b58cce Merge branch 'fix/20-invalid-api-key-shows-no-error-to-the-user' into 'main'
fix/20-invalid-api-key-shows-no-error-to-the-user

Closes #20

See merge request soapbox-pub/act2!30
2025-09-24 02:56:59 +00:00
Alex Gleason 0c379c5495 Merge branch 'fix/23-detect-inference-errors-and-show-something-useful-to-the-user' into 'main'
Fix/23 detect inference errors and show something useful to the user

Closes #23

See merge request soapbox-pub/act2!29
2025-09-24 02:54:08 +00:00
Alex Gleason fcf6369356 ProjectDetailsDialog 2025-09-23 21:49:14 -05:00
Alex Gleason fc36073654 Rename project 2025-09-23 21:38:26 -05:00
Alex Gleason 131566750d Add hexdump command 2025-09-23 21:16:58 -05:00
Alex Gleason 540e017074 Fix attaching a file to the initial project message 2025-09-23 21:06:04 -05:00
Alex Gleason 4881480679 Add virtual unzip command to ShellTool 2025-09-23 21:04:27 -05:00
Alex Gleason be13d563c4 Show OnboardingDialog in ProjectView 2025-09-23 20:07:30 -05:00
Alex Gleason a5befda7dc Build automatically after cloning (if applicable) 2025-09-23 19:55:52 -05:00
Alex Gleason fe82f36533 Fix double-clone error 2025-09-23 19:12:48 -05:00
Alex Gleason 22de6889d9 Fix type errors 2025-09-23 18:55:38 -05:00
Alex Gleason d0a520ce17 Get accurate OpenRouter pricing 2025-09-23 18:28:51 -05:00
Alex Gleason aa35b13ad3 Refactor parseProviderModel, prepare to intercept chat completion params 2025-09-23 17:26:43 -05:00
Alex Gleason 738b883f3b Request workflow scope for GitHub (required to push .github directory in mkstack projects) 2025-09-23 17:04:16 -05:00
Alex Gleason 9ea9a4ac4b Fix state issues navigating between projects 2025-09-23 16:14:51 -05:00
Alex Gleason db697d0a85 Add OpenRouter app headers 2025-09-23 15:48:35 -05:00
Alex Gleason 3c75849434 Add badge.svg 2025-09-23 13:42:35 -05:00
Chad Curtis 2b5e3013ff Refactor previewpane to avoid overload of positional parameters. 2025-09-23 14:40:42 +00:00
Chad Curtis 951eefb7b8 Trim down AGENTS.md 2025-09-23 14:30:39 +00:00
Chad Curtis a68d37452b Clean up code duplication and excess changes
- Move ConsoleMessage interface to shared types file to eliminate duplication
- Remove redundant handleSetConsoleMessages variable in PreviewPane
- Update all imports to use shared ConsoleMessage type
- Clean up excess comments and redundant code patterns
2025-09-23 14:29:22 +00:00
Chad Curtis c8653e67dc lint fix + reset console output on project change. 2025-09-23 14:24:22 +00:00
Chad Curtis 660f25656c Replace X with Trash icon for clearing console output 2025-09-23 14:21:09 +00:00
Chad Curtis 804efb4d23 Expose console messages via tool call. 2025-09-23 14:19:49 +00:00
sam 8932413c2d lint fix 2025-09-23 21:08:54 +07:00
Chad Curtis 8108407478 Improve visual presentation of console output. 2025-09-23 13:59:21 +00:00
sam 9de4b167e7 catch the error bubbled up exactly 2025-09-23 15:07:02 +07:00
sam c9073bb4bd wip: when creating a project fails, check for auth errors with the api call to feed back to the user what/why we had an issue 2025-09-23 14:34:50 +07:00
Alex Gleason f9f72e6a50 Don't show preview tab for projects that are not buildable 2025-09-22 21:46:26 -05:00
Alex Gleason feb0bd7d3c Fix CORS proxy 2025-09-22 16:18:55 -05:00
Alex Gleason 0eac4c66ee Make code a dedicated button in the browser bar again 2025-09-22 15:33:55 -05:00
Alex Gleason aea8c1390b Add max width to preview address bar 2025-09-22 15:23:14 -05:00
Alex Gleason 893d2e66ab Fix handling of empty assistant messages 2025-09-22 11:26:13 -05:00
sam e88a11ce21 most recent error only 2025-09-22 22:55:46 +07:00
sam 3a8e040212 lint 2025-09-22 22:48:26 +07:00
sam 37e15ac786 lint / text fixes 2025-09-22 22:28:01 +07:00
sam c3fc719e82 Merge branch 'main' into fix/23-detect-inference-errors-and-show-something-useful-to-the-user 2025-09-22 20:57:11 +07:00
Alex Gleason 02750c9b5c Always show address bar in preview pane 2025-09-22 08:55:30 -05:00
sam 0e80915d58 define actions in errorPatterns 2025-09-22 20:54:43 +07:00
Alex Gleason 89f8701855 OnboardingDialog: use model description as title 2025-09-22 08:42:05 -05:00
sam ff95c13f84 fix scroll to bottom on alert 2025-09-22 20:33:39 +07:00
sam c38113c9b8 wip catch errors from the app and offer to help fix 2025-09-22 20:19:08 +07:00
sam c97117db5d quilly beautification 2025-09-22 19:34:49 +07:00
sam 999c250216 #keepnostrweird quilly to thee rescue 2025-09-22 19:29:00 +07:00
Alex Gleason 6d6f18a877 Swap out corsproxy.io for our custom proxy 2025-09-22 06:32:49 -05:00
sam 8e8976b9bc chat intervention actions 2025-09-22 18:30:02 +07:00
sam f4190d22fb expose a ref to the model selector 2025-09-22 18:15:31 +07:00
Alex Gleason 92376d58b8 Use new corsProxy format 2025-09-22 06:04:29 -05:00
sam fb192b8657 make model selector controlled 2025-09-22 18:00:04 +07:00
sam 3e9b15eed3 alert spacing 2025-09-22 17:23:46 +07:00
sam 561e5614c5 chat intervention component and flow 2025-09-22 17:21:59 +07:00
Alex Gleason 04d812382b Support ollama "reasoning" field 2025-09-22 04:16:05 -05:00
Alex Gleason 49d4c5120e Add translations for 3 Nigerian languages 2025-09-22 03:25:39 -05:00
Alex Gleason 8aaaea0b8f Simplify code tabs on desktop 2025-09-22 03:09:57 -05:00
Alex Gleason 3c46c72bba Improve Preview and Code buttons visually 2025-09-22 02:50:34 -05:00
Alex Gleason d52d7b57a6 Add DeployDialog 2025-09-22 02:46:12 -05:00
Alex Gleason cadebaaa0e Move Delete Project into ProjectInfoDialog 2025-09-22 02:31:59 -05:00
Alex Gleason 79be6c8252 Use PasswordInput on GitSettings page 2025-09-22 02:22:37 -05:00
Alex Gleason 35ac22c74f Add loading indicator to preview when building 2025-09-22 02:02:06 -05:00
Alex Gleason 3ec89713bc Fix tests 2025-09-22 02:01:59 -05:00
Alex Gleason 7cbaaec734 Move build button into PreviewPane 2025-09-22 01:55:34 -05:00
Alex Gleason 46a5ca2a1e Add useBuildProject, useDeployProject hooks 2025-09-22 01:33:01 -05:00
Alex Gleason 668a6c79d9 Greatly simplify ProjectInfoDialog, move Export Project into there 2025-09-22 01:08:05 -05:00
Alex Gleason 3692863830 GitDialog tweaks 2025-09-22 00:23:44 -05:00
Alex Gleason 6478ed21bb Remove pointless "File Explorer" header 2025-09-22 00:10:08 -05:00
Alex Gleason 25f11dbe1d Start simplifying 3-dots menu 2025-09-22 00:02:52 -05:00
Alex Gleason 16ee1235d3 Fix Git History overflow 2025-09-21 23:49:21 -05:00
Alex Gleason fed44cef5e GitDialog improvements 2025-09-21 23:40:08 -05:00
Alex Gleason 4ce35b8ff0 Merge branch 'main' of gitlab.com:soapbox-pub/act2 2025-09-21 23:25:09 -05:00
Alex Gleason f6dc218ae7 Remove "Repository Information" from GitDialog 2025-09-21 21:59:38 -05:00
Alex Gleason da37ddfdfb Merge branch 'signup-flow' into 'main'
Simplify Nostr signup and login form

See merge request soapbox-pub/act2!24
2025-09-22 01:27:49 +00:00
Alex Gleason 230d4bc443 Push to Nostr works! 2025-09-21 20:07:55 -05:00
Mary Kate Fain 61254d2ee3 Increase circle size to w-40 h-40 for better emoji proportion
- Change both container and circle from w-32 h-32 to w-40 h-40 (10rem / 160px)
- Provides more generous spacing around the text-8xl emoji key
- Creates better visual balance and prevents the emoji from appearing cramped
- Applied consistently across all instances in both login and signup dialogs
- All tests passing
2025-09-21 19:15:28 -05:00
Mary Kate Fain b28f700600 Increase circle size to match larger emoji key
- Change circle from w-20 h-20 to w-32 h-32 to better accommodate text-8xl emoji
- Now the circle fills the entire container space for better visual balance
- Applied consistently across all instances in both login and signup dialogs
- Creates better proportional relationship between emoji and background circle
- All tests passing
2025-09-21 19:14:16 -05:00
Mary Kate Fain 691077d754 Increase emoji key size from text-4xl to text-8xl
- Make the 🔑 emoji 2x bigger as requested
- Applied to all instances in both SimpleLoginDialog and SimpleSignupDialog
- Creates more prominent visual focal point in the authentication flows
- All tests passing
2025-09-21 19:13:09 -05:00
Mary Kate Fain 7d0c0b6ba2 Replace key icons with emoji key in circular background
- Replace Lucide Key icons with 🔑 emoji in both login and signup dialogs
- Add circular background with primary color tint (bg-primary/10)
- Maintain consistent sizing (w-20 h-20 circle, text-4xl emoji)
- Remove unused Key import from both components
- Creates friendlier, more approachable visual design
- All tests passing
2025-09-21 19:11:22 -05:00
Mary Kate Fain 3d42d93ef1 Fix 'I already have an account' button to properly open login dialog
- Add onLogin prop to SimpleSignupDialog interface
- Connect handleLoginClick to onLogin callback
- Update LoginArea and NostrSettings to handle signup->login transition
- Now clicking 'I already have an account' properly closes signup and opens login
- All tests passing
2025-09-21 19:05:40 -05:00
Mary Kate Fain d5c5132662 Prioritize account creation and key generation as default user experience
- Make signup the primary action in dropdown menu (moved above login)
- Start with key generation as default signup flow instead of extension
- Only show extension options when browser extension is detected
- Remove complex step navigation - direct to key creation for new users
- Update copy to be more welcoming for new users vs returning users
- Clean up unused imports and simplify component structure
- All tests passing
2025-09-21 19:00:39 -05:00
Mary Kate Fain ce29d036ad Replace complex Nostr login/signup modals with simpler Soapbox/Ditto-inspired design
- Created SimpleLoginDialog and SimpleSignupDialog with clean, minimal design
- Simplified step-based flow similar to Soapbox/Ditto implementation
- Reduced visual complexity while maintaining all functionality
- Updated LoginArea and NostrSettings to use new simple modals
- Updated tests to reference new components
- All tests passing
2025-09-21 18:54:53 -05:00
Alex Gleason c0e00d40f7 Add getNostrRemoteInfo 2025-09-21 18:03:27 -05:00
Alex Gleason 9678041502 git push over Nostr 2025-09-21 17:55:14 -05:00
Alex Gleason 154b9330d4 Simplify git onAuth calls 2025-09-21 17:42:16 -05:00
Alex Gleason bc907fdd63 Implement nostr fetch, pull 2025-09-21 17:27:12 -05:00
Alex Gleason 93983f88af Clone with the state commit from Nostr 2025-09-21 17:15:28 -05:00
Alex Gleason 72a537ce2e Refactor nostr git clone, add "nostr.repo" git config 2025-09-21 16:50:22 -05:00
Alex Gleason f06c7dbe70 Remove Moonshot AI due to no CORS support 2025-09-21 15:41:40 -05:00
Alex Gleason 3e502fa3a9 When cloning by Nostr URI, set the URI in the remote 2025-09-21 15:38:03 -05:00
Alex Gleason d3e257f759 Transfer Nostr clone logic into Git class 2025-09-21 14:45:27 -05:00
Alex Gleason 69c1000063 Refactor Git to accept a nostr object 2025-09-21 14:31:13 -05:00
Alex Gleason f797ec55c5 Break out npm tasks so the robot is faster 2025-09-21 13:28:20 -05:00
Alex Gleason 7b5c9a5581 Convert AI providers into array instead of object, allow dragging to change their order 2025-09-21 13:11:04 -05:00
Chad Curtis 41d7d7834d a bit more janitorial work 2025-09-21 06:52:56 +00:00
Chad Curtis 785f75a39a remove cruft path 2025-09-21 06:48:03 +00:00
Chad Curtis 8e3cc67ce2 cleanup current logic 2025-09-21 06:47:23 +00:00
Chad Curtis fae90cc85e refresh functionality fix 2025-09-21 06:08:18 +00:00
Chad Curtis 2ed44e43f7 v3 2025-09-21 06:08:18 +00:00
Chad Curtis 53cf844fd6 v2 navigation 2025-09-21 06:08:18 +00:00
Chad Curtis 6aa36b6738 v1 navigation 2025-09-21 06:08:18 +00:00
Alex Gleason 5cf19c61cc DotAI: always write 2025-09-20 22:26:06 -05:00
Alex Gleason 5a9fccf631 Merge branch 'drag-and-drop' into 'main'
Add drag-and-drop

See merge request soapbox-pub/act2!11
2025-09-21 00:41:47 +00:00
Alex Gleason adf9113ab3 Remove faulty Index test 2025-09-20 19:08:23 -05:00
Alex Gleason a3c204f44f Replace spaces with underscores in uploaded files 2025-09-20 19:05:53 -05:00
Alex Gleason 75d4d13737 Fix attachment button on dark mode and position 2025-09-20 18:42:07 -05:00
Alex Gleason 549385077f Merge remote-tracking branch 'origin/main' into drag-and-drop 2025-09-20 18:32:23 -05:00
Alex Gleason f3b33c9b48 Merge branch 'main' of gitlab.com:soapbox-pub/act2 2025-09-20 14:26:34 -05:00
Alex Gleason be0b432a00 Move model selector actions to the bottom 2025-09-20 14:26:17 -05:00
Chad Curtis 1a60ee6bbe Merge branch 'consoleFrame' into 'main'
Add console log/error tracking to preview pane

See merge request soapbox-pub/act2!8
2025-09-20 19:19:26 +00:00
Chad Curtis c6617beb6d Gracefully handle total response failure from site - no response at all. 2025-09-20 18:36:52 +00:00
Chad Curtis 718b2f369b Remove code example from a file path already linked. 2025-09-20 18:24:18 +00:00
Chad Curtis a823f81b50 Function definition consistency + slight deduplication 2025-09-20 18:21:55 +00:00
Chad Curtis 4cd8683e73 Re-add purged, but informative documentation/comment items. 2025-09-20 18:09:03 +00:00
Alex Gleason 27fb8103a3 Remove pointless separators from settings pages 2025-09-20 12:59:17 -05:00
Chad Curtis 53ac813eb5 Further simplify main.js, update documentation. 2025-09-20 17:59:04 +00:00
Alex Gleason 60f70db7b4 Hide "Recently Used" section of model selector if there are less than 5 models 2025-09-20 12:56:29 -05:00
Alex Gleason 050d24fcb7 Improve display of model picker in OnboardingDialog 2025-09-20 12:45:56 -05:00
Alex Gleason 04b9ead22e Add OnboardingDialog 2025-09-20 12:29:16 -05:00
Chad Curtis f4f455606f Simplify console overrides list within iframe client as well. 2025-09-20 17:15:17 +00:00
Alex Gleason 62f5a4fe87 Expose model description 2025-09-20 12:12:26 -05:00
Chad Curtis 1a424c0762 Refactor and simplify console methods. 2025-09-20 17:10:47 +00:00
Alex Gleason c5f74ceafc Replace @std/path with path-browserify 2025-09-20 11:24:33 -05:00
Alex Gleason ace3e0b3ac Fix cd command 2025-09-20 10:53:56 -05:00
Alex Gleason ba24edc7fe Merge branch 'main' of gitlab.com:soapbox-pub/act2 2025-09-20 10:46:02 -05:00
Alex Gleason 8c1927fdf7 Fix git diff subcommand 2025-09-20 10:45:52 -05:00
Alex Gleason 3c3ac25101 Merge branch 'fix-settings-pane-on-midsize-screens' into 'main'
adjust pixel breakpoint for responsive design

Closes #2

See merge request soapbox-pub/act2!14
2025-09-20 14:53:40 +00:00
Chad Curtis adeb3bf53f Revert "remove custom id logic"
This reverts commit 588e32a43d.
2025-09-20 06:57:24 +00:00
Chad Curtis 588e32a43d remove custom id logic 2025-09-20 06:52:47 +00:00
Chad Curtis 57e12261af clean up index spaces 2025-09-20 06:39:11 +00:00
Chad Curtis 797984c5d3 Revert "Restore mobile back buttons and clean up branch"
This reverts commit 4d6bc91650.
2025-09-20 06:38:53 +00:00
Chad Curtis 6d49648580 simplify agents.md entry 2025-09-20 06:34:45 +00:00
Chad Curtis 4d6bc91650 Restore mobile back buttons and clean up branch
- Restore mobile back buttons in AboutSettings and DataSettings pages
- Remove extra empty lines in Index.tsx
- Ensure compatibility with origin/main changes
- All tests pass and build succeeds

This resolves conflicts where the zipImport branch had incorrectly
removed mobile navigation features that were added in origin/main.
2025-09-20 06:14:16 +00:00
Chad Curtis 2fdf8a3740 refactors v2 2025-09-20 06:00:20 +00:00
Chad Curtis f4ccc2d924 refactors 2025-09-20 05:47:17 +00:00
shakespeare.diy bda9501e63 Add mobile back button to Data and About settings pages
- Added mobile navigation with back button to DataSettings.tsx
- Added mobile navigation with back button to AboutSettings.tsx
- Import ArrowLeft icon and useIsMobile hook in both pages
- Maintain consistency with other settings pages (AISettings, NostrSettings)
- Show mobile back button only on mobile devices
- Preserve existing desktop header layout
2025-09-19 23:32:57 -05:00
Alex Gleason d4ea9bf1bd Remove log in condition in CreditsDialog 2025-09-19 23:23:02 -05:00
Chad Curtis 6f4aa264eb merge in from upstream and resolve conflict 2025-09-20 03:55:34 +00:00
Chad Curtis f299c73c4d final consolidation 2025-09-20 03:53:46 +00:00
Chad Curtis 1d05aa10eb further cleanup 2025-09-20 03:38:19 +00:00
Chad Curtis ca2426a800 Further cleanup + make errors copiable 2025-09-20 03:37:20 +00:00
Chad Curtis fbea142bbb Address review items 2025-09-20 02:16:40 +00:00
Chad Curtis 0027752654 consolidation and visual cleanup 2025-09-20 02:16:40 +00:00
Chad Curtis d64fa0e0ec Deduplicate console interception code
- Extract shared console utilities to console-utils.js
- Remove duplicated console methods array
- Consolidate original console storage logic
- Extract console override and error handler patterns
- Reduced code duplication by ~90 lines
2025-09-20 02:16:40 +00:00
Chad Curtis 696cbca55a remove debug file 2025-09-20 02:16:40 +00:00
Chad Curtis 92f3c06f51 cleanup 2025-09-20 02:16:40 +00:00
Chad Curtis 3898681d97 CF worker setup + iframe domain to env 2025-09-20 02:16:40 +00:00
Chad Curtis ba251d57eb baseline 2025-09-20 02:16:40 +00:00
Alex Gleason efd7c3901b Display loading state for reasoning 2025-09-19 20:36:40 -05:00
Alex Gleason e6c9c213b5 Support reasoning_content 2025-09-19 20:23:55 -05:00
Alex Gleason bd5373f57b Simplify Preferences page 2025-09-19 19:54:23 -05:00
Alex Gleason f67d6dbfc5 Add About Shakespeare page 2025-09-19 19:49:29 -05:00
Alex Gleason efbec14d24 Add AGPL license 2025-09-19 19:31:17 -05:00
Alex Gleason 1c8095d40e Enforce max height on transactions list 2025-09-19 19:26:46 -05:00
Alex Gleason 7807f875f2 Add Back button to Lightning view 2025-09-19 19:10:26 -05:00
Alex Gleason fdd3fd2b52 Add refresh button to transactions 2025-09-19 18:47:32 -05:00
Alex Gleason 77863f97be Copy tooltip 2025-09-19 18:32:38 -05:00
Alex Gleason 1d88ca84f2 Improve Lightning payment UX 2025-09-19 18:26:24 -05:00
Alex Gleason 62cd515a9e Improve credits dialog 2025-09-19 18:09:22 -05:00
Alex Gleason a1e18ec335 Render dialog outside of accordion 2025-09-19 17:59:34 -05:00
Alex Gleason dca1573293 Add initial AI credits dialog 2025-09-19 17:49:15 -05:00
Alex Gleason 04d28cbe01 Delete CreditsBadge test 2025-09-19 17:19:12 -05:00
Alex Gleason 234418babd Display provider credits in the UI 2025-09-19 17:12:57 -05:00
Alex Gleason e570ee0236 Add special treatment for Nostr providers in the UI 2025-09-19 16:31:59 -05:00
Alex Gleason 45745dc368 Add Shakespeare AI provider 2025-09-19 16:22:28 -05:00
Alex Gleason 15ec573ed1 Merge branch 'fix-spacing-ui' into 'main'
Fix spacing ui

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

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

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

See merge request soapbox-pub/act2!15
2025-09-18 20:46:38 +00:00
Alex Gleason 61fcbc7003 Downgrade streamdown again 2025-09-18 15:44:13 -05:00
Alex Gleason 562d2c3085 Upgrade streamdown 2025-09-18 15:39:22 -05:00
Alex Gleason 7b4a5ee22e Remove unused streamdown dep 2025-09-18 15:35:01 -05:00
Alex Gleason 9ac157e802 Remove unused dep, fix esbuild plugins 2025-09-18 15:31:36 -05:00
P. Reis aac0d5d320 fix test CI 2025-09-18 17:28:51 -03:00
Alex Gleason 4b42f4cedb Improve resolution of imports in esmPlugin in some cases 2025-09-18 15:20:56 -05:00
filemon 758ed90bb7 Merge branch 'main' into drag-and-drop 2025-09-18 17:20:06 -03:00
filemon 6378e49a96 remove file validation 2025-09-18 17:19:39 -03:00
P. Reis ceb716d2ab Merge branch 'main' into add-eye-password 2025-09-18 17:09:03 -03:00
Alex Gleason f43e582a78 Make react-hooks/exhaustive-deps required 2025-09-18 15:08:24 -05:00
P. Reis 1aafb67cbd fix CI eslint complain 2025-09-18 17:06:40 -03:00
P. Reis 81af9852a8 feat: add eye to toggle visibility of passwords 2025-09-18 17:02:32 -03:00
Siddharth Singh 993b5ece9c switch back to width breakpoint for useMobileView
@alexgleason pointed out aspect ratio would break screens that were
physically wide but not quite the shape 11/9 expects
2025-09-19 00:37:11 +05:30
Siddharth Singh cd60ab8cbe use aspect ratio query instead of hard pixel breakpoint for mobile 2025-09-19 00:08:01 +05:30
Alex Gleason c278618afd Always show sidebar in Settings on desktop 2025-09-18 13:30:52 -05:00
Alex Gleason 94a14c5f7e Fix sidebar menu button on ProjectView 2025-09-18 13:27:12 -05:00
Alex Gleason 47b2f2bb12 Merge branch 'menu-update' into 'main'
Menu update

Closes #25

See merge request soapbox-pub/act2!12
2025-09-18 18:06:25 +00:00
Alex Gleason 8d00ac57c7 Merge branch 'main' of gitlab.com:soapbox-pub/act2 2025-09-18 12:35:48 -05:00
Mary Kate Fain 85f1f4597e fix sidebar collapse button location when settings is open 2025-09-18 12:21:36 -05:00
Alex Gleason 3989a8a217 Implement GitHub PKCE 2025-09-18 12:15:04 -05:00
Alex Gleason 72f8a9def9 Fix Connect to GitHub styling 2025-09-18 12:02:06 -05:00
Alex Gleason 945bc002f2 Fix OAuth useEffect getting called twice 2025-09-18 11:54:58 -05:00
Mary Kate Fain 80e9a8decb add help center link to user menu 2025-09-18 11:48:02 -05:00
Alex Gleason 9ee120f765 Switch GitHub auth page to /oauth/github 2025-09-18 11:44:08 -05:00
Mary Kate Fain b73bb3971e move sidebar collapse button into the sidebar 2025-09-18 11:41:58 -05:00
Alex Gleason 87c533666d Merge branch 'feature-search' into 'main'
feat: add 'search' funcionalities, both for file names and file contents

See merge request soapbox-pub/act2!7
2025-09-18 16:37:49 +00:00
Mary Kate Fain 69c38b489a Change logged out view to still have bottom user menu, and move settings into it 2025-09-18 11:35:50 -05:00
P. Reis f7ef7a2080 Remove search in content functionality from File Explorer
- Removed the 'Search in content' button and its toggle functionality
- Simplified search logic to only search file names by exact string match
- Removed FileText import and Button import as they're no longer needed
- Fixed ESLint warning by removing unnecessary dependencies from useCallback
- All tests pass and build is successful

The File Explorer now only searches file names as requested by the boss.
2025-09-18 13:31:35 -03:00
filemon 846a3fd685 fix test error 2025-09-18 12:13:57 -03:00
filemon 5bcede498d Merge branch 'main' into drag-and-drop 2025-09-18 11:51:11 -03:00
filemon bd34c38701 feat: add drag-and-drop file support to description textarea 2025-09-18 11:48:47 -03:00
Alex Gleason 60fa8d2239 Merge branch 'fix/18-auto-scroll-to-the-bottom-when-opening-or-reloading' into 'main'
fix/18-auto-scroll-to-the-bottom-when-opening-or-reloading

Closes #18

See merge request soapbox-pub/act2!10
2025-09-18 13:38:56 +00:00
Alex Gleason c7527b24df Merge branch 'fix/14-large-prompts-underlap-the-model-submit-button' into 'main'
fix/14-large-prompts-underlap-the-model-submit-button

Closes #14

See merge request soapbox-pub/act2!9
2025-09-18 13:38:11 +00:00
sam 7755277877 also fix inconcistent appearing of scroll to bottom button when changing project versus a fresh load 2025-09-18 19:07:25 +07:00
sam 72db1b21f4 scroll to bottom when first navigating to a project/page 2025-09-18 18:41:36 +07:00
sam fec198e7b3 css fix: use flex so that cells can't overlap 2025-09-18 17:13:20 +07:00
Alex Gleason 2d0e7ae281 Fix deps lint warning in Clone.tsx 2025-09-17 20:13:16 -05:00
Alex Gleason e8a889c247 Merge branch 'github' 2025-09-17 20:09:50 -05:00
Alex Gleason 68edc0b6dc Fix trash icon 2025-09-17 20:04:18 -05:00
Alex Gleason a8a7e3ace9 Add one-click GitHub connect 2025-09-17 19:47:06 -05:00
P. Reis 8ea62f4b23 feat: add 'search' funcionalities, both for file names and file contents 2025-09-17 19:38:22 -03:00
Alex Gleason d7950924a8 Merge branch 'edit-with-shakespeare' into 'main'
Allow Direct Clone from URL

See merge request soapbox-pub/act2!6
2025-09-17 08:53:40 +00:00
lemonknowsall dd5c7b22be address pipline onClick handler error 2025-09-16 23:09:28 -07:00
Alex Gleason 5f1eaed12b Add Routstr preset 2025-09-16 15:14:29 -05:00
Alex Gleason b289983071 Fix indentation in App.tsx 2025-09-16 14:58:47 -05:00
Alex Gleason 1f23fa6359 Clean up tmp files on start 2025-09-16 14:23:53 -05:00
Alex Gleason 94d14a87aa Try a different code-splitting tactic 2025-09-16 00:07:30 -05:00
lemonknowsall 4b1c3ee381 allow direct clone from url 2025-09-15 21:54:14 -07:00
Alex Gleason 753c12bcac Remove misbehaving test 2025-09-15 23:46:22 -05:00
Alex Gleason 9d53f74782 Remove low quality test 2025-09-15 23:19:00 -05:00
Alex Gleason d16515a5c4 Fix setting recently used model in model selector 2025-09-15 23:18:03 -05:00
Alex Gleason 015a6c8536 Fix git push through terminal
Fixes https://gitlab.com/soapbox-pub/act2/-/issues/10
2025-09-15 23:14:51 -05:00
Alex Gleason 373f25db76 Migrate AI settings and git settings to the VFS 2025-09-15 20:57:45 -05:00
Alex Gleason a09916fcb8 Pass include_usage to text generation endpoint 2025-09-15 17:37:18 -05:00
Alex Gleason 11522c8426 Use NIP98Client from Nostrify 2025-09-15 16:09:45 -05:00
Alex Gleason dedb9c7f55 Refresh models when providers are changed 2025-09-15 12:33:24 -05:00
Alex Gleason ab9c269240 Remove wrong test 2025-09-14 22:50:50 -05:00
Alex Gleason a22cc50990 Allow pasting an attachment directly into the message box 2025-09-14 21:19:52 -05:00
Alex Gleason b2eb443b43 Remove intermittently failing test 2025-09-14 18:01:31 -05:00
Alex Gleason 94e1a6543c Make corsProxy configurable 2025-09-14 17:58:41 -05:00
Alex Gleason bc009d444e make GitCommitTool accept git instance 2025-09-14 17:27:12 -05:00
Alex Gleason 1ab895bd59 Refactor git subcommands to accept a git instance 2025-09-14 17:15:07 -05:00
Alex Gleason 772a2f424b Refactor code to use our custom Git class 2025-09-14 16:26:37 -05:00
Alex Gleason 55120452c7 Add git wrapper class 2025-09-14 16:10:36 -05:00
Alex Gleason 0dd5ae13a9 Fix git hard reset 2025-09-14 16:04:58 -05:00
Alex Gleason f56f88b1cb Remove path from added file render 2025-09-14 15:17:33 -05:00
Alex Gleason c225821a44 Allow commands to write to cwd with public paths 2025-09-14 15:11:01 -05:00
Alex Gleason e8203dd69f Fix the text_editor_view tool when used on binary data 2025-09-14 14:48:09 -05:00
Alex Gleason ffb9c3d95e Let ls work on absolute paths 2025-09-14 14:41:38 -05:00
Alex Gleason feaa767632 Change File Added format 2025-09-14 14:29:14 -05:00
Alex Gleason 425976bb82 Break user texts up into separate messages 2025-09-14 14:25:02 -05:00
Alex Gleason 76fa9940db Parse user messages 2025-09-14 14:13:18 -05:00
Alex Gleason 80ed3d606d AGENTS: describe user messages 2025-09-14 14:08:50 -05:00
Alex Gleason a106a6e10b Support adding files through the VFS 2025-09-14 12:50:28 -05:00
Alex Gleason be8309b503 Update tools to allow reading any VFS path, writing to /tmp 2025-09-14 12:31:23 -05:00
Alex Gleason f23b92c79f AGENTS.md: shell commands 2025-09-14 12:15:06 -05:00
Alex Gleason 21f9511a1e AGENTS.md: update project structure 2025-09-14 12:09:59 -05:00
Alex Gleason 82d2aed921 Clarify VFS and path security in AGENTS.md 2025-09-14 12:03:29 -05:00
Alex Gleason 7c7275cfdb Allow reading files from any directory on the VFS 2025-09-14 11:40:43 -05:00
Alex Gleason 7c500d1047 Scroll settings views independently from settings launchpad 2025-09-13 23:00:48 -05:00
Alex Gleason 7ad72f6ff8 Fix encoding of index.html 2025-09-13 22:27:25 -05:00
Alex Gleason 1938c145db TextEditorViewTool: don't use default gitignore list 2025-09-13 22:13:36 -05:00
Alex Gleason 04f81a3375 iframe-fetch-client: encode body as base64 text (to make binary files work) 2025-09-13 22:01:19 -05:00
Alex Gleason fa34cade7a Fix DataSettings test 2025-09-13 20:58:46 -05:00
Alex Gleason cab91f692e Simplify Project preview placeholder 2025-09-13 20:52:59 -05:00
Alex Gleason 731e74ad06 Hide "Add Custom Provider" behind accordion click 2025-09-13 20:46:23 -05:00
Alex Gleason 5331a56d36 Simplify DataSettings storage display 2025-09-13 20:43:54 -05:00
Alex Gleason 9b85c11803 Make curl go through corsproxy 2025-09-13 20:32:40 -05:00
Alex Gleason c9069cfebd Implement curl command 2025-09-13 20:28:21 -05:00
Alex Gleason 492542df91 Add Storage Usage section to Data Settings page 2025-09-13 20:24:56 -05:00
Alex Gleason 6935b343ae Improve textarea styles 2025-09-13 19:17:36 -05:00
Alex Gleason ef6642181e Use a browser-like UI in the project preview 2025-09-13 19:01:21 -05:00
Alex Gleason ebc4c2d997 Fix position of star icon in ProjectSidebar 2025-09-13 18:59:13 -05:00
Alex Gleason 383fa9b0ae Improve truncation of long chat titles 2025-09-13 18:49:55 -05:00
Alex Gleason 787b0bb777 Give useIsMobile an initial state 2025-09-13 18:34:30 -05:00
Alex Gleason 0edef42bf2 Start fixing loading state of ProjectView 2025-09-13 18:30:19 -05:00
Alex Gleason 022efa74c3 AccountSwitcher: don't shrink for no reason on mobile 2025-09-13 17:58:00 -05:00
Alex Gleason ba62a139e2 Rework useLocalStorage to use React Query, fix starring projects updates sidebar immediately 2025-09-13 17:55:56 -05:00
Alex Gleason b72baaeb48 Only display star button if project is favorited, refactor into useProjects hook 2025-09-13 17:26:04 -05:00
Alex Gleason bdcc030de6 Add empty messages screen to ChatPane 2025-09-13 16:21:15 -05:00
Alex Gleason b9568896d6 Various UI polishing 2025-09-13 16:17:25 -05:00
Alex Gleason dc55626832 Move Import Repository into New Project button 2025-09-13 16:04:43 -05:00
Alex Gleason 2c7fd7d79b Add Data page to settings 2025-09-13 15:59:29 -05:00
Alex Gleason bb47f36a35 Add SettingsLayout 2025-09-13 15:22:08 -05:00
Alex Gleason a87df5d0aa Add dedicated settings pages 2025-09-13 14:47:53 -05:00
Alex Gleason e6864cf8f3 Clone full repo history, except when cloning a stack (for a new project) 2025-09-13 14:18:28 -05:00
Alex Gleason 0119972cc9 Reimplement the entire git command in the virtual shell, lmao 2025-09-13 13:51:37 -05:00
Alex Gleason 874bca5d61 Simplify credentials in GitDialog, use configured credentials 2025-09-13 12:11:30 -05:00
Alex Gleason 81b0571b3e Add GitSettingsDialog 2025-09-13 12:01:46 -05:00
Alex Gleason ddf09c6684 Add git password input (for now) 2025-09-12 18:03:48 -05:00
Alex Gleason 227b0fab76 Add GitDialog 2025-09-12 17:51:57 -05:00
Alex Gleason a84ebb16e0 Add git info to top of AGENTS.md 2025-09-12 16:33:18 -05:00
Alex Gleason 9538c72c99 Allow horizontal scrolling in File Explorer 2025-09-12 13:47:48 -05:00
Alex Gleason 8e727b0b63 copyFiles in parallel 2025-09-12 13:41:28 -05:00
Alex Gleason d33fa36591 Refactor buildProject, copy public files 2025-09-12 13:35:52 -05:00
Alex Gleason e8e2b28504 Stylize typecheck tool 2025-09-12 10:53:30 -05:00
Alex Gleason 3f52efe4b8 Add custom icon and text for deploy_project 2025-09-12 10:48:37 -05:00
Alex Gleason 266774fc61 Treat AI empty tool call as empty object 2025-09-12 10:34:38 -05:00
Alex Gleason e92b3b9cd4 Refresh preview automatically after project is built 2025-09-12 10:31:59 -05:00
Alex Gleason 5b828f0c83 Add information about the user to the system prompt 2025-09-12 09:41:05 -05:00
Alex Gleason 5debca98d6 Fix tests 2025-09-11 22:28:18 -05:00
Alex Gleason 069cda512e Add VFS layout to AGENTS.md 2025-09-11 22:18:36 -05:00
Alex Gleason ff37b3d758 Improve performance of useProviderModels hook 2025-09-11 21:03:13 -05:00
Alex Gleason 4039e1e355 Enhance ShellTool with &&, ||, |, etc 2025-09-11 20:54:11 -05:00
Alex Gleason 943a4e592b Gray gitignored files in FileTree 2025-09-11 20:39:26 -05:00
Alex Gleason 24b8b5bd05 Retry generating projectId if the generated name is already taken 2025-09-11 19:36:40 -05:00
Alex Gleason 8db727ed14 Remove whitespace-pre-wrap on assistant messages 2025-09-11 18:58:04 -05:00
Alex Gleason 6085713885 Add cwd to system prompt 2025-09-11 18:45:17 -05:00
Alex Gleason 60eca98d86 Fix useProjectId tests 2025-09-11 18:42:26 -05:00
Alex Gleason 0b02edfe32 Simplify title generation error handling 2025-09-11 18:37:41 -05:00
Alex Gleason 79605c7ed1 Improve title generation 2025-09-11 18:28:51 -05:00
Alex Gleason 8383384af7 Add Lemon's AI 2025-09-11 18:06:11 -05:00
Alex Gleason bd0ed0a10f Make Nostr Auth work 2025-09-11 17:53:36 -05:00
Alex Gleason d7807f3911 Fix favorite star alignment 2025-09-11 16:51:51 -05:00
Alex Gleason 5f619c769a Fix esbuild target 2025-09-11 16:49:18 -05:00
Alex Gleason 154adfd83f Make loading skeleton only 1 line tall 2025-09-11 16:26:04 -05:00
Alex Gleason 9cba46d33f npm_add_package tool also updates package-json.lock 2025-09-11 16:21:45 -05:00
Alex Gleason 0f67f64936 Make Tool inputSchema optional 2025-09-11 16:03:06 -05:00
Alex Gleason ba2cfe7b68 Fix loading project 2025-09-11 15:44:42 -05:00
Alex Gleason 251959c18e Fix autostart 2025-09-11 15:33:24 -05:00
Alex Gleason d7fc8f62e8 Improve SessionManager logic 2025-09-11 14:05:01 -05:00
Alex Gleason 11b9aa9e20 DotAI: validate messages before saving to history 2025-09-11 13:04:24 -05:00
Alex Gleason 6f923251d4 Remove redundant methods 2025-09-11 12:49:49 -05:00
Alex Gleason 9b7b79dacc Remove SessionConfig 2025-09-11 12:47:20 -05:00
Alex Gleason af6942c04f Sessions should be keyed by projectId, not a generated ID 2025-09-11 12:42:34 -05:00
Alex Gleason d3550b0fca Remove projectName variable, memoize onUpdateMetadata 2025-09-11 12:31:17 -05:00
Alex Gleason 795639a8f4 Start refactoring SessionManager 2025-09-11 12:21:45 -05:00
Alex Gleason 0f1126174a Add TypecheckTool stub 2025-09-10 20:24:44 -05:00
Alex Gleason 2433a7daff Autosave AI Settings 2025-09-10 13:09:40 -05:00
Alex Gleason a8b46e04ef Increase width of ModelSelector 2025-09-10 13:05:43 -05:00
Alex Gleason e899a93358 Fix streaming message not being saved 2025-09-10 13:04:05 -05:00
Alex Gleason 2005acc343 Disable homepage form unless a model is selected 2025-09-10 12:59:56 -05:00
Alex Gleason 716bd42c7d Fix streaming message disappearing after it finishes 2025-09-10 12:14:48 -05:00
Alex Gleason c74edebc1b Use mkstack from gitlab 2025-09-10 11:39:11 -05:00
Alex Gleason 6c37b11b59 Fix cost calculation, improve display 2025-09-10 11:36:22 -05:00
Alex Gleason 1042bdcf56 Improve KindGenerator performance 2025-09-09 23:30:56 -05:00
Alex Gleason facbeff722 Track session context usage 2025-09-09 23:22:57 -05:00
Alex Gleason 6e9e04a65f Added cost indicator 2025-09-09 23:12:24 -05:00
Alex Gleason ddba6c3cea Extract context_length and pricing from API if available 2025-09-09 23:01:33 -05:00
Alex Gleason 695f500ab0 Add a bunch more shell commands 2025-09-09 20:51:14 -05:00
Alex Gleason 9d5f575765 Add a bunch more shell commands 2025-09-09 19:52:41 -05:00
Alex Gleason 9afa747cd4 Add special rendering for shell commands 2025-09-09 19:39:38 -05:00
Alex Gleason 7cbcd03c10 Add a bunch of shell tool commands 2025-09-09 19:30:06 -05:00
Alex Gleason a8c021411b Add virtual shell command 2025-09-09 19:03:36 -05:00
Alex Gleason aaa2dc1100 Add Scroll to Bottom button to chat UI 2025-09-09 11:17:50 -05:00
Alex Gleason 774280dc90 Upgrade mkstack 2025-09-08 15:25:31 -05:00
Alex Gleason 85f71fd00a Remove README.md and reinitialize git after cloning stack 2025-09-08 13:50:30 -05:00
Alex Gleason 0732fc5efd Add "Your Environment" section to system prompt 2025-09-08 13:31:55 -05:00
Alex Gleason d49c52a8d8 Remove WebContainers 2025-09-07 21:07:42 -05:00
Alex Gleason 26635a4b6a Deploy with picohost 2025-09-07 17:58:19 -05:00
Alex Gleason fd9aa5b683 Add NIP98Client 2025-09-07 17:41:39 -05:00
Alex Gleason c32fa627e4 Merge branch 'sessionManager' into 'main'
Use multi-session agent chats

See merge request soapbox-pub/act2!4
2025-09-06 06:31:06 +00:00
Chad Curtis 423828705a space rm 2025-09-06 03:33:55 +00:00
Chad Curtis c8e78f8a19 local storage fix 2025-09-06 03:28:54 +00:00
Chad Curtis ba273282db Use DotAI over local storage 2025-09-06 02:46:37 +00:00
Chad Curtis 0e1ccfe469 Fix messages appearing immediately, again. 2025-09-06 00:23:12 +00:00
Chad Curtis a177c81314 cleanup v2 2025-09-05 23:30:45 +00:00
Chad Curtis 6583e29d08 cleanup 2025-09-05 23:21:58 +00:00
Chad Curtis a3d491f1a5 clean up icons 2025-09-05 22:44:47 +00:00
Chad Curtis beeffd820d remove status indicator button and count, move progress icons to folder 2025-09-05 22:24:38 +00:00
Chad Curtis e622c09251 Fix messages not appearing 2025-09-05 22:17:46 +00:00
Chad Curtis 8475ca7c1a baseline session management 2025-09-04 06:35:55 +00:00
Alex Gleason da1d221e1d Read from AGENTS.md before CONTEXT.md 2025-08-31 20:44:50 -05:00
Alex Gleason fe5fd75487 Add xAI 2025-08-30 21:32:12 -05:00
Alex Gleason 2e0d97a8bf Reorganize menus somewhat 2025-08-30 18:22:50 -05:00
Alex Gleason e7f56aaa78 Conditionally display GitStatusIndicator 2025-08-30 17:52:46 -05:00
Alex Gleason a5de673ad9 Move git status indicator to Code tab 2025-08-30 17:49:48 -05:00
Alex Gleason 2728be2aa6 Improve sizing consistency of sidebar header 2025-08-30 17:30:48 -05:00
Alex Gleason 6fc0bb96be Also color-code editor pane titles with their git state 2025-08-30 16:52:34 -05:00
Alex Gleason 5867e1313c FileTree: add highlighting to changed paths 2025-08-30 16:39:08 -05:00
Alex Gleason a9400df4b9 Add git info to ProjectInfoDialog 2025-08-29 15:20:52 -05:00
Alex Gleason 11deafd5cc Remove buggy ProjectInfoDialog test 2025-08-29 14:18:55 -05:00
Alex Gleason 6f1e01fe8b Add ProjectInfoDialog 2025-08-29 12:58:53 -05:00
Alex Gleason 2e7c185f3b Improve ModelSelector styles on small screens 2025-08-29 12:03:55 -05:00
Alex Gleason 35b2e8c53f Display git status indicator 2025-08-28 18:44:49 -05:00
Alex Gleason 7fe8236611 ModelSelector conditional elements 2025-08-28 17:17:05 -05:00
Alex Gleason 2b95959361 Make left sidebar acessible on all screen sizes 2025-08-28 16:07:29 -05:00
Alex Gleason 0fcea2a61b Actually fix sidebar click events bug 2025-08-28 15:30:25 -05:00
Alex Gleason 09e4ae7c59 Revert "Fix deleting project from homepage"
This reverts commit f8adf59780.
2025-08-28 15:18:25 -05:00
Alex Gleason f8adf59780 Fix deleting project from homepage 2025-08-28 15:15:45 -05:00
Alex Gleason e1ca6d7bbc Add custom rendering for Nostr tool calls 2025-08-28 14:37:15 -05:00
Alex Gleason 1b04be3c46 Fix tool argument parsing 2025-08-28 14:33:31 -05:00
Alex Gleason 027c4f4fd2 Add Nostr AI tools 2025-08-28 14:12:16 -05:00
Alex Gleason 3fe2c8e9db Add system prompt 2025-08-26 23:22:43 -05:00
Alex Gleason 75c01dafd5 Remove unused imports 2025-08-26 22:32:35 -05:00
Alex Gleason 6260ce630d Simplify clone page 2025-08-26 22:32:12 -05:00
Alex Gleason 3841b68d7a Change chat/preview proportions to 60/40 2025-08-26 22:29:01 -05:00
Alex Gleason f789434f1b Clean up AI Settings Dialog 2025-08-26 20:35:39 -05:00
Alex Gleason 4302b7c2fb Fix "start new session" button 2025-08-26 13:45:41 -05:00
Alex Gleason 84a6c1b38c Fix needing to send 2 messages to start a chat 2025-08-26 12:33:04 -05:00
Alex Gleason d1110445e6 Allow apiKey to be empty 2025-08-26 12:03:42 -05:00
Alex Gleason 365ce0757e Simplify left sidebar 2025-08-25 23:09:55 -05:00
Alex Gleason 029edb4758 Simplify project actions 2025-08-25 23:04:03 -05:00
Alex Gleason 637b6ff0aa Don't hide model selector behind conditional 2025-08-25 22:45:11 -05:00
Alex Gleason 8a0071563f Add model selector to new project input 2025-08-25 22:34:15 -05:00
Alex Gleason cdc18303b4 Add Manage Providers option into model dropdown 2025-08-25 22:25:24 -05:00
Alex Gleason 5e45c86a0f Require the user to select a model 2025-08-25 21:55:45 -05:00
Alex Gleason b5d8e1764a Improve model selector styles 2025-08-25 21:22:50 -05:00
Alex Gleason 36a4782383 Add preset providers 2025-08-25 21:04:02 -05:00
Alex Gleason f280b0c183 Don't capitalize provider name 2025-08-25 19:45:28 -05:00
Alex Gleason 3a3cfb51c5 Put custom model at top of dropdown 2025-08-25 19:32:37 -05:00
Alex Gleason 1415008d67 Fetch models from API 2025-08-25 19:19:28 -05:00
Alex Gleason fd485ac1e9 Add model selector 2025-08-25 18:49:49 -05:00
Alex Gleason b9d9ab8526 Add recentlyUsedModels 2025-08-25 17:38:48 -05:00
Alex Gleason 5eb18965ff Fix Enter behavior on homepage 2025-08-25 17:14:48 -05:00
Alex Gleason 53e07d1f26 Fix the behavior of the create project textarea 2025-08-25 16:59:51 -05:00
Alex Gleason 857bea336a Simplify homepage textarea 2025-08-25 16:33:26 -05:00
Alex Gleason eb54b1eb9d Remove onboarding for now 2025-08-25 16:27:09 -05:00
Alex Gleason cd378f537e Rework chat textarea 2025-08-25 16:18:39 -05:00
Alex Gleason 4675f1126d Clone with nip05 identifier 2025-08-25 15:03:58 -05:00
Alex Gleason 60bb66d0ac Clone by Nostr URI 2025-08-25 14:43:23 -05:00
Alex Gleason 02e6d6d1d5 Allow configuring multiple AI providers 2025-08-25 13:23:23 -05:00
Alex Gleason 5e6208eebb Improve display of user messages 2025-08-25 12:53:56 -05:00
Alex Gleason 7f68a664a7 Add build_project tool 2025-08-25 12:47:25 -05:00
Alex Gleason 49866709c0 Remove unused deps, SPEC.md 2025-08-25 12:30:07 -05:00
Alex Gleason a70399b780 Add tool call loading indicator 2025-08-24 22:13:25 -05:00
Alex Gleason 4555565753 Add padding around user messages, fix "Stop" button position 2025-08-24 22:06:17 -05:00
Alex Gleason 4253f57ed8 Simplify chat UI 2025-08-24 21:53:48 -05:00
Alex Gleason cb2859f60c Improve empty assistant messages 2025-08-24 21:44:27 -05:00
Alex Gleason 9818b99812 Make tool calls look beautiful 2025-08-24 21:03:27 -05:00
Alex Gleason d0d85f26b2 Improve UI for tool calls 2025-08-24 20:53:47 -05:00
Alex Gleason 6c0bab27c0 Merge remote-tracking branch 'origin/main' 2025-08-24 19:58:35 -05:00
Alex Gleason 61cdc763f8 Use Streamdown (but the css is kinda messed up still) 2025-08-24 19:37:05 -05:00
Alex Gleason be73d63bf2 Use Streamdown (but the css is kinda messed up still) 2025-08-24 19:34:35 -05:00
Alex Gleason 6c540fc099 Add streaming 2025-08-24 17:18:57 -05:00
Alex Gleason 7b19cbcd52 useAIChat: infinite while-loop 2025-08-24 17:03:38 -05:00
Alex Gleason 5350506a89 DotAI: addToHistory -> setHistory 2025-08-24 16:53:48 -05:00
Alex Gleason 479df7cdad DRY variable in useAIChat 2025-08-24 16:43:00 -05:00
Alex Gleason 570f594dc7 Save and load chat history again 2025-08-24 16:34:46 -05:00
Alex Gleason b813dbe8c4 Add DotAI module again 2025-08-24 16:22:56 -05:00
Alex Gleason 558044db25 Use OpenAI messages format 2025-08-24 16:12:53 -05:00
Alex Gleason 5d11f51e05 Rip out the streaming chat code 2025-08-24 14:18:01 -05:00
Alex Gleason 1264384402 Remove ai-elements 2025-08-24 13:59:43 -05:00
Alex Gleason 65309f25c2 Fix how messages are saved (it breaks tools again) 2025-08-23 17:16:41 -05:00
Alex Gleason c565decbe3 Fix tools again, except it's still in the wrong format goddammit 2025-08-23 15:38:32 -05:00
Alex Gleason 4bc1ae96c9 Fix tool calls, remove dead code 2025-08-23 15:13:34 -05:00
Alex Gleason d3390fdbba Simplify streamdown usage 2025-08-23 13:07:38 -05:00
Alex Gleason d90f2cc83d Fix empty assistant message being added to history 2025-08-23 13:01:28 -05:00
Alex Gleason e07f55e5ed Fix loading messages from .ai dir 2025-08-23 01:31:22 -05:00
Alex Gleason 4df17bc17e Add DotAI class 2025-08-23 01:24:13 -05:00
Alex Gleason 9a4c2a8cb5 Improve useStreamingChat types 2025-08-22 16:55:16 -05:00
Alex Gleason cd6b797481 Ensure streamed content is broken up across multiple messages 2025-08-21 15:45:15 -05:00
Alex Gleason 7ceb99ec79 Start implementing streaming API 2025-08-21 13:45:56 -05:00
Alex Gleason 79f11383f1 ReadWebpageTool: fix newlines in codeblocks 2025-08-21 13:38:53 -05:00
Alex Gleason cc62c116a8 Fix fetch mcp 2025-08-21 13:34:58 -05:00
Alex Gleason a9f6a04e83 Add fetch mcp 2025-08-21 13:13:01 -05:00
Alex Gleason 69453350a2 Add ReadWebpageTool 2025-08-21 13:12:30 -05:00
Alex Gleason a0c3bf02ec Clear messages when navigating between projects 2025-08-21 12:41:03 -05:00
Alex Gleason ba1b08eab8 Use my streamdown fork 2025-08-20 20:17:19 -05:00
Alex Gleason d90d203ac3 Add ai-elements 2025-08-20 16:45:12 -05:00
Alex Gleason 678d898d48 Swap out deprecated types 2025-08-20 16:05:32 -05:00
Alex Gleason 351d13e1c3 Upgrade ai-sdk to the latest version 2025-08-20 16:03:03 -05:00
Alex Gleason c9214b5535 Allow cloning from GitHub/GitLab with corsProxy 2025-08-20 14:49:11 -05:00
Alex Gleason cfdd412546 Add clone repo page, fix deleting a local repo directory 2025-08-20 14:34:28 -05:00
Alex Gleason c649698806 Remove repos list from homepage 2025-08-20 13:52:35 -05:00
Alex Gleason 3accc0e158 Prepare for stacks 1.0 2025-08-19 19:38:26 -05:00
Alex Gleason 352bb2c059 Fix transitive package version resolution to support scoped packages 2025-08-11 19:32:48 -07:00
Alex Gleason 4a9bf570f8 Correctly resolve transitive deps 2025-08-11 17:21:29 -07:00
Alex Gleason 4f608d2dd2 Load esbuild-wasm more efficiently, fix tests 2025-08-11 16:17:09 -07:00
Alex Gleason 7eaa3f583f Load Tailwind config 2025-08-11 15:32:29 -07:00
Alex Gleason 0cb6096019 Cache redirected URLs in onLoad 2025-08-11 13:50:01 -08:00
Alex Gleason 82daf4044b mkstack builds with esbuild 2025-08-11 13:15:08 -08:00
Alex Gleason 4f31588cec lightningFsPlugin path resolution fix 2025-08-09 14:03:14 -05:00
Alex Gleason 5fe4a8fa97 Restore lightningFsPlugin 2025-08-07 15:43:27 -05:00
Alex Gleason 6d6e928854 It's very close but still not working 2025-08-07 14:53:09 -05:00
Alex Gleason 54cb053dfe Fix LightningFS resolver 2025-08-07 14:45:48 -05:00
Alex Gleason d564da3872 Fix esm.sh plugin for namespaced packages and jsr 2025-08-07 14:40:59 -05:00
Alex Gleason cd3be1ae27 Fix Tailwind (bad) 2025-08-07 14:10:27 -05:00
Alex Gleason ca8e4616b4 Fix multiple react versions 2025-08-06 22:24:47 -05:00
Alex Gleason 8dfefdc7fd Resolve package.json versions 2025-08-06 22:09:52 -05:00
Alex Gleason d89555723b Parse index.html (fragile) 2025-08-06 21:37:31 -05:00
Alex Gleason 28ec6f98cf esbuild almost works! 2025-08-06 20:57:33 -05:00
Alex Gleason 6009ee7360 Remove useNostrRepos hook, consolidate code into useRepos 2025-07-30 22:21:38 -05:00
Alex Gleason b9677ca557 Add folder icons to left sidebar 2025-07-30 22:10:27 -05:00
Alex Gleason 2e2ba2be58 Preserve original project names 2025-07-30 22:07:41 -05:00
Alex Gleason 1dacc1371b Add unified useRepos hook 2025-07-30 22:04:08 -05:00
Alex Gleason 1890a22efe Remove createdAt from Project interface 2025-07-30 21:52:15 -05:00
Alex Gleason 202b61ec2e Get rid of project.json files 2025-07-30 21:46:31 -05:00
Alex Gleason aba494e6b9 Show all directories under /projects 2025-07-30 15:40:07 -05:00
Alex Gleason 56863d5672 Add Nostr repos list 2025-07-30 15:01:59 -05:00
Alex Gleason 2ff99b7116 Update stacks stuff 2025-07-29 00:10:03 -05:00
Alex Gleason a267a2644c Merge branch 'onboardingUpdate' into 'main'
Small onboarding UX improvements + mobile onboarding

See merge request soapbox-pub/act2!1
2025-07-28 16:20:58 +00:00
Chad Curtis bb1287e02e center progress labels for onboarding 2025-07-28 14:18:30 +00:00
Chad Curtis 00a24f13b6 Re-use local storage prompt on index until project has been created. 2025-07-28 14:13:08 +00:00
Chad Curtis 213eda9797 further optimization for small screens 2025-07-28 14:03:24 +00:00
Chad Curtis 47e3bf8fe5 fix bug where onboarding does not appear on mobile. make step 1 fit more nicely on smaller screens. 2025-07-28 09:35:19 +00:00
Chad Curtis 95f3ebc1e0 Revert earlier commit sans re-using the prompt for onboarding. 2025-07-28 08:26:25 +00:00
Chad Curtis 2f8439d6ac Do not show sidebar until a project exists. 2025-07-28 08:20:01 +00:00
Chad Curtis f13c99de80 Add login/signup call to action below index prompt. Re-use index prompt if user began typing before logging in. 2025-07-28 08:11:43 +00:00
Alex Gleason ed21b3db8d Don't skip .git when creating project zip 2025-07-27 20:11:06 -05:00
Alex Gleason bb19f05f8f Play dog whistle sine wave to make persistent notification display on Android 2025-07-27 19:42:08 -05:00
Alex Gleason c5cd14afb5 Add favicon 2025-07-27 18:36:18 -05:00
Alex Gleason 6cfa34c341 Add useKeepAlive hook 2025-07-27 18:34:15 -05:00
Alex Gleason 4bdb25b687 Simplify project metadata 2025-07-26 18:10:48 -05:00
Alex Gleason 477d59d271 Don't add random characters to project names. Increment if repeated 2025-07-25 20:17:45 -05:00
Alex Gleason 7b43eed28d Export individual projects as zip 2025-07-25 20:07:59 -05:00
Alex Gleason fc296b44d8 Filesystem export 2025-07-25 19:36:44 -05:00
Alex Gleason 05cfecd073 Add download zip 2025-07-25 19:22:05 -05:00
Alex Gleason 6ee7472b65 When build finishes, refresh preview pane 2025-07-25 15:03:59 -05:00
Alex Gleason cbcab47db3 "Build" and "Deploy" button feedback 2025-07-25 15:00:13 -05:00
Alex Gleason 93f6ab8b61 Clean up ProjectSidebar 2025-07-25 14:47:59 -05:00
Alex Gleason 0881ef6524 Add git_commit tool-call component 2025-07-25 14:41:56 -05:00
Alex Gleason 15014a7bb1 Use a proper commit name and email 2025-07-25 14:21:59 -05:00
Alex Gleason af911d8592 In rollback, use only first line of target commit message 2025-07-25 14:18:28 -05:00
Alex Gleason c63caaf040 Improve GitHistoryDialog design 2025-07-25 14:11:29 -05:00
Alex Gleason 66f1d9140f Improve display of multiline commit messages 2025-07-25 13:32:07 -05:00
Alex Gleason d8b0584915 Add git rollback button to commit history 2025-07-25 13:20:49 -05:00
Alex Gleason 4e0dfd9883 Add Git History dialog 2025-07-25 13:09:39 -05:00
Chad Curtis 8fd42b9a94 more onboarding improvements 2025-07-25 12:55:44 -05:00
Chad Curtis 6fb8e9dbc6 baseline onboarding flow 2025-07-25 12:55:44 -05:00
Alex Gleason 4d9a4bf9e2 Add git_commit tool 2025-07-25 12:53:33 -05:00
Alex Gleason 15ce829190 Fix display of tool results 2025-07-25 03:38:25 -05:00
Alex Gleason faf4b669bb Update lockfile 2025-07-25 03:09:25 -05:00
Alex Gleason 9bdfe64ced Remove unnecessary instructions 2025-07-25 03:04:54 -05:00
Alex Gleason ae6c83dc70 Add npm tools 2025-07-25 03:01:14 -05:00
Alex Gleason 52ce8e5d0b Don't use custom dirname implementation 2025-07-25 02:33:44 -05:00
Alex Gleason 2f1d7c7302 Fix TextEditorWriteTool 2025-07-25 02:26:18 -05:00
Alex Gleason 2aa0e0c320 Add text_editor tools 2025-07-25 02:19:28 -05:00
Chad Curtis c28461942c fix mobile nav via sidebar, hide sidebar by default on mobile 2025-07-21 03:31:39 +00:00
Chad Curtis a114de32a9 minor fixes 2025-07-21 03:18:04 +00:00
Chad Curtis d73206c237 Reimplement assistant/tool response rendering akin to the original Shakespeare 2025-07-21 02:27:25 +00:00
Chad Curtis f58bc266d6 baseline style v2 2025-07-21 01:50:10 +00:00
Chad Curtis 03109e63b5 baseline style 2025-07-21 01:34:34 +00:00
Alex Gleason 37c16f54ef Update deploy relays 2025-07-20 19:16:59 -05:00
Alex Gleason b6275fc33e Add deploy button 2025-07-20 19:11:41 -05:00
Alex Gleason 68d852b5b8 JSRuntime: remove WebContainer type dependency 2025-07-20 17:57:07 -05:00
Alex Gleason a7d44e7ec5 .project.json -> .git/project.json 2025-07-20 17:43:25 -05:00
Alex Gleason 87f5d6a117 Adapt FS before passing it to FSProvider 2025-07-20 17:27:04 -05:00
Alex Gleason 3bf924ef3a fs.ts -> ProjectsManager.ts 2025-07-20 17:22:28 -05:00
Alex Gleason 79676891a0 Runtime.fs() must return a promise 2025-07-20 17:14:11 -05:00
Alex Gleason 0fbd5f0b84 Add missing FS methods needed by isomorphic-git 2025-07-20 17:03:48 -05:00
Alex Gleason 0b0696e624 Force FS types into a shared RuntimeFS type 2025-07-20 16:45:04 -05:00
Alex Gleason 43a272b50f Remove .mount call 2025-07-20 16:24:20 -05:00
Alex Gleason 1ab9763302 Abstract WebContainer into "JSRuntime" type 2025-07-20 16:21:49 -05:00
Alex Gleason e0053af20a ShakespeareHome -> Index 2025-07-20 15:45:07 -05:00
Alex Gleason ddedf9d11f Add useProjectsManager hook 2025-07-20 15:41:57 -05:00
Alex Gleason 27c541a6be Remove ServiceWorker 2025-07-20 15:34:01 -05:00
Alex Gleason ba4b8d040f Fix linter errors 2025-07-20 15:31:29 -05:00
Alex Gleason 29ce881e63 npm audit fix 2025-07-20 15:23:34 -05:00
Alex Gleason 9c3812c405 Add useFS hook 2025-07-20 15:17:46 -05:00
Alex Gleason 6b28a01413 Remove dead code 2025-07-20 14:35:03 -05:00
Alex Gleason d1f7063d48 Make refresh button actually refresh 2025-07-20 14:10:52 -05:00
Alex Gleason 6b99d31fdc SHAKESPEARE.md -> README.md 2025-07-20 14:09:16 -05:00
Alex Gleason 5b2f6e1938 Implement new iframe preview system 2025-07-20 14:07:48 -05:00
Alex Gleason 245e424c3a eslint html tweak, improve iframe-fetch-client text 2025-07-20 13:20:23 -05:00
Alex Gleason f09236d61d Add iframe-fetch-client code 2025-07-20 13:15:33 -05:00
Alex Gleason 295854af48 It works! 2025-07-19 22:21:15 -05:00
Alex Gleason d0190cacf9 Revert "Deploy with nostrdeploy"
This reverts commit 9b35a16d7b.
2025-07-19 13:34:49 -05:00
Alex Gleason 9b35a16d7b Deploy with nostrdeploy 2025-07-18 23:35:12 -05:00
Alex Gleason 75e2830057 Make sw.js use LightningFS directly 2025-07-18 19:08:15 -05:00
Alex Gleason c68f76adbc iframe improvements 2025-07-18 18:37:10 -05:00
Alex Gleason 5ac349f1eb Serve raw file paths from sw.js 2025-07-18 18:22:08 -05:00
Alex Gleason df45d927db Start making preview pane work 2025-07-18 15:59:20 -05:00
Alex Gleason 0fa7093461 Run build and install together (it works wtf!!!!) 2025-07-18 14:47:47 -05:00
Alex Gleason 514fb9c2b0 Fix copying node_modules 2025-07-17 19:13:37 -05:00
Alex Gleason b55a378396 Try copying node_modules in 2025-07-17 18:49:01 -05:00
Alex Gleason 3d8ccdca45 Build progress 2025-07-17 18:15:54 -05:00
Alex Gleason 157ddfdac9 Implement more FS tools 2025-07-17 15:52:23 -05:00
Alex Gleason bcfb9d54ef Deduplicate messages by ID when adding them to the messages history 2025-07-17 14:15:29 -05:00
Alex Gleason 0ae7a45dd8 Add a tidier FsToolSet 2025-07-17 13:46:55 -05:00
Alex Gleason 475b998c1a Make the agent loop work 2025-07-17 12:55:30 -05:00
Alex Gleason cdbcbfa3ee Fix tool calls using the wrong directory 2025-07-17 12:11:40 -05:00
Alex Gleason 96b7d31475 Fix lint errors 2025-07-16 16:29:20 -05:00
Alex Gleason 08024d2269 Add AI settings 2025-07-16 16:02:41 -05:00
Alex Gleason f7f76fe14f Shakespeare 2025-07-16 14:32:02 -05:00
Alex Gleason ec5d8de6c2 Stack: nostr:naddr1qvzqqqrhl5pzqprpljlvcnpnw3pejvkkhrc3y6wvmd7vjuad0fg2ud3dky66gaxaqqrk66mnw3skx6c4g6ltw 2025-07-16 14:07:08 -05:00
362 changed files with 50061 additions and 12556 deletions

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
VITE_GITHUB_OAUTH_CLIENT_ID="********************"
VITE_GITHUB_OAUTH_CLIENT_SECRET="****************************************"
-9
View File
@@ -1,9 +0,0 @@
{
"mcpServers": {
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "xjsr", "@nostrbook/mcp"]
}
}
}
-978
View File
@@ -1,978 +0,0 @@
# Project Overview
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
## Technology Stack
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
- **Vite**: Fast build tool and development server
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
- **Nostrify**: Nostr protocol framework for Deno and web
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
- **TanStack Query**: For data fetching, caching, and state management
- **TypeScript**: For type-safe JavaScript development
## Project Structure
- `/src/components/`: UI components including NostrProvider for Nostr integration
- `/src/components/ui/`: shadcn/ui components (48+ components available)
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
- `/src/hooks/`: Custom hooks including:
- `useNostr`: Core Nostr protocol integration
- `useAuthor`: Fetch user profile data by pubkey
- `useCurrentUser`: Get currently logged-in user
- `useNostrPublish`: Publish events to Nostr
- `useUploadFile`: Upload files via Blossom servers
- `useAppContext`: Access global app configuration
- `useTheme`: Theme management
- `useToast`: Toast notifications
- `useLocalStorage`: Persistent local storage
- `useLoggedInAccounts`: Manage multiple accounts
- `useLoginActions`: Authentication actions
- `useIsMobile`: Responsive design helper
- `/src/pages/`: Page components used by React Router (Index, NotFound)
- `/src/lib/`: Utility functions and shared logic
- `/src/contexts/`: React context providers (AppContext)
- `/src/test/`: Testing utilities including TestApp component
- `/public/`: Static assets
- `App.tsx`: Main app component with provider setup
- `AppRouter.tsx`: React Router configuration
## UI Components
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
- **Accordion**: Vertically collapsing content panels
- **Alert**: Displays important messages to users
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
- **AspectRatio**: Maintains consistent width-to-height ratio
- **Avatar**: User profile pictures with fallback support
- **Badge**: Small status descriptors for UI elements
- **Breadcrumb**: Navigation aid showing current location in hierarchy
- **Button**: Customizable button with multiple variants and sizes
- **Calendar**: Date picker component
- **Card**: Container with header, content, and footer sections
- **Carousel**: Slideshow for cycling through elements
- **Chart**: Data visualization component
- **Checkbox**: Selectable input element
- **Collapsible**: Toggle for showing/hiding content
- **Command**: Command palette for keyboard-first interfaces
- **ContextMenu**: Right-click menu component
- **Dialog**: Modal window overlay
- **Drawer**: Side-sliding panel (using vaul)
- **DropdownMenu**: Menu that appears from a trigger element
- **Form**: Form validation and submission handling
- **HoverCard**: Card that appears when hovering over an element
- **InputOTP**: One-time password input field
- **Input**: Text input field
- **Label**: Accessible form labels
- **Menubar**: Horizontal menu with dropdowns
- **NavigationMenu**: Accessible navigation component
- **Pagination**: Controls for navigating between pages
- **Popover**: Floating content triggered by a button
- **Progress**: Progress indicator
- **RadioGroup**: Group of radio inputs
- **Resizable**: Resizable panels and interfaces
- **ScrollArea**: Scrollable container with custom scrollbars
- **Select**: Dropdown selection component
- **Separator**: Visual divider between content
- **Sheet**: Side-anchored dialog component
- **Sidebar**: Navigation sidebar component
- **Skeleton**: Loading placeholder
- **Slider**: Input for selecting a value from a range
- **Sonner**: Toast notification manager
- **Switch**: Toggle switch control
- **Table**: Data table with headers and rows
- **Tabs**: Tabbed interface component
- **Textarea**: Multi-line text input
- **Toast**: Toast notification component
- **ToggleGroup**: Group of toggle buttons
- **Toggle**: Two-state button
- **Tooltip**: Informational text that appears on hover
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
## System Prompt Management
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
1. Edit CONTEXT.md directly
2. The changes take effect in the next session
## "Vibed with MKStack"
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
## Nostr Protocol Integration
This project comes with custom hooks for querying and publishing events on the Nostr network.
### Nostr Implementation Guidelines
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
#### Choosing Between Existing NIPs and Custom Kinds
When implementing features that could use existing NIPs, follow this decision framework:
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
4. **Extension Strategy**: When existing NIPs are close but not perfect:
- Use the existing kind as the base
- Add domain-specific tags for additional metadata
- Document the extensions in `NIP.md`
5. **When to Generate Custom Kinds**:
- No existing NIP covers the core functionality
- The data structure is fundamentally different from existing patterns
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
**Example Decision Process**:
```
Need: Equipment marketplace for farmers
Options:
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
3. Custom kind - Perfect fit but no interoperability
Decision: Use NIP-99 + farming-specific tags for best balance
```
#### Tag Design Principles
When designing tags for Nostr events, follow these principles:
1. **Kind vs Tags Separation**:
- **Kind** = Schema/structure (how the data is organized)
- **Tags** = Semantics/categories (what the data represents)
- Don't create different kinds for the same data structure
2. **Use Single-Letter Tags for Categories**:
- **Relays only index single-letter tags** for efficient querying
- Use `t` tags for categorization, not custom multi-letter tags
- Multiple `t` tags allow items to belong to multiple categories
3. **Relay-Level Filtering**:
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
- Avoid client-side filtering when relay-level filtering is possible
- Consider query patterns when designing tag structure
4. **Tag Examples**:
```json
// ❌ Wrong: Multi-letter tag, not queryable at relay level
["product_type", "electronics"]
// ✅ Correct: Single-letter tag, relay-indexed and queryable
["t", "electronics"]
["t", "smartphone"]
["t", "android"]
```
5. **Querying Best Practices**:
```typescript
// ❌ Inefficient: Get all events, filter in JavaScript
const events = await nostr.query([{ kinds: [30402] }]);
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
// ✅ Efficient: Filter at relay level
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
```
#### `t` Tag Filtering for Community-Specific Content
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
**When to Use:**
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
- ❌ Generic platforms: Twitter clones, general Nostr clients
**Implementation:**
```typescript
// Publishing with community tag
createEvent({
kind: 1,
content: data.content,
tags: [['t', 'farming']]
});
// Querying community content
const events = await nostr.query([{
kinds: [1],
'#t': ['farming'],
limit: 20
}], { signal });
```
### Kind Ranges
An event's kind number determines the event's behavior and storage characteristics:
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
### Content Field Design Principles
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
#### Guidelines
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
- **Empty content is valid**: Many events need only tags with `content: ""`
- **Relays only index tags**: If you need to filter by a field, it must be a tag
#### Example
**✅ Good - queryable data in tags:**
```json
{
"kind": 30402,
"content": "",
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
}
```
**❌ Bad - structured data in content:**
```json
{
"kind": 30402,
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
"tags": [["d", "product-123"]]
}
```
### NIP.md
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
### The `useNostr` Hook
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
```typescript
import { useNostr } from '@nostrify/react';
function useCustomHook() {
const { nostr } = useNostr();
// ...
}
```
### Query Nostr Data with `useNostr` and Tanstack Query
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
```typescript
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/query';
function usePosts() {
const { nostr } = useNostr();
return useQuery({
queryKey: ['posts'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
return events; // these events could be transformed into another format
},
});
}
```
#### Efficient Query Design
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
**✅ Efficient - Single query with multiple kinds:**
```typescript
// Query multiple event types in one request
const events = await nostr.query([
{
kinds: [1, 6, 16], // All repost kinds in one query
'#e': [eventId],
limit: 150,
}
], { signal });
// Separate by type in JavaScript
const notes = events.filter((e) => e.kind === 1);
const reposts = events.filter((e) => e.kind === 6);
const genericReposts = events.filter((e) => e.kind === 16);
```
**❌ Inefficient - Multiple separate queries:**
```typescript
// This creates unnecessary load and can trigger rate limiting
const [notes, reposts, genericReposts] = await Promise.all([
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
]);
```
**Query Optimization Guidelines:**
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
3. **Adjust limits**: When combining queries, increase the limit appropriately
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
#### Event Validation
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
```typescript
// Example validator function for NIP-52 calendar events
function validateCalendarEvent(event: NostrEvent): boolean {
// Check if it's a calendar event kind
if (![31922, 31923].includes(event.kind)) return false;
// Check for required tags according to NIP-52
const d = event.tags.find(([name]) => name === 'd')?.[1];
const title = event.tags.find(([name]) => name === 'title')?.[1];
const start = event.tags.find(([name]) => name === 'start')?.[1];
// All calendar events require 'd', 'title', and 'start' tags
if (!d || !title || !start) return false;
// Additional validation for date-based events (kind 31922)
if (event.kind === 31922) {
// start tag should be in YYYY-MM-DD format for date-based events
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
if (!dateRegex.test(start)) return false;
}
// Additional validation for time-based events (kind 31923)
if (event.kind === 31923) {
// start tag should be a unix timestamp for time-based events
const timestamp = parseInt(start);
if (isNaN(timestamp) || timestamp <= 0) return false;
}
return true;
}
function useCalendarEvents() {
const { nostr } = useNostr();
return useQuery({
queryKey: ['calendar-events'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
// Filter events through validator to ensure they meet NIP-52 requirements
return events.filter(validateCalendarEvent);
},
});
}
```
### The `useAuthor` Hook
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
```tsx
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
function Post({ event }: { event: NostrEvent }) {
const author = useAuthor(event.pubkey);
const metadata: NostrMetadata | undefined = author.data?.metadata;
const displayName = metadata?.name ?? genUserName(event.pubkey);
const profileImage = metadata?.picture;
// ...render elements with this data
}
```
#### `NostrMetadata` type
```ts
/** Kind 0 metadata. */
interface NostrMetadata {
/** A short description of the user. */
about?: string;
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
banner?: string;
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
bot?: boolean;
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
display_name?: string;
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
lud06?: string;
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
lud16?: string;
/** A short name to be displayed for the user. */
name?: string;
/** An email-like Nostr address according to NIP-05. */
nip05?: string;
/** A URL to the user's avatar. */
picture?: string;
/** A web URL related in any way to the event author. */
website?: string;
}
```
### The `useNostrPublish` Hook
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
```tsx
import { useState } from 'react';
import { useCurrentUser } from "@/hooks/useCurrentUser";
import { useNostrPublish } from '@/hooks/useNostrPublish';
export function MyComponent() {
const [ data, setData] = useState<Record<string, string>>({});
const { user } = useCurrentUser();
const { mutate: createEvent } = useNostrPublish();
const handleSubmit = () => {
createEvent({ kind: 1, content: data.content });
};
if (!user) {
return <span>You must be logged in to use this form.</span>;
}
return (
<form onSubmit={handleSubmit} disabled={!user}>
{/* ...some input fields */}
</form>
);
}
```
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
### Nostr Login
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
```tsx
import { LoginArea } from "@/components/auth/LoginArea";
function MyComponent() {
return (
<div>
{/* other components ... */}
<LoginArea className="max-w-60" />
</div>
);
}
```
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
### `npub`, `naddr`, and other Nostr addresses
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
- `nrelay1`: **relay references** - Relay URLs (deprecated)
#### Key Differences Between Similar Identifiers
**`note1` vs `nevent1`:**
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
- Use `note1` for simple references to text notes and threads
- Use `nevent1` when you need to include relay hints or author context for any event type
**`npub1` vs `nprofile1`:**
- `npub1`: Contains only the public key (32 bytes)
- `nprofile1`: Contains public key plus optional relay hints and petname
- Use `npub1` for simple user references
- Use `nprofile1` when you need to include relay hints or display name context
#### NIP-19 Routing Implementation
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
**How it works:**
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
- `note1`: Note section with placeholder for kind:1 text note view
- `nevent1`: Event section with placeholder for any event type view
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
**Example URLs that work automatically:**
- `/npub1abc123...` - User profile (needs implementation)
- `/note1def456...` - Kind:1 text note (needs implementation)
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
- `/naddr1jkl012...` - Addressable event (needs implementation)
**Features included:**
- Basic NIP-19 identifier decoding and routing
- Type-specific sections for different identifier types
- Error handling for invalid identifiers
- Responsive container structure
- Comments indicating where to implement specific views
**Error handling:**
- Invalid NIP-19 format → 404 NotFound
- Unsupported identifier types (like `nsec1`) → 404 NotFound
- Empty or missing identifiers → 404 NotFound
To implement NIP-19 routing in your Nostr application:
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
2. **The route is already configured** in `AppRouter.tsx`
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
4. **Add specific components** for profile views, event displays, etc. as needed
#### Event Type Distinctions
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
- The event is not a kind:1 text note
- You need to include relay hints for better discoverability
- You want to include author context
#### Use in Filters
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
```ts
// ❌ Wrong: naddr is not decoded
const events = await nostr.query(
[{ ids: [naddr] }],
{ signal }
);
```
Corrected example:
```ts
// Import nip19 from nostr-tools
import { nip19 } from 'nostr-tools';
// Decode a NIP-19 identifier
const decoded = nip19.decode(value);
// Optional: guard certain types (depending on the use-case)
if (decoded.type !== 'naddr') {
throw new Error('Unsupported Nostr identifier');
}
// Get the addr object
const naddr = decoded.data;
// ✅ Correct: naddr is expanded into the correct filter
const events = await nostr.query(
[{
kinds: [naddr.kind],
authors: [naddr.pubkey],
'#d': [naddr.identifier],
}],
{ signal }
);
```
#### Implementation Guidelines
1. **Always decode NIP-19 identifiers** before using them in queries
2. **Use the appropriate identifier type** based on your needs:
- Use `note1` for kind:1 text notes specifically
- Use `nevent1` when including relay hints or for non-kind:1 events
- Use `naddr1` for addressable events (always includes author pubkey for security)
3. **Handle different identifier types** appropriately:
- `npub1`/`nprofile1`: Display user profiles
- `note1`: Display kind:1 text notes specifically
- `nevent1`: Display any event with optional relay context
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
### Nostr Edit Profile
To include an Edit Profile form, place the `EditProfileForm` component in the project:
```tsx
import { EditProfileForm } from "@/components/EditProfileForm";
function EditProfilePage() {
return (
<div>
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
<EditProfileForm />
</div>
);
}
```
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
### Uploading Files on Nostr
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
```tsx
import { useUploadFile } from "@/hooks/useUploadFile";
function MyComponent() {
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const handleUpload = async (file: File) => {
try {
// Provides an array of NIP-94 compatible tags
// The first tag in the array contains the URL
const [[_, url]] = await uploadFile(file);
// ...use the url
} catch (error) {
// ...handle errors
}
};
// ...rest of component
}
```
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
### Nostr Encryption and Decryption
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
```ts
// Get the current user
const { user } = useCurrentUser();
// Optional guard to check that nip44 is available
if (!user.signer.nip44) {
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
}
// Encrypt message to self
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
// Decrypt message to self
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
```
### Rendering Rich Text Content
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
```tsx
import { NoteContent } from "@/components/NoteContent";
export function Post(/* ...props */) {
// ...
return (
<CardContent className="pb-2">
<div className="whitespace-pre-wrap break-words">
<NoteContent event={post} className="text-sm" />
</div>
</CardContent>
);
}
```
### Adding Comments Sections
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
#### Basic Usage
```tsx
import { CommentsSection } from "@/components/comments/CommentsSection";
function ArticlePage({ article }: { article: NostrEvent }) {
return (
<div className="space-y-6">
{/* Your article content */}
<div>{/* article content */}</div>
{/* Comments section */}
<CommentsSection root={article} />
</div>
);
}
```
#### Props and Customization
The `CommentsSection` component accepts the following props:
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
- **`title`**: Custom title for the comments section (default: "Comments")
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
- **`className`**: Additional CSS classes for styling
- **`limit`**: Maximum number of comments to load (default: 500)
```tsx
<CommentsSection
root={event}
title="Discussion"
emptyStateMessage="Start the conversation"
emptyStateSubtitle="Share your thoughts about this post"
className="mt-8"
limit={100}
/>
```
#### Commenting on URLs
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
```tsx
<CommentsSection
root={new URL("https://example.com/article")}
title="Comments on this article"
/>
```
## App Configuration
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
```typescript
const defaultConfig: AppConfig = {
theme: "light",
relayUrl: "wss://relay.nostr.band",
};
```
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
## Routing
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
1. Create your page component in `/src/pages/`
2. Import it in `AppRouter.tsx`
3. Add the route above the catch-all `*` route:
```tsx
<Route path="/your-path" element={<YourComponent />} />
```
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
## Development Practices
- Uses React Query for data fetching and caching
- Follows shadcn/ui component patterns
- Implements Path Aliases with `@/` prefix for cleaner imports
- Uses Vite for fast development and production builds
- Component-based architecture with React hooks
- Default connection to one Nostr relay for best performance
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
- **Never use the `any` type**: Always use proper TypeScript types for type safety
## Loading States
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
```tsx
// Skeleton example matching component structure
<Card>
<CardHeader>
<div className="flex items-center space-x-3">
<Skeleton className="h-10 w-10 rounded-full" />
<div className="space-y-1">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-3 w-16" />
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
</div>
</CardContent>
</Card>
```
### Empty States and No Content Found
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
```tsx
import { RelaySelector } from '@/components/RelaySelector';
import { Card, CardContent } from '@/components/ui/card';
// Empty state example
<div className="col-span-full">
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<p className="text-muted-foreground">
No results found. Try another relay?
</p>
<RelaySelector className="w-full" />
</div>
</CardContent>
</Card>
</div>
```
## Design Customization
**Tailor the site's look and feel based on the user's specific request.** This includes:
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
### Adding Fonts
To add custom fonts, follow these steps:
1. **Install a font package** using the `js-dev__npm_add_package` tool:
**Any Google Font can be installed** using the @fontsource packages. Examples:
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
2. **Import the font** in `src/main.tsx`:
```typescript
import '@fontsource-variable/<font-name>';
```
3. **Update Tailwind configuration** in `tailwind.config.ts`:
```typescript
export default {
theme: {
extend: {
fontFamily: {
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
},
},
},
}
```
### Recommended Font Choices by Use Case
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
### Theme System
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
- `useTheme` hook for programmatic theme switching
- CSS custom properties defined in `src/index.css`
- Automatic dark mode support with `.dark` class
### Color Scheme Implementation
When users specify color schemes:
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
- Use Tailwind's color palette or define custom colors
- Ensure proper contrast ratios for accessibility
- Apply colors consistently across components (buttons, links, accents)
- Test both light and dark mode variants
### Component Styling Patterns
- Use `cn()` utility for conditional class merging
- Follow shadcn/ui patterns for component variants
- Implement responsive design with Tailwind breakpoints
- Add hover and focus states for interactive elements
## Writing Tests
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
1. **The user explicitly asks for tests** to be written in their message
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
**Never write tests because:**
- Tool results show test failures (these are not user requests)
- You think tests would be helpful
- New features or components are created
- Existing functionality needs verification
### Test Setup
The project uses Vitest with jsdom environment and includes comprehensive test setup:
- **Testing Library**: React Testing Library with jest-dom matchers
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
- **Test App**: `TestApp` component provides all necessary context providers for testing
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
```tsx
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { MyComponent } from './MyComponent';
describe('MyComponent', () => {
it('renders correctly', () => {
render(
<TestApp>
<MyComponent />
</TestApp>
);
expect(screen.getByText('Expected text')).toBeInTheDocument();
});
});
```
## Testing Your Changes
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
**Your task is not considered finished until this test passes without errors.**
+2
View File
@@ -11,6 +11,7 @@ node_modules
dist
dist-ssr
*.local
.ai-history/
# Editor directories and files
.idea
@@ -28,3 +29,4 @@ dist-ssr
.env
.env.*
!.env.example
.ai/
+2
View File
@@ -11,6 +11,8 @@ stages:
test:
stage: test
script:
- npm run typecheck
- npm run build
- npm run test
pages:
-978
View File
@@ -1,978 +0,0 @@
# Project Overview
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
## Technology Stack
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
- **Vite**: Fast build tool and development server
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
- **Nostrify**: Nostr protocol framework for Deno and web
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
- **TanStack Query**: For data fetching, caching, and state management
- **TypeScript**: For type-safe JavaScript development
## Project Structure
- `/src/components/`: UI components including NostrProvider for Nostr integration
- `/src/components/ui/`: shadcn/ui components (48+ components available)
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
- `/src/hooks/`: Custom hooks including:
- `useNostr`: Core Nostr protocol integration
- `useAuthor`: Fetch user profile data by pubkey
- `useCurrentUser`: Get currently logged-in user
- `useNostrPublish`: Publish events to Nostr
- `useUploadFile`: Upload files via Blossom servers
- `useAppContext`: Access global app configuration
- `useTheme`: Theme management
- `useToast`: Toast notifications
- `useLocalStorage`: Persistent local storage
- `useLoggedInAccounts`: Manage multiple accounts
- `useLoginActions`: Authentication actions
- `useIsMobile`: Responsive design helper
- `/src/pages/`: Page components used by React Router (Index, NotFound)
- `/src/lib/`: Utility functions and shared logic
- `/src/contexts/`: React context providers (AppContext)
- `/src/test/`: Testing utilities including TestApp component
- `/public/`: Static assets
- `App.tsx`: Main app component with provider setup
- `AppRouter.tsx`: React Router configuration
## UI Components
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
- **Accordion**: Vertically collapsing content panels
- **Alert**: Displays important messages to users
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
- **AspectRatio**: Maintains consistent width-to-height ratio
- **Avatar**: User profile pictures with fallback support
- **Badge**: Small status descriptors for UI elements
- **Breadcrumb**: Navigation aid showing current location in hierarchy
- **Button**: Customizable button with multiple variants and sizes
- **Calendar**: Date picker component
- **Card**: Container with header, content, and footer sections
- **Carousel**: Slideshow for cycling through elements
- **Chart**: Data visualization component
- **Checkbox**: Selectable input element
- **Collapsible**: Toggle for showing/hiding content
- **Command**: Command palette for keyboard-first interfaces
- **ContextMenu**: Right-click menu component
- **Dialog**: Modal window overlay
- **Drawer**: Side-sliding panel (using vaul)
- **DropdownMenu**: Menu that appears from a trigger element
- **Form**: Form validation and submission handling
- **HoverCard**: Card that appears when hovering over an element
- **InputOTP**: One-time password input field
- **Input**: Text input field
- **Label**: Accessible form labels
- **Menubar**: Horizontal menu with dropdowns
- **NavigationMenu**: Accessible navigation component
- **Pagination**: Controls for navigating between pages
- **Popover**: Floating content triggered by a button
- **Progress**: Progress indicator
- **RadioGroup**: Group of radio inputs
- **Resizable**: Resizable panels and interfaces
- **ScrollArea**: Scrollable container with custom scrollbars
- **Select**: Dropdown selection component
- **Separator**: Visual divider between content
- **Sheet**: Side-anchored dialog component
- **Sidebar**: Navigation sidebar component
- **Skeleton**: Loading placeholder
- **Slider**: Input for selecting a value from a range
- **Sonner**: Toast notification manager
- **Switch**: Toggle switch control
- **Table**: Data table with headers and rows
- **Tabs**: Tabbed interface component
- **Textarea**: Multi-line text input
- **Toast**: Toast notification component
- **ToggleGroup**: Group of toggle buttons
- **Toggle**: Two-state button
- **Tooltip**: Informational text that appears on hover
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
## System Prompt Management
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
1. Edit CONTEXT.md directly
2. The changes take effect in the next session
## "Vibed with MKStack"
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
## Nostr Protocol Integration
This project comes with custom hooks for querying and publishing events on the Nostr network.
### Nostr Implementation Guidelines
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
#### Choosing Between Existing NIPs and Custom Kinds
When implementing features that could use existing NIPs, follow this decision framework:
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
4. **Extension Strategy**: When existing NIPs are close but not perfect:
- Use the existing kind as the base
- Add domain-specific tags for additional metadata
- Document the extensions in `NIP.md`
5. **When to Generate Custom Kinds**:
- No existing NIP covers the core functionality
- The data structure is fundamentally different from existing patterns
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
**Example Decision Process**:
```
Need: Equipment marketplace for farmers
Options:
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
3. Custom kind - Perfect fit but no interoperability
Decision: Use NIP-99 + farming-specific tags for best balance
```
#### Tag Design Principles
When designing tags for Nostr events, follow these principles:
1. **Kind vs Tags Separation**:
- **Kind** = Schema/structure (how the data is organized)
- **Tags** = Semantics/categories (what the data represents)
- Don't create different kinds for the same data structure
2. **Use Single-Letter Tags for Categories**:
- **Relays only index single-letter tags** for efficient querying
- Use `t` tags for categorization, not custom multi-letter tags
- Multiple `t` tags allow items to belong to multiple categories
3. **Relay-Level Filtering**:
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
- Avoid client-side filtering when relay-level filtering is possible
- Consider query patterns when designing tag structure
4. **Tag Examples**:
```json
// ❌ Wrong: Multi-letter tag, not queryable at relay level
["product_type", "electronics"]
// ✅ Correct: Single-letter tag, relay-indexed and queryable
["t", "electronics"]
["t", "smartphone"]
["t", "android"]
```
5. **Querying Best Practices**:
```typescript
// ❌ Inefficient: Get all events, filter in JavaScript
const events = await nostr.query([{ kinds: [30402] }]);
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
// ✅ Efficient: Filter at relay level
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
```
#### `t` Tag Filtering for Community-Specific Content
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
**When to Use:**
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
- ❌ Generic platforms: Twitter clones, general Nostr clients
**Implementation:**
```typescript
// Publishing with community tag
createEvent({
kind: 1,
content: data.content,
tags: [['t', 'farming']]
});
// Querying community content
const events = await nostr.query([{
kinds: [1],
'#t': ['farming'],
limit: 20
}], { signal });
```
### Kind Ranges
An event's kind number determines the event's behavior and storage characteristics:
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
### Content Field Design Principles
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
#### Guidelines
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
- **Empty content is valid**: Many events need only tags with `content: ""`
- **Relays only index tags**: If you need to filter by a field, it must be a tag
#### Example
**✅ Good - queryable data in tags:**
```json
{
"kind": 30402,
"content": "",
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
}
```
**❌ Bad - structured data in content:**
```json
{
"kind": 30402,
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
"tags": [["d", "product-123"]]
}
```
### NIP.md
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
### The `useNostr` Hook
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
```typescript
import { useNostr } from '@nostrify/react';
function useCustomHook() {
const { nostr } = useNostr();
// ...
}
```
### Query Nostr Data with `useNostr` and Tanstack Query
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
```typescript
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/query';
function usePosts() {
const { nostr } = useNostr();
return useQuery({
queryKey: ['posts'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
return events; // these events could be transformed into another format
},
});
}
```
#### Efficient Query Design
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
**✅ Efficient - Single query with multiple kinds:**
```typescript
// Query multiple event types in one request
const events = await nostr.query([
{
kinds: [1, 6, 16], // All repost kinds in one query
'#e': [eventId],
limit: 150,
}
], { signal });
// Separate by type in JavaScript
const notes = events.filter((e) => e.kind === 1);
const reposts = events.filter((e) => e.kind === 6);
const genericReposts = events.filter((e) => e.kind === 16);
```
**❌ Inefficient - Multiple separate queries:**
```typescript
// This creates unnecessary load and can trigger rate limiting
const [notes, reposts, genericReposts] = await Promise.all([
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
]);
```
**Query Optimization Guidelines:**
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
3. **Adjust limits**: When combining queries, increase the limit appropriately
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
#### Event Validation
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
```typescript
// Example validator function for NIP-52 calendar events
function validateCalendarEvent(event: NostrEvent): boolean {
// Check if it's a calendar event kind
if (![31922, 31923].includes(event.kind)) return false;
// Check for required tags according to NIP-52
const d = event.tags.find(([name]) => name === 'd')?.[1];
const title = event.tags.find(([name]) => name === 'title')?.[1];
const start = event.tags.find(([name]) => name === 'start')?.[1];
// All calendar events require 'd', 'title', and 'start' tags
if (!d || !title || !start) return false;
// Additional validation for date-based events (kind 31922)
if (event.kind === 31922) {
// start tag should be in YYYY-MM-DD format for date-based events
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
if (!dateRegex.test(start)) return false;
}
// Additional validation for time-based events (kind 31923)
if (event.kind === 31923) {
// start tag should be a unix timestamp for time-based events
const timestamp = parseInt(start);
if (isNaN(timestamp) || timestamp <= 0) return false;
}
return true;
}
function useCalendarEvents() {
const { nostr } = useNostr();
return useQuery({
queryKey: ['calendar-events'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
// Filter events through validator to ensure they meet NIP-52 requirements
return events.filter(validateCalendarEvent);
},
});
}
```
### The `useAuthor` Hook
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
```tsx
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
function Post({ event }: { event: NostrEvent }) {
const author = useAuthor(event.pubkey);
const metadata: NostrMetadata | undefined = author.data?.metadata;
const displayName = metadata?.name ?? genUserName(event.pubkey);
const profileImage = metadata?.picture;
// ...render elements with this data
}
```
#### `NostrMetadata` type
```ts
/** Kind 0 metadata. */
interface NostrMetadata {
/** A short description of the user. */
about?: string;
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
banner?: string;
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
bot?: boolean;
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
display_name?: string;
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
lud06?: string;
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
lud16?: string;
/** A short name to be displayed for the user. */
name?: string;
/** An email-like Nostr address according to NIP-05. */
nip05?: string;
/** A URL to the user's avatar. */
picture?: string;
/** A web URL related in any way to the event author. */
website?: string;
}
```
### The `useNostrPublish` Hook
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
```tsx
import { useState } from 'react';
import { useCurrentUser } from "@/hooks/useCurrentUser";
import { useNostrPublish } from '@/hooks/useNostrPublish';
export function MyComponent() {
const [ data, setData] = useState<Record<string, string>>({});
const { user } = useCurrentUser();
const { mutate: createEvent } = useNostrPublish();
const handleSubmit = () => {
createEvent({ kind: 1, content: data.content });
};
if (!user) {
return <span>You must be logged in to use this form.</span>;
}
return (
<form onSubmit={handleSubmit} disabled={!user}>
{/* ...some input fields */}
</form>
);
}
```
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
### Nostr Login
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
```tsx
import { LoginArea } from "@/components/auth/LoginArea";
function MyComponent() {
return (
<div>
{/* other components ... */}
<LoginArea className="max-w-60" />
</div>
);
}
```
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
### `npub`, `naddr`, and other Nostr addresses
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
- `nrelay1`: **relay references** - Relay URLs (deprecated)
#### Key Differences Between Similar Identifiers
**`note1` vs `nevent1`:**
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
- Use `note1` for simple references to text notes and threads
- Use `nevent1` when you need to include relay hints or author context for any event type
**`npub1` vs `nprofile1`:**
- `npub1`: Contains only the public key (32 bytes)
- `nprofile1`: Contains public key plus optional relay hints and petname
- Use `npub1` for simple user references
- Use `nprofile1` when you need to include relay hints or display name context
#### NIP-19 Routing Implementation
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
**How it works:**
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
- `note1`: Note section with placeholder for kind:1 text note view
- `nevent1`: Event section with placeholder for any event type view
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
**Example URLs that work automatically:**
- `/npub1abc123...` - User profile (needs implementation)
- `/note1def456...` - Kind:1 text note (needs implementation)
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
- `/naddr1jkl012...` - Addressable event (needs implementation)
**Features included:**
- Basic NIP-19 identifier decoding and routing
- Type-specific sections for different identifier types
- Error handling for invalid identifiers
- Responsive container structure
- Comments indicating where to implement specific views
**Error handling:**
- Invalid NIP-19 format → 404 NotFound
- Unsupported identifier types (like `nsec1`) → 404 NotFound
- Empty or missing identifiers → 404 NotFound
To implement NIP-19 routing in your Nostr application:
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
2. **The route is already configured** in `AppRouter.tsx`
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
4. **Add specific components** for profile views, event displays, etc. as needed
#### Event Type Distinctions
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
- The event is not a kind:1 text note
- You need to include relay hints for better discoverability
- You want to include author context
#### Use in Filters
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
```ts
// ❌ Wrong: naddr is not decoded
const events = await nostr.query(
[{ ids: [naddr] }],
{ signal }
);
```
Corrected example:
```ts
// Import nip19 from nostr-tools
import { nip19 } from 'nostr-tools';
// Decode a NIP-19 identifier
const decoded = nip19.decode(value);
// Optional: guard certain types (depending on the use-case)
if (decoded.type !== 'naddr') {
throw new Error('Unsupported Nostr identifier');
}
// Get the addr object
const naddr = decoded.data;
// ✅ Correct: naddr is expanded into the correct filter
const events = await nostr.query(
[{
kinds: [naddr.kind],
authors: [naddr.pubkey],
'#d': [naddr.identifier],
}],
{ signal }
);
```
#### Implementation Guidelines
1. **Always decode NIP-19 identifiers** before using them in queries
2. **Use the appropriate identifier type** based on your needs:
- Use `note1` for kind:1 text notes specifically
- Use `nevent1` when including relay hints or for non-kind:1 events
- Use `naddr1` for addressable events (always includes author pubkey for security)
3. **Handle different identifier types** appropriately:
- `npub1`/`nprofile1`: Display user profiles
- `note1`: Display kind:1 text notes specifically
- `nevent1`: Display any event with optional relay context
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
### Nostr Edit Profile
To include an Edit Profile form, place the `EditProfileForm` component in the project:
```tsx
import { EditProfileForm } from "@/components/EditProfileForm";
function EditProfilePage() {
return (
<div>
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
<EditProfileForm />
</div>
);
}
```
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
### Uploading Files on Nostr
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
```tsx
import { useUploadFile } from "@/hooks/useUploadFile";
function MyComponent() {
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const handleUpload = async (file: File) => {
try {
// Provides an array of NIP-94 compatible tags
// The first tag in the array contains the URL
const [[_, url]] = await uploadFile(file);
// ...use the url
} catch (error) {
// ...handle errors
}
};
// ...rest of component
}
```
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
### Nostr Encryption and Decryption
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
```ts
// Get the current user
const { user } = useCurrentUser();
// Optional guard to check that nip44 is available
if (!user.signer.nip44) {
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
}
// Encrypt message to self
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
// Decrypt message to self
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
```
### Rendering Rich Text Content
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
```tsx
import { NoteContent } from "@/components/NoteContent";
export function Post(/* ...props */) {
// ...
return (
<CardContent className="pb-2">
<div className="whitespace-pre-wrap break-words">
<NoteContent event={post} className="text-sm" />
</div>
</CardContent>
);
}
```
### Adding Comments Sections
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
#### Basic Usage
```tsx
import { CommentsSection } from "@/components/comments/CommentsSection";
function ArticlePage({ article }: { article: NostrEvent }) {
return (
<div className="space-y-6">
{/* Your article content */}
<div>{/* article content */}</div>
{/* Comments section */}
<CommentsSection root={article} />
</div>
);
}
```
#### Props and Customization
The `CommentsSection` component accepts the following props:
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
- **`title`**: Custom title for the comments section (default: "Comments")
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
- **`className`**: Additional CSS classes for styling
- **`limit`**: Maximum number of comments to load (default: 500)
```tsx
<CommentsSection
root={event}
title="Discussion"
emptyStateMessage="Start the conversation"
emptyStateSubtitle="Share your thoughts about this post"
className="mt-8"
limit={100}
/>
```
#### Commenting on URLs
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
```tsx
<CommentsSection
root={new URL("https://example.com/article")}
title="Comments on this article"
/>
```
## App Configuration
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
```typescript
const defaultConfig: AppConfig = {
theme: "light",
relayUrl: "wss://relay.nostr.band",
};
```
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
## Routing
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
1. Create your page component in `/src/pages/`
2. Import it in `AppRouter.tsx`
3. Add the route above the catch-all `*` route:
```tsx
<Route path="/your-path" element={<YourComponent />} />
```
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
## Development Practices
- Uses React Query for data fetching and caching
- Follows shadcn/ui component patterns
- Implements Path Aliases with `@/` prefix for cleaner imports
- Uses Vite for fast development and production builds
- Component-based architecture with React hooks
- Default connection to one Nostr relay for best performance
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
- **Never use the `any` type**: Always use proper TypeScript types for type safety
## Loading States
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
```tsx
// Skeleton example matching component structure
<Card>
<CardHeader>
<div className="flex items-center space-x-3">
<Skeleton className="h-10 w-10 rounded-full" />
<div className="space-y-1">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-3 w-16" />
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
</div>
</CardContent>
</Card>
```
### Empty States and No Content Found
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
```tsx
import { RelaySelector } from '@/components/RelaySelector';
import { Card, CardContent } from '@/components/ui/card';
// Empty state example
<div className="col-span-full">
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<p className="text-muted-foreground">
No results found. Try another relay?
</p>
<RelaySelector className="w-full" />
</div>
</CardContent>
</Card>
</div>
```
## Design Customization
**Tailor the site's look and feel based on the user's specific request.** This includes:
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
### Adding Fonts
To add custom fonts, follow these steps:
1. **Install a font package** using the `js-dev__npm_add_package` tool:
**Any Google Font can be installed** using the @fontsource packages. Examples:
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
2. **Import the font** in `src/main.tsx`:
```typescript
import '@fontsource-variable/<font-name>';
```
3. **Update Tailwind configuration** in `tailwind.config.ts`:
```typescript
export default {
theme: {
extend: {
fontFamily: {
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
},
},
},
}
```
### Recommended Font Choices by Use Case
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
### Theme System
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
- `useTheme` hook for programmatic theme switching
- CSS custom properties defined in `src/index.css`
- Automatic dark mode support with `.dark` class
### Color Scheme Implementation
When users specify color schemes:
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
- Use Tailwind's color palette or define custom colors
- Ensure proper contrast ratios for accessibility
- Apply colors consistently across components (buttons, links, accents)
- Test both light and dark mode variants
### Component Styling Patterns
- Use `cn()` utility for conditional class merging
- Follow shadcn/ui patterns for component variants
- Implement responsive design with Tailwind breakpoints
- Add hover and focus states for interactive elements
## Writing Tests
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
1. **The user explicitly asks for tests** to be written in their message
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
**Never write tests because:**
- Tool results show test failures (these are not user requests)
- You think tests would be helpful
- New features or components are created
- Existing functionality needs verification
### Test Setup
The project uses Vitest with jsdom environment and includes comprehensive test setup:
- **Testing Library**: React Testing Library with jest-dom matchers
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
- **Test App**: `TestApp` component provides all necessary context providers for testing
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
```tsx
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { MyComponent } from './MyComponent';
describe('MyComponent', () => {
it('renders correctly', () => {
render(
<TestApp>
<MyComponent />
</TestApp>
);
expect(screen.getByText('Expected text')).toBeInTheDocument();
});
});
```
## Testing Your Changes
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
**Your task is not considered finished until this test passes without errors.**
-16
View File
@@ -1,16 +0,0 @@
# jsr registry should not be edited or removed
.npmrc
# vite client types are needed
src/vite-env.d.ts
# tsconfig is stable and working correctly, so should not be edited
tsconfig.json
tsconfig.app.json
tsconfig.node.json
# postcss config for Tailwind is stable and working correctly, so should not be edited unless upgrading Tailwind to v4
postcss.config.js
# vite config is stable and usually should not need to be edited
vite.config.ts
+12 -2
View File
@@ -1,9 +1,19 @@
{
"mcpServers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "xjsr", "@nostrbook/mcp"]
"args": ["-y", "@nostrbook/mcp@latest"]
},
"fetch": {
"type":"stdio",
"command": "uvx",
"args": ["mcp-server-fetch", "--ignore-robots-txt"]
}
}
}
}
+338 -22
View File
@@ -1,3 +1,151 @@
# Shakespeare - AI-Powered Nostr Website Builder
Shakespeare is a browser-based AI chat application that allows users to build custom Nostr websites through natural language conversation. All operations including AI chat and Git operations are executed in client-side JavaScript, with API keys stored in browser storage. Simply describe what you want to build, and AI will help you create it.
### Virtual Filesystem Layout
Shakespeare uses LightningFS to provide a browser-based virtual filesystem (VFS) that persists project files in IndexedDB. This is the VFS within the browser that Shakespeare agents act upon. Each project is stored in its own isolated directory structure within the virtual filesystem.
#### Virtual Filesystem Architecture
```
/
├── projects/
│ └── {projectId}/ # Individual project directory
│ └── ... # Project files (package.json, src/, public/, etc.)
├── config/ # Configuration files
│ ├── ai.json # AI provider settings and API keys
│ └── git.json # Git credentials and repository settings
└── tmp/ # Temporary files and scratch space
└── ... # Various temporary files and directories
```
#### Key Features
- **IndexedDB Backend**: All project files are stored in the browser's IndexedDB for persistence across sessions
- **Project Isolation**: Each project has its own directory namespace to prevent conflicts
- **File Operations**: Full POSIX-like filesystem operations (read, write, mkdir, rm, etc.)
- **Git Integration**: Projects can be initialized as Git repositories for template cloning
This architecture allows Shakespeare to provide a full development environment entirely within the browser, with no server-side storage requirements.
#### AI Tools Available in Shakespeare
Shakespeare provides AI agents with specialized tools for project development (note: these are different from the tools available during Shakespeare's own development). These tools are defined in `src/lib/tools/`:
- **ShellTool**: Execute shell commands in the virtual filesystem environment
- **TextEditorViewTool**: Read file contents and view directory structures
- **TextEditorWriteTool**: Create or overwrite files with new content
- **TextEditorStrReplaceTool**: Replace strings in files
- **BuildProjectTool**: Build and compile projects
- **TypecheckTool**: Run TypeScript type checking
- **NpmAddPackageTool**: Add npm packages to projects
- **NpmRemovePackageTool**: Remove npm packages from projects
- **GitCommitTool**: Commit changes to Git repositories
- **DeployProjectTool**: Deploy projects to hosting platforms
- **ReadWebpageTool**: Fetch and read web pages
- **NostrReadNipTool**: Read Nostr protocol NIP documents
- **NostrReadKindTool**: Read Nostr event kind documentation
- **NostrReadTagTool**: Read Nostr tag documentation
- **NostrReadProtocolTool**: Read Nostr protocol basics
- **NostrReadNipsIndexTool**: Read the full list of NIPs, kinds, and tags
- **NostrFetchEventTool**: Fetch Nostr events using NIP-19 identifiers
- **NostrGenerateKindTool**: Generate unused Nostr event kind numbers
- **ReadConsoleMessagesTool**: Read console messages from project preview with filtering capabilities
#### Shell Commands
Shakespeare provides a comprehensive set of shell commands that are JavaScript reimplementations of common Unix commands. These commands operate on the virtual filesystem (VFS) and are accessible through the ShellTool. The shell commands are implemented in `src/lib/commands/` and provide familiar Unix-like functionality for file and directory operations.
**Available Commands:**
- **File Operations**: `cat`, `cp`, `mv`, `rm`, `touch`, `find`, `grep`
- **Directory Operations**: `cd`, `ls`, `mkdir`, `pwd`, `tree`
- **System Commands**: `echo`, `which`, `wc`, `head`, `tail`
- **Git Commands**: `git add`, `git commit`, `git push`, `git pull`, `git status`, `git log`, etc.
#### Security
AI filesystem access through tools (including shell commands via ShellTool) has path restrictions to ensure safe operation:
- **Read operations**: Can access any file in the VFS, including absolute paths
- **Write operations**: Restricted to current project directory and `/tmp/` directory (including subdirectories)
- **Copy operations**: Can copy from any absolute path to relative paths or `/tmp/`, but cannot copy from relative to absolute paths outside allowed areas
### Git Integration with isomorphic-git
Shakespeare provides full Git functionality in the browser using `isomorphic-git` and `@isomorphic-git/lightning-fs`, with all data persisted in IndexedDB.
#### Key Components
- **LightningFSAdapter**: Adapts LightningFS to the unified JSRuntimeFS interface
- **GitCommitTool**: AI tool for automated commits with staging and validation
- **useGitStatus Hook**: Real-time Git status monitoring (updates every 5 seconds)
- **ProjectsManager**: Handles project creation, Git initialization, and template cloning
#### Core Features
**Project Creation:**
1. Clone template from GitLab repository (shallow clone, depth: 1)
2. Remove original Git history
3. Initialize fresh repository with `main` branch
4. Stage all files and create initial commit
**Version Control:**
- Automatic staging of all changed files before commits
- Real-time status tracking (modified, added, deleted, untracked, staged files)
- Full commit history with author info and SHA hashes
- Branch management and remote repository support
**AI Integration:**
- GitCommitTool allows AI assistants to commit changes automatically
- Validates repository status and handles edge cases
- Generates descriptive commit messages with file change statistics
**Browser Compatibility:**
- CORS proxy for GitHub/GitLab repositories (`https://cors.isomorphic-git.org`)
- IndexedDB persistence across browser sessions
- Gitignore support using the `ignore` library
Git operations happen transparently in the background, providing professional version control without requiring Git knowledge from users.
## AI Message Format
Shakespeare uses OpenAI-compatible messages for communication between users and AI assistants. The message format follows these conventions:
### User Messages
**String Content**: When the user message `content` is a string, it represents the actual user's message directly.
```json
{
"role": "user",
"content": "Please help me build a todo app"
}
```
**Array Content**: When the user message `content` is an array of parts, the structure follows this pattern:
- **First text part**: Represents the user's actual message
- **Subsequent text parts**: Represent user actions, such as adding files to the VFS
```json
{
"role": "user",
"content": [
{
"type": "text",
"text": "Can you add this logo to my site?"
},
{
"type": "text",
"text": "Added file: /tmp/logo.svg"
}
]
}
```
This format allows the Shakespeare UI to parse and display user actions appropriately while maintaining compatibility with OpenAI's message format standard.
# Project Overview
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
@@ -18,6 +166,12 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `/src/components/`: UI components including NostrProvider for Nostr integration
- `/src/components/ui/`: shadcn/ui components (48+ components available)
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
- `/src/components/ai/`: AI-related components (GitCommit, GitHistoryDialog)
- `/src/components/comments/`: Comment system components (Comment, CommentForm, CommentsSection)
- `/src/components/Shakespeare/`: Core Shakespeare editor components (ChatPane, FileEditor, FileTree, PreviewPane)
- `/src/components/ProjectSidebar.tsx`: Sidebar component containing project list and import options
- `/src/components/ZipImportDialog.tsx`: Dialog component for importing projects from ZIP files
- Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments
- `/src/hooks/`: Custom hooks including:
- `useNostr`: Core Nostr protocol integration
- `useAuthor`: Fetch user profile data by pubkey
@@ -25,15 +179,44 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `useNostrPublish`: Publish events to Nostr
- `useUploadFile`: Upload files via Blossom servers
- `useAppContext`: Access global app configuration
- `useFS`: Access virtual filesystem for project file operations
- `useAISettings`: Manage AI provider configurations and API keys
- `useGitSettings`: Manage Git credentials and repository settings
- `useSessionManager`: Access session management for AI chat sessions
- `useGitStatus`: Real-time Git repository status monitoring
- `useProjects`: Project management and CRUD operations
- `useProjectsManager`: Advanced project operations (creation, cloning, building, ZIP import)
- `useTheme`: Theme management
- `useToast`: Toast notifications
- `useLocalStorage`: Persistent local storage
- `useLoggedInAccounts`: Manage multiple accounts
- `useLoginActions`: Authentication actions
- `useIsMobile`: Responsive design helper
- `/src/pages/`: Page components used by React Router (Index, NotFound)
- `useZaps`: Lightning zap functionality with payment processing
- `useWallet`: Unified wallet detection (WebLN + NWC)
- `useNWC`: Nostr Wallet Connect connection management
- `useNWCContext`: Access NWC context provider
- `/src/pages/`: Page components used by React Router (Index, NotFound, ProjectView, Settings pages)
- `/src/lib/`: Utility functions and shared logic
- `/src/contexts/`: React context providers (AppContext)
- `/src/lib/build/`: Project build system with esbuild integration (esmPlugin, fsPlugin)
- `/src/lib/commands/`: Shell command implementations for virtual filesystem
- `/src/lib/commands/git/`: Git command implementations (add, commit, push, pull, etc.)
- Unix-style commands: `cat`, `cd`, `cp`, `find`, `grep`, `ls`, `mkdir`, `mv`, `rm`, etc.
- `/src/lib/tools/`: AI tool implementations for project development
- File operations: `TextEditorViewTool`, `TextEditorWriteTool`, `TextEditorStrReplaceTool`
- Project tools: `BuildProjectTool`, `TypecheckTool`, `DeployProjectTool`
- Package management: `NpmAddPackageTool`, `NpmRemovePackageTool`
- Git integration: `GitCommitTool`
- Shell access: `ShellTool`
- Web access: `ReadWebpageTool`
- Nostr tools: `NostrReadNipTool`, `NostrFetchEventTool`, `NostrGenerateKindTool`, etc.
- `/src/contexts/`: React context providers
- `AppContext`: Global app configuration and theme
- `FSContext`: Virtual filesystem access
- `AISettingsContext`: AI provider settings and API key management
- `GitSettingsContext`: Git credentials and repository configuration
- `SessionManagerContext`: AI chat session management
- `NWCContext`: Nostr Wallet Connect integration
- `/src/test/`: Testing utilities including TestApp component
- `/public/`: Static assets
- `App.tsx`: Main app component with provider setup
@@ -81,7 +264,6 @@ The project uses shadcn/ui components located in `@/components/ui`. These are un
- **Sidebar**: Navigation sidebar component
- **Skeleton**: Loading placeholder
- **Slider**: Input for selecting a value from a range
- **Sonner**: Toast notification manager
- **Switch**: Toggle switch control
- **Table**: Data table with headers and rows
- **Tabs**: Tabbed interface component
@@ -95,11 +277,52 @@ These components follow a consistent pattern using React's `forwardRef` and use
## System Prompt Management
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
The AI assistant's behavior and knowledge is defined by the AGENTS.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
1. Edit CONTEXT.md directly
1. Edit AGENTS.md directly
2. The changes take effect in the next session
## Translations
Shakespeare includes internationalization (i18n) support using react-i18next. The translation system allows the interface to be displayed in multiple languages.
### Key Files
- **`src/lib/i18n.ts`**: Main translation configuration file containing all translation resources for supported languages
- **`src/components/LanguagePicker.tsx`**: Language selection component used in preferences, must be updated when adding new languages
### Usage in Components
Use the `useTranslation` hook to access translations in React components:
```tsx
import { useTranslation } from 'react-i18next';
function MyComponent() {
const { t } = useTranslation();
return <h1>{t('settings')}</h1>; // Returns "Settings", "Configurações", etc.
}
```
### Translation Key Organization
Translation keys are organized by functionality:
- **Navigation and Layout**: `preferences`, `settings`, `help`, etc.
- **Authentication**: `logIn`, `signUp`
- **UI Elements**: `save`, `cancel`, `loading`, etc.
- **Feature-specific sections**: AI Settings, Git Settings, Nostr Settings, etc.
### Adding New Languages
1. Add the new language code and translation object to the `resources` object in `src/lib/i18n.ts`
2. Add all required key-value pairs for the new language, following existing patterns
3. Update `src/components/LanguagePicker.tsx` to include the new language option in the dropdown
4. Add the language name translations (e.g., `spanish: 'Spanish'`) to all existing language objects
5. Use descriptive, hierarchical key names (avoid duplicates)
6. Keep translations concise and consistent with existing patterns
7. Test the new language thoroughly to ensure proper display across all components
## "Vibed with MKStack"
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
@@ -110,9 +333,9 @@ This project comes with custom hooks for querying and publishing events on the N
### Nostr Implementation Guidelines
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
- Always check the full list of existing NIPs before implementing any Nostr features to see what kinds are currently in use across all NIPs.
- If any existing kind or NIP might offer the required functionality, read the relevant NIPs to investigate thoroughly. Several NIPs may need to be read before making a decision.
- Only generate new kind numbers if no existing suitable kinds are found after comprehensive research.
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
@@ -120,7 +343,7 @@ Knowing when to create a new kind versus reusing an existing kind requires caref
When implementing features that could use existing NIPs, follow this decision framework:
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Get an overview of all NIPs, and then read specific NIPs and kind documentation to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
@@ -138,7 +361,7 @@ When implementing features that could use existing NIPs, follow this decision fr
- The data structure is fundamentally different from existing patterns
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
6. **Custom Kind Publishing**: When publishing events with custom generated kinds, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
**Example Decision Process**:
```
@@ -299,6 +522,70 @@ function usePosts() {
}
```
### Infinite Scroll for Feeds
For feed-like interfaces, implement infinite scroll using TanStack Query's `useInfiniteQuery` with Nostr's timestamp-based pagination:
```typescript
import { useNostr } from '@nostrify/react';
import { useInfiniteQuery } from '@tanstack/react-query';
export function useGlobalFeed() {
const { nostr } = useNostr();
return useInfiniteQuery({
queryKey: ['global-feed'],
queryFn: async ({ pageParam, signal }) => {
const filter = { kinds: [1], limit: 20 };
if (pageParam) filter.until = pageParam;
const events = await nostr.query([filter], {
signal: AbortSignal.any([signal, AbortSignal.timeout(1500)])
});
return events;
},
getNextPageParam: (lastPage) => {
if (lastPage.length === 0) return undefined;
return lastPage[lastPage.length - 1].created_at - 1; // Subtract 1 since 'until' is inclusive
},
initialPageParam: undefined,
});
}
```
Example usage with intersection observer for automatic loading:
```tsx
import { useInView } from 'react-intersection-observer';
function GlobalFeed() {
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useGlobalFeed();
const { ref, inView } = useInView();
useEffect(() => {
if (inView && hasNextPage) {
fetchNextPage();
}
}, [inView, hasNextPage, fetchNextPage]);
const posts = data?.pages.flat() || [];
return (
<div className="space-y-4">
{posts.map((post) => (
<PostCard key={post.id} post={post} />
))}
{hasNextPage && (
<div ref={ref} className="py-4">
{isFetchingNextPage && <Skeleton className="h-20 w-full" />}
</div>
)}
</div>
);
}
```
#### Efficient Query Design
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
@@ -494,12 +781,14 @@ The `LoginArea` component handles all the login-related UI and interactions, inc
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
**Important**: Social applications should include a profile menu button in the main interface (typically in headers/navigation) to provide access to account settings, profile editing, and logout functionality. Don't only show `LoginArea` in logged-out states.
### `npub`, `naddr`, and other Nostr addresses
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
@@ -553,7 +842,7 @@ This project includes a boilerplate `NIP19Page` component that provides the foun
**Error handling:**
- Invalid NIP-19 format → 404 NotFound
- Unsupported identifier types (like `nsec1`) → 404 NotFound
- Unsupported identifier types (like `nsec1`) → 404 NotFound
- Empty or missing identifiers → 404 NotFound
To implement NIP-19 routing in your Nostr application:
@@ -868,14 +1157,14 @@ import { Card, CardContent } from '@/components/ui/card';
To add custom fonts, follow these steps:
1. **Install a font package** using the `js-dev__npm_add_package` tool:
1. **Install a font package** using npm:
**Any Google Font can be installed** using the @fontsource packages. Examples:
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
- For Inter Variable: `@fontsource-variable/inter`
- For Roboto: `@fontsource/roboto`
- For Outfit Variable: `@fontsource-variable/outfit`
- For Poppins: `@fontsource/poppins`
- For Open Sans: `@fontsource/open-sans`
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
@@ -928,8 +1217,11 @@ When users specify color schemes:
- Implement responsive design with Tailwind breakpoints
- Add hover and focus states for interactive elements
## Writing Tests
## Writing Tests vs Running Tests
There is an important distinction between **writing new tests** and **running existing tests**:
### Writing Tests (Creating New Test Files)
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
1. **The user explicitly asks for tests** to be written in their message
@@ -942,6 +1234,14 @@ When users specify color schemes:
- New features or components are created
- Existing functionality needs verification
### Running Tests (Executing the Test Suite)
**ALWAYS run the test script** after making any code changes. This is mandatory regardless of whether you wrote new tests or not.
- **You must run the test script** to validate your changes
- **Your task is not complete** until the test script passes without errors
- **This applies to all changes** - bug fixes, new features, refactoring, or any code modifications
- **The test script includes** TypeScript compilation, ESLint checks, and existing test validation
### Test Setup
The project uses Vitest with jsdom environment and includes comprehensive test setup:
@@ -971,8 +1271,24 @@ describe('MyComponent', () => {
});
```
## Testing Your Changes
## Validating Your Changes
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
**CRITICAL**: After making any code changes, you must validate your work by running available validation tools.
**Your task is not considered finished until this test passes without errors.**
**Your task is not considered finished until the code successfully type-checks and builds without errors.**
### Validation Priority Order
Run available tools in this priority order:
1. **Type Checking** (Required): Ensure TypeScript compilation succeeds
2. **Building/Compilation** (Required): Verify the project builds successfully
3. **Linting** (Recommended): Check code style and catch potential issues
4. **Tests** (If Available): Run existing test suite
**Minimum Requirements:**
- Code must type-check without errors
- Code must build/compile successfully
- Fix any critical linting errors that would break functionality
The validation ensures code quality and catches errors before deployment, regardless of the development environment.
-978
View File
@@ -1,978 +0,0 @@
# Project Overview
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
## Technology Stack
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
- **Vite**: Fast build tool and development server
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
- **Nostrify**: Nostr protocol framework for Deno and web
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
- **TanStack Query**: For data fetching, caching, and state management
- **TypeScript**: For type-safe JavaScript development
## Project Structure
- `/src/components/`: UI components including NostrProvider for Nostr integration
- `/src/components/ui/`: shadcn/ui components (48+ components available)
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
- `/src/hooks/`: Custom hooks including:
- `useNostr`: Core Nostr protocol integration
- `useAuthor`: Fetch user profile data by pubkey
- `useCurrentUser`: Get currently logged-in user
- `useNostrPublish`: Publish events to Nostr
- `useUploadFile`: Upload files via Blossom servers
- `useAppContext`: Access global app configuration
- `useTheme`: Theme management
- `useToast`: Toast notifications
- `useLocalStorage`: Persistent local storage
- `useLoggedInAccounts`: Manage multiple accounts
- `useLoginActions`: Authentication actions
- `useIsMobile`: Responsive design helper
- `/src/pages/`: Page components used by React Router (Index, NotFound)
- `/src/lib/`: Utility functions and shared logic
- `/src/contexts/`: React context providers (AppContext)
- `/src/test/`: Testing utilities including TestApp component
- `/public/`: Static assets
- `App.tsx`: Main app component with provider setup
- `AppRouter.tsx`: React Router configuration
## UI Components
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
- **Accordion**: Vertically collapsing content panels
- **Alert**: Displays important messages to users
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
- **AspectRatio**: Maintains consistent width-to-height ratio
- **Avatar**: User profile pictures with fallback support
- **Badge**: Small status descriptors for UI elements
- **Breadcrumb**: Navigation aid showing current location in hierarchy
- **Button**: Customizable button with multiple variants and sizes
- **Calendar**: Date picker component
- **Card**: Container with header, content, and footer sections
- **Carousel**: Slideshow for cycling through elements
- **Chart**: Data visualization component
- **Checkbox**: Selectable input element
- **Collapsible**: Toggle for showing/hiding content
- **Command**: Command palette for keyboard-first interfaces
- **ContextMenu**: Right-click menu component
- **Dialog**: Modal window overlay
- **Drawer**: Side-sliding panel (using vaul)
- **DropdownMenu**: Menu that appears from a trigger element
- **Form**: Form validation and submission handling
- **HoverCard**: Card that appears when hovering over an element
- **InputOTP**: One-time password input field
- **Input**: Text input field
- **Label**: Accessible form labels
- **Menubar**: Horizontal menu with dropdowns
- **NavigationMenu**: Accessible navigation component
- **Pagination**: Controls for navigating between pages
- **Popover**: Floating content triggered by a button
- **Progress**: Progress indicator
- **RadioGroup**: Group of radio inputs
- **Resizable**: Resizable panels and interfaces
- **ScrollArea**: Scrollable container with custom scrollbars
- **Select**: Dropdown selection component
- **Separator**: Visual divider between content
- **Sheet**: Side-anchored dialog component
- **Sidebar**: Navigation sidebar component
- **Skeleton**: Loading placeholder
- **Slider**: Input for selecting a value from a range
- **Sonner**: Toast notification manager
- **Switch**: Toggle switch control
- **Table**: Data table with headers and rows
- **Tabs**: Tabbed interface component
- **Textarea**: Multi-line text input
- **Toast**: Toast notification component
- **ToggleGroup**: Group of toggle buttons
- **Toggle**: Two-state button
- **Tooltip**: Informational text that appears on hover
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
## System Prompt Management
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
1. Edit CONTEXT.md directly
2. The changes take effect in the next session
## "Vibed with MKStack"
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
## Nostr Protocol Integration
This project comes with custom hooks for querying and publishing events on the Nostr network.
### Nostr Implementation Guidelines
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
#### Choosing Between Existing NIPs and Custom Kinds
When implementing features that could use existing NIPs, follow this decision framework:
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
4. **Extension Strategy**: When existing NIPs are close but not perfect:
- Use the existing kind as the base
- Add domain-specific tags for additional metadata
- Document the extensions in `NIP.md`
5. **When to Generate Custom Kinds**:
- No existing NIP covers the core functionality
- The data structure is fundamentally different from existing patterns
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
**Example Decision Process**:
```
Need: Equipment marketplace for farmers
Options:
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
3. Custom kind - Perfect fit but no interoperability
Decision: Use NIP-99 + farming-specific tags for best balance
```
#### Tag Design Principles
When designing tags for Nostr events, follow these principles:
1. **Kind vs Tags Separation**:
- **Kind** = Schema/structure (how the data is organized)
- **Tags** = Semantics/categories (what the data represents)
- Don't create different kinds for the same data structure
2. **Use Single-Letter Tags for Categories**:
- **Relays only index single-letter tags** for efficient querying
- Use `t` tags for categorization, not custom multi-letter tags
- Multiple `t` tags allow items to belong to multiple categories
3. **Relay-Level Filtering**:
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
- Avoid client-side filtering when relay-level filtering is possible
- Consider query patterns when designing tag structure
4. **Tag Examples**:
```json
// ❌ Wrong: Multi-letter tag, not queryable at relay level
["product_type", "electronics"]
// ✅ Correct: Single-letter tag, relay-indexed and queryable
["t", "electronics"]
["t", "smartphone"]
["t", "android"]
```
5. **Querying Best Practices**:
```typescript
// ❌ Inefficient: Get all events, filter in JavaScript
const events = await nostr.query([{ kinds: [30402] }]);
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
// ✅ Efficient: Filter at relay level
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
```
#### `t` Tag Filtering for Community-Specific Content
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
**When to Use:**
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
- ❌ Generic platforms: Twitter clones, general Nostr clients
**Implementation:**
```typescript
// Publishing with community tag
createEvent({
kind: 1,
content: data.content,
tags: [['t', 'farming']]
});
// Querying community content
const events = await nostr.query([{
kinds: [1],
'#t': ['farming'],
limit: 20
}], { signal });
```
### Kind Ranges
An event's kind number determines the event's behavior and storage characteristics:
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
### Content Field Design Principles
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
#### Guidelines
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
- **Empty content is valid**: Many events need only tags with `content: ""`
- **Relays only index tags**: If you need to filter by a field, it must be a tag
#### Example
**✅ Good - queryable data in tags:**
```json
{
"kind": 30402,
"content": "",
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
}
```
**❌ Bad - structured data in content:**
```json
{
"kind": 30402,
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
"tags": [["d", "product-123"]]
}
```
### NIP.md
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
### The `useNostr` Hook
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
```typescript
import { useNostr } from '@nostrify/react';
function useCustomHook() {
const { nostr } = useNostr();
// ...
}
```
### Query Nostr Data with `useNostr` and Tanstack Query
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
```typescript
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/query';
function usePosts() {
const { nostr } = useNostr();
return useQuery({
queryKey: ['posts'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
return events; // these events could be transformed into another format
},
});
}
```
#### Efficient Query Design
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
**✅ Efficient - Single query with multiple kinds:**
```typescript
// Query multiple event types in one request
const events = await nostr.query([
{
kinds: [1, 6, 16], // All repost kinds in one query
'#e': [eventId],
limit: 150,
}
], { signal });
// Separate by type in JavaScript
const notes = events.filter((e) => e.kind === 1);
const reposts = events.filter((e) => e.kind === 6);
const genericReposts = events.filter((e) => e.kind === 16);
```
**❌ Inefficient - Multiple separate queries:**
```typescript
// This creates unnecessary load and can trigger rate limiting
const [notes, reposts, genericReposts] = await Promise.all([
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
]);
```
**Query Optimization Guidelines:**
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
3. **Adjust limits**: When combining queries, increase the limit appropriately
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
#### Event Validation
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
```typescript
// Example validator function for NIP-52 calendar events
function validateCalendarEvent(event: NostrEvent): boolean {
// Check if it's a calendar event kind
if (![31922, 31923].includes(event.kind)) return false;
// Check for required tags according to NIP-52
const d = event.tags.find(([name]) => name === 'd')?.[1];
const title = event.tags.find(([name]) => name === 'title')?.[1];
const start = event.tags.find(([name]) => name === 'start')?.[1];
// All calendar events require 'd', 'title', and 'start' tags
if (!d || !title || !start) return false;
// Additional validation for date-based events (kind 31922)
if (event.kind === 31922) {
// start tag should be in YYYY-MM-DD format for date-based events
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
if (!dateRegex.test(start)) return false;
}
// Additional validation for time-based events (kind 31923)
if (event.kind === 31923) {
// start tag should be a unix timestamp for time-based events
const timestamp = parseInt(start);
if (isNaN(timestamp) || timestamp <= 0) return false;
}
return true;
}
function useCalendarEvents() {
const { nostr } = useNostr();
return useQuery({
queryKey: ['calendar-events'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
// Filter events through validator to ensure they meet NIP-52 requirements
return events.filter(validateCalendarEvent);
},
});
}
```
### The `useAuthor` Hook
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
```tsx
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
function Post({ event }: { event: NostrEvent }) {
const author = useAuthor(event.pubkey);
const metadata: NostrMetadata | undefined = author.data?.metadata;
const displayName = metadata?.name ?? genUserName(event.pubkey);
const profileImage = metadata?.picture;
// ...render elements with this data
}
```
#### `NostrMetadata` type
```ts
/** Kind 0 metadata. */
interface NostrMetadata {
/** A short description of the user. */
about?: string;
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
banner?: string;
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
bot?: boolean;
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
display_name?: string;
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
lud06?: string;
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
lud16?: string;
/** A short name to be displayed for the user. */
name?: string;
/** An email-like Nostr address according to NIP-05. */
nip05?: string;
/** A URL to the user's avatar. */
picture?: string;
/** A web URL related in any way to the event author. */
website?: string;
}
```
### The `useNostrPublish` Hook
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
```tsx
import { useState } from 'react';
import { useCurrentUser } from "@/hooks/useCurrentUser";
import { useNostrPublish } from '@/hooks/useNostrPublish';
export function MyComponent() {
const [ data, setData] = useState<Record<string, string>>({});
const { user } = useCurrentUser();
const { mutate: createEvent } = useNostrPublish();
const handleSubmit = () => {
createEvent({ kind: 1, content: data.content });
};
if (!user) {
return <span>You must be logged in to use this form.</span>;
}
return (
<form onSubmit={handleSubmit} disabled={!user}>
{/* ...some input fields */}
</form>
);
}
```
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
### Nostr Login
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
```tsx
import { LoginArea } from "@/components/auth/LoginArea";
function MyComponent() {
return (
<div>
{/* other components ... */}
<LoginArea className="max-w-60" />
</div>
);
}
```
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
### `npub`, `naddr`, and other Nostr addresses
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
- `nrelay1`: **relay references** - Relay URLs (deprecated)
#### Key Differences Between Similar Identifiers
**`note1` vs `nevent1`:**
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
- Use `note1` for simple references to text notes and threads
- Use `nevent1` when you need to include relay hints or author context for any event type
**`npub1` vs `nprofile1`:**
- `npub1`: Contains only the public key (32 bytes)
- `nprofile1`: Contains public key plus optional relay hints and petname
- Use `npub1` for simple user references
- Use `nprofile1` when you need to include relay hints or display name context
#### NIP-19 Routing Implementation
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
**How it works:**
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
- `note1`: Note section with placeholder for kind:1 text note view
- `nevent1`: Event section with placeholder for any event type view
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
**Example URLs that work automatically:**
- `/npub1abc123...` - User profile (needs implementation)
- `/note1def456...` - Kind:1 text note (needs implementation)
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
- `/naddr1jkl012...` - Addressable event (needs implementation)
**Features included:**
- Basic NIP-19 identifier decoding and routing
- Type-specific sections for different identifier types
- Error handling for invalid identifiers
- Responsive container structure
- Comments indicating where to implement specific views
**Error handling:**
- Invalid NIP-19 format → 404 NotFound
- Unsupported identifier types (like `nsec1`) → 404 NotFound
- Empty or missing identifiers → 404 NotFound
To implement NIP-19 routing in your Nostr application:
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
2. **The route is already configured** in `AppRouter.tsx`
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
4. **Add specific components** for profile views, event displays, etc. as needed
#### Event Type Distinctions
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
- The event is not a kind:1 text note
- You need to include relay hints for better discoverability
- You want to include author context
#### Use in Filters
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
```ts
// ❌ Wrong: naddr is not decoded
const events = await nostr.query(
[{ ids: [naddr] }],
{ signal }
);
```
Corrected example:
```ts
// Import nip19 from nostr-tools
import { nip19 } from 'nostr-tools';
// Decode a NIP-19 identifier
const decoded = nip19.decode(value);
// Optional: guard certain types (depending on the use-case)
if (decoded.type !== 'naddr') {
throw new Error('Unsupported Nostr identifier');
}
// Get the addr object
const naddr = decoded.data;
// ✅ Correct: naddr is expanded into the correct filter
const events = await nostr.query(
[{
kinds: [naddr.kind],
authors: [naddr.pubkey],
'#d': [naddr.identifier],
}],
{ signal }
);
```
#### Implementation Guidelines
1. **Always decode NIP-19 identifiers** before using them in queries
2. **Use the appropriate identifier type** based on your needs:
- Use `note1` for kind:1 text notes specifically
- Use `nevent1` when including relay hints or for non-kind:1 events
- Use `naddr1` for addressable events (always includes author pubkey for security)
3. **Handle different identifier types** appropriately:
- `npub1`/`nprofile1`: Display user profiles
- `note1`: Display kind:1 text notes specifically
- `nevent1`: Display any event with optional relay context
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
### Nostr Edit Profile
To include an Edit Profile form, place the `EditProfileForm` component in the project:
```tsx
import { EditProfileForm } from "@/components/EditProfileForm";
function EditProfilePage() {
return (
<div>
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
<EditProfileForm />
</div>
);
}
```
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
### Uploading Files on Nostr
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
```tsx
import { useUploadFile } from "@/hooks/useUploadFile";
function MyComponent() {
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const handleUpload = async (file: File) => {
try {
// Provides an array of NIP-94 compatible tags
// The first tag in the array contains the URL
const [[_, url]] = await uploadFile(file);
// ...use the url
} catch (error) {
// ...handle errors
}
};
// ...rest of component
}
```
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
### Nostr Encryption and Decryption
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
```ts
// Get the current user
const { user } = useCurrentUser();
// Optional guard to check that nip44 is available
if (!user.signer.nip44) {
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
}
// Encrypt message to self
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
// Decrypt message to self
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
```
### Rendering Rich Text Content
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
```tsx
import { NoteContent } from "@/components/NoteContent";
export function Post(/* ...props */) {
// ...
return (
<CardContent className="pb-2">
<div className="whitespace-pre-wrap break-words">
<NoteContent event={post} className="text-sm" />
</div>
</CardContent>
);
}
```
### Adding Comments Sections
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
#### Basic Usage
```tsx
import { CommentsSection } from "@/components/comments/CommentsSection";
function ArticlePage({ article }: { article: NostrEvent }) {
return (
<div className="space-y-6">
{/* Your article content */}
<div>{/* article content */}</div>
{/* Comments section */}
<CommentsSection root={article} />
</div>
);
}
```
#### Props and Customization
The `CommentsSection` component accepts the following props:
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
- **`title`**: Custom title for the comments section (default: "Comments")
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
- **`className`**: Additional CSS classes for styling
- **`limit`**: Maximum number of comments to load (default: 500)
```tsx
<CommentsSection
root={event}
title="Discussion"
emptyStateMessage="Start the conversation"
emptyStateSubtitle="Share your thoughts about this post"
className="mt-8"
limit={100}
/>
```
#### Commenting on URLs
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
```tsx
<CommentsSection
root={new URL("https://example.com/article")}
title="Comments on this article"
/>
```
## App Configuration
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
```typescript
const defaultConfig: AppConfig = {
theme: "light",
relayUrl: "wss://relay.nostr.band",
};
```
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
## Routing
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
1. Create your page component in `/src/pages/`
2. Import it in `AppRouter.tsx`
3. Add the route above the catch-all `*` route:
```tsx
<Route path="/your-path" element={<YourComponent />} />
```
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
## Development Practices
- Uses React Query for data fetching and caching
- Follows shadcn/ui component patterns
- Implements Path Aliases with `@/` prefix for cleaner imports
- Uses Vite for fast development and production builds
- Component-based architecture with React hooks
- Default connection to one Nostr relay for best performance
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
- **Never use the `any` type**: Always use proper TypeScript types for type safety
## Loading States
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
```tsx
// Skeleton example matching component structure
<Card>
<CardHeader>
<div className="flex items-center space-x-3">
<Skeleton className="h-10 w-10 rounded-full" />
<div className="space-y-1">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-3 w-16" />
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
</div>
</CardContent>
</Card>
```
### Empty States and No Content Found
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
```tsx
import { RelaySelector } from '@/components/RelaySelector';
import { Card, CardContent } from '@/components/ui/card';
// Empty state example
<div className="col-span-full">
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<p className="text-muted-foreground">
No results found. Try another relay?
</p>
<RelaySelector className="w-full" />
</div>
</CardContent>
</Card>
</div>
```
## Design Customization
**Tailor the site's look and feel based on the user's specific request.** This includes:
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
### Adding Fonts
To add custom fonts, follow these steps:
1. **Install a font package** using the `js-dev__npm_add_package` tool:
**Any Google Font can be installed** using the @fontsource packages. Examples:
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
2. **Import the font** in `src/main.tsx`:
```typescript
import '@fontsource-variable/<font-name>';
```
3. **Update Tailwind configuration** in `tailwind.config.ts`:
```typescript
export default {
theme: {
extend: {
fontFamily: {
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
},
},
},
}
```
### Recommended Font Choices by Use Case
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
### Theme System
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
- `useTheme` hook for programmatic theme switching
- CSS custom properties defined in `src/index.css`
- Automatic dark mode support with `.dark` class
### Color Scheme Implementation
When users specify color schemes:
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
- Use Tailwind's color palette or define custom colors
- Ensure proper contrast ratios for accessibility
- Apply colors consistently across components (buttons, links, accents)
- Test both light and dark mode variants
### Component Styling Patterns
- Use `cn()` utility for conditional class merging
- Follow shadcn/ui patterns for component variants
- Implement responsive design with Tailwind breakpoints
- Add hover and focus states for interactive elements
## Writing Tests
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
1. **The user explicitly asks for tests** to be written in their message
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
**Never write tests because:**
- Tool results show test failures (these are not user requests)
- You think tests would be helpful
- New features or components are created
- Existing functionality needs verification
### Test Setup
The project uses Vitest with jsdom environment and includes comprehensive test setup:
- **Testing Library**: React Testing Library with jest-dom matchers
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
- **Test App**: `TestApp` component provides all necessary context providers for testing
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
```tsx
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { MyComponent } from './MyComponent';
describe('MyComponent', () => {
it('renders correctly', () => {
render(
<TestApp>
<MyComponent />
</TestApp>
);
expect(screen.getByText('Expected text')).toBeInTheDocument();
});
});
```
## Testing Your Changes
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
**Your task is not considered finished until this test passes without errors.**
-978
View File
@@ -1,978 +0,0 @@
# Project Overview
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
## Technology Stack
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
- **Vite**: Fast build tool and development server
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
- **Nostrify**: Nostr protocol framework for Deno and web
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
- **TanStack Query**: For data fetching, caching, and state management
- **TypeScript**: For type-safe JavaScript development
## Project Structure
- `/src/components/`: UI components including NostrProvider for Nostr integration
- `/src/components/ui/`: shadcn/ui components (48+ components available)
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
- `/src/hooks/`: Custom hooks including:
- `useNostr`: Core Nostr protocol integration
- `useAuthor`: Fetch user profile data by pubkey
- `useCurrentUser`: Get currently logged-in user
- `useNostrPublish`: Publish events to Nostr
- `useUploadFile`: Upload files via Blossom servers
- `useAppContext`: Access global app configuration
- `useTheme`: Theme management
- `useToast`: Toast notifications
- `useLocalStorage`: Persistent local storage
- `useLoggedInAccounts`: Manage multiple accounts
- `useLoginActions`: Authentication actions
- `useIsMobile`: Responsive design helper
- `/src/pages/`: Page components used by React Router (Index, NotFound)
- `/src/lib/`: Utility functions and shared logic
- `/src/contexts/`: React context providers (AppContext)
- `/src/test/`: Testing utilities including TestApp component
- `/public/`: Static assets
- `App.tsx`: Main app component with provider setup
- `AppRouter.tsx`: React Router configuration
## UI Components
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
- **Accordion**: Vertically collapsing content panels
- **Alert**: Displays important messages to users
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
- **AspectRatio**: Maintains consistent width-to-height ratio
- **Avatar**: User profile pictures with fallback support
- **Badge**: Small status descriptors for UI elements
- **Breadcrumb**: Navigation aid showing current location in hierarchy
- **Button**: Customizable button with multiple variants and sizes
- **Calendar**: Date picker component
- **Card**: Container with header, content, and footer sections
- **Carousel**: Slideshow for cycling through elements
- **Chart**: Data visualization component
- **Checkbox**: Selectable input element
- **Collapsible**: Toggle for showing/hiding content
- **Command**: Command palette for keyboard-first interfaces
- **ContextMenu**: Right-click menu component
- **Dialog**: Modal window overlay
- **Drawer**: Side-sliding panel (using vaul)
- **DropdownMenu**: Menu that appears from a trigger element
- **Form**: Form validation and submission handling
- **HoverCard**: Card that appears when hovering over an element
- **InputOTP**: One-time password input field
- **Input**: Text input field
- **Label**: Accessible form labels
- **Menubar**: Horizontal menu with dropdowns
- **NavigationMenu**: Accessible navigation component
- **Pagination**: Controls for navigating between pages
- **Popover**: Floating content triggered by a button
- **Progress**: Progress indicator
- **RadioGroup**: Group of radio inputs
- **Resizable**: Resizable panels and interfaces
- **ScrollArea**: Scrollable container with custom scrollbars
- **Select**: Dropdown selection component
- **Separator**: Visual divider between content
- **Sheet**: Side-anchored dialog component
- **Sidebar**: Navigation sidebar component
- **Skeleton**: Loading placeholder
- **Slider**: Input for selecting a value from a range
- **Sonner**: Toast notification manager
- **Switch**: Toggle switch control
- **Table**: Data table with headers and rows
- **Tabs**: Tabbed interface component
- **Textarea**: Multi-line text input
- **Toast**: Toast notification component
- **ToggleGroup**: Group of toggle buttons
- **Toggle**: Two-state button
- **Tooltip**: Informational text that appears on hover
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
## System Prompt Management
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
1. Edit CONTEXT.md directly
2. The changes take effect in the next session
## "Vibed with MKStack"
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
## Nostr Protocol Integration
This project comes with custom hooks for querying and publishing events on the Nostr network.
### Nostr Implementation Guidelines
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
#### Choosing Between Existing NIPs and Custom Kinds
When implementing features that could use existing NIPs, follow this decision framework:
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
4. **Extension Strategy**: When existing NIPs are close but not perfect:
- Use the existing kind as the base
- Add domain-specific tags for additional metadata
- Document the extensions in `NIP.md`
5. **When to Generate Custom Kinds**:
- No existing NIP covers the core functionality
- The data structure is fundamentally different from existing patterns
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
**Example Decision Process**:
```
Need: Equipment marketplace for farmers
Options:
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
3. Custom kind - Perfect fit but no interoperability
Decision: Use NIP-99 + farming-specific tags for best balance
```
#### Tag Design Principles
When designing tags for Nostr events, follow these principles:
1. **Kind vs Tags Separation**:
- **Kind** = Schema/structure (how the data is organized)
- **Tags** = Semantics/categories (what the data represents)
- Don't create different kinds for the same data structure
2. **Use Single-Letter Tags for Categories**:
- **Relays only index single-letter tags** for efficient querying
- Use `t` tags for categorization, not custom multi-letter tags
- Multiple `t` tags allow items to belong to multiple categories
3. **Relay-Level Filtering**:
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
- Avoid client-side filtering when relay-level filtering is possible
- Consider query patterns when designing tag structure
4. **Tag Examples**:
```json
// ❌ Wrong: Multi-letter tag, not queryable at relay level
["product_type", "electronics"]
// ✅ Correct: Single-letter tag, relay-indexed and queryable
["t", "electronics"]
["t", "smartphone"]
["t", "android"]
```
5. **Querying Best Practices**:
```typescript
// ❌ Inefficient: Get all events, filter in JavaScript
const events = await nostr.query([{ kinds: [30402] }]);
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
// ✅ Efficient: Filter at relay level
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
```
#### `t` Tag Filtering for Community-Specific Content
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
**When to Use:**
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
- ❌ Generic platforms: Twitter clones, general Nostr clients
**Implementation:**
```typescript
// Publishing with community tag
createEvent({
kind: 1,
content: data.content,
tags: [['t', 'farming']]
});
// Querying community content
const events = await nostr.query([{
kinds: [1],
'#t': ['farming'],
limit: 20
}], { signal });
```
### Kind Ranges
An event's kind number determines the event's behavior and storage characteristics:
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
### Content Field Design Principles
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
#### Guidelines
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
- **Empty content is valid**: Many events need only tags with `content: ""`
- **Relays only index tags**: If you need to filter by a field, it must be a tag
#### Example
**✅ Good - queryable data in tags:**
```json
{
"kind": 30402,
"content": "",
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
}
```
**❌ Bad - structured data in content:**
```json
{
"kind": 30402,
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
"tags": [["d", "product-123"]]
}
```
### NIP.md
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
### The `useNostr` Hook
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
```typescript
import { useNostr } from '@nostrify/react';
function useCustomHook() {
const { nostr } = useNostr();
// ...
}
```
### Query Nostr Data with `useNostr` and Tanstack Query
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
```typescript
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/query';
function usePosts() {
const { nostr } = useNostr();
return useQuery({
queryKey: ['posts'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
return events; // these events could be transformed into another format
},
});
}
```
#### Efficient Query Design
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
**✅ Efficient - Single query with multiple kinds:**
```typescript
// Query multiple event types in one request
const events = await nostr.query([
{
kinds: [1, 6, 16], // All repost kinds in one query
'#e': [eventId],
limit: 150,
}
], { signal });
// Separate by type in JavaScript
const notes = events.filter((e) => e.kind === 1);
const reposts = events.filter((e) => e.kind === 6);
const genericReposts = events.filter((e) => e.kind === 16);
```
**❌ Inefficient - Multiple separate queries:**
```typescript
// This creates unnecessary load and can trigger rate limiting
const [notes, reposts, genericReposts] = await Promise.all([
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
]);
```
**Query Optimization Guidelines:**
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
3. **Adjust limits**: When combining queries, increase the limit appropriately
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
#### Event Validation
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
```typescript
// Example validator function for NIP-52 calendar events
function validateCalendarEvent(event: NostrEvent): boolean {
// Check if it's a calendar event kind
if (![31922, 31923].includes(event.kind)) return false;
// Check for required tags according to NIP-52
const d = event.tags.find(([name]) => name === 'd')?.[1];
const title = event.tags.find(([name]) => name === 'title')?.[1];
const start = event.tags.find(([name]) => name === 'start')?.[1];
// All calendar events require 'd', 'title', and 'start' tags
if (!d || !title || !start) return false;
// Additional validation for date-based events (kind 31922)
if (event.kind === 31922) {
// start tag should be in YYYY-MM-DD format for date-based events
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
if (!dateRegex.test(start)) return false;
}
// Additional validation for time-based events (kind 31923)
if (event.kind === 31923) {
// start tag should be a unix timestamp for time-based events
const timestamp = parseInt(start);
if (isNaN(timestamp) || timestamp <= 0) return false;
}
return true;
}
function useCalendarEvents() {
const { nostr } = useNostr();
return useQuery({
queryKey: ['calendar-events'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
// Filter events through validator to ensure they meet NIP-52 requirements
return events.filter(validateCalendarEvent);
},
});
}
```
### The `useAuthor` Hook
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
```tsx
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
function Post({ event }: { event: NostrEvent }) {
const author = useAuthor(event.pubkey);
const metadata: NostrMetadata | undefined = author.data?.metadata;
const displayName = metadata?.name ?? genUserName(event.pubkey);
const profileImage = metadata?.picture;
// ...render elements with this data
}
```
#### `NostrMetadata` type
```ts
/** Kind 0 metadata. */
interface NostrMetadata {
/** A short description of the user. */
about?: string;
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
banner?: string;
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
bot?: boolean;
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
display_name?: string;
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
lud06?: string;
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
lud16?: string;
/** A short name to be displayed for the user. */
name?: string;
/** An email-like Nostr address according to NIP-05. */
nip05?: string;
/** A URL to the user's avatar. */
picture?: string;
/** A web URL related in any way to the event author. */
website?: string;
}
```
### The `useNostrPublish` Hook
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
```tsx
import { useState } from 'react';
import { useCurrentUser } from "@/hooks/useCurrentUser";
import { useNostrPublish } from '@/hooks/useNostrPublish';
export function MyComponent() {
const [ data, setData] = useState<Record<string, string>>({});
const { user } = useCurrentUser();
const { mutate: createEvent } = useNostrPublish();
const handleSubmit = () => {
createEvent({ kind: 1, content: data.content });
};
if (!user) {
return <span>You must be logged in to use this form.</span>;
}
return (
<form onSubmit={handleSubmit} disabled={!user}>
{/* ...some input fields */}
</form>
);
}
```
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
### Nostr Login
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
```tsx
import { LoginArea } from "@/components/auth/LoginArea";
function MyComponent() {
return (
<div>
{/* other components ... */}
<LoginArea className="max-w-60" />
</div>
);
}
```
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
### `npub`, `naddr`, and other Nostr addresses
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
- `nrelay1`: **relay references** - Relay URLs (deprecated)
#### Key Differences Between Similar Identifiers
**`note1` vs `nevent1`:**
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
- Use `note1` for simple references to text notes and threads
- Use `nevent1` when you need to include relay hints or author context for any event type
**`npub1` vs `nprofile1`:**
- `npub1`: Contains only the public key (32 bytes)
- `nprofile1`: Contains public key plus optional relay hints and petname
- Use `npub1` for simple user references
- Use `nprofile1` when you need to include relay hints or display name context
#### NIP-19 Routing Implementation
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
**How it works:**
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
- `note1`: Note section with placeholder for kind:1 text note view
- `nevent1`: Event section with placeholder for any event type view
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
**Example URLs that work automatically:**
- `/npub1abc123...` - User profile (needs implementation)
- `/note1def456...` - Kind:1 text note (needs implementation)
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
- `/naddr1jkl012...` - Addressable event (needs implementation)
**Features included:**
- Basic NIP-19 identifier decoding and routing
- Type-specific sections for different identifier types
- Error handling for invalid identifiers
- Responsive container structure
- Comments indicating where to implement specific views
**Error handling:**
- Invalid NIP-19 format → 404 NotFound
- Unsupported identifier types (like `nsec1`) → 404 NotFound
- Empty or missing identifiers → 404 NotFound
To implement NIP-19 routing in your Nostr application:
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
2. **The route is already configured** in `AppRouter.tsx`
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
4. **Add specific components** for profile views, event displays, etc. as needed
#### Event Type Distinctions
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
- The event is not a kind:1 text note
- You need to include relay hints for better discoverability
- You want to include author context
#### Use in Filters
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
```ts
// ❌ Wrong: naddr is not decoded
const events = await nostr.query(
[{ ids: [naddr] }],
{ signal }
);
```
Corrected example:
```ts
// Import nip19 from nostr-tools
import { nip19 } from 'nostr-tools';
// Decode a NIP-19 identifier
const decoded = nip19.decode(value);
// Optional: guard certain types (depending on the use-case)
if (decoded.type !== 'naddr') {
throw new Error('Unsupported Nostr identifier');
}
// Get the addr object
const naddr = decoded.data;
// ✅ Correct: naddr is expanded into the correct filter
const events = await nostr.query(
[{
kinds: [naddr.kind],
authors: [naddr.pubkey],
'#d': [naddr.identifier],
}],
{ signal }
);
```
#### Implementation Guidelines
1. **Always decode NIP-19 identifiers** before using them in queries
2. **Use the appropriate identifier type** based on your needs:
- Use `note1` for kind:1 text notes specifically
- Use `nevent1` when including relay hints or for non-kind:1 events
- Use `naddr1` for addressable events (always includes author pubkey for security)
3. **Handle different identifier types** appropriately:
- `npub1`/`nprofile1`: Display user profiles
- `note1`: Display kind:1 text notes specifically
- `nevent1`: Display any event with optional relay context
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
### Nostr Edit Profile
To include an Edit Profile form, place the `EditProfileForm` component in the project:
```tsx
import { EditProfileForm } from "@/components/EditProfileForm";
function EditProfilePage() {
return (
<div>
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
<EditProfileForm />
</div>
);
}
```
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
### Uploading Files on Nostr
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
```tsx
import { useUploadFile } from "@/hooks/useUploadFile";
function MyComponent() {
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const handleUpload = async (file: File) => {
try {
// Provides an array of NIP-94 compatible tags
// The first tag in the array contains the URL
const [[_, url]] = await uploadFile(file);
// ...use the url
} catch (error) {
// ...handle errors
}
};
// ...rest of component
}
```
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
### Nostr Encryption and Decryption
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
```ts
// Get the current user
const { user } = useCurrentUser();
// Optional guard to check that nip44 is available
if (!user.signer.nip44) {
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
}
// Encrypt message to self
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
// Decrypt message to self
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
```
### Rendering Rich Text Content
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
```tsx
import { NoteContent } from "@/components/NoteContent";
export function Post(/* ...props */) {
// ...
return (
<CardContent className="pb-2">
<div className="whitespace-pre-wrap break-words">
<NoteContent event={post} className="text-sm" />
</div>
</CardContent>
);
}
```
### Adding Comments Sections
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
#### Basic Usage
```tsx
import { CommentsSection } from "@/components/comments/CommentsSection";
function ArticlePage({ article }: { article: NostrEvent }) {
return (
<div className="space-y-6">
{/* Your article content */}
<div>{/* article content */}</div>
{/* Comments section */}
<CommentsSection root={article} />
</div>
);
}
```
#### Props and Customization
The `CommentsSection` component accepts the following props:
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
- **`title`**: Custom title for the comments section (default: "Comments")
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
- **`className`**: Additional CSS classes for styling
- **`limit`**: Maximum number of comments to load (default: 500)
```tsx
<CommentsSection
root={event}
title="Discussion"
emptyStateMessage="Start the conversation"
emptyStateSubtitle="Share your thoughts about this post"
className="mt-8"
limit={100}
/>
```
#### Commenting on URLs
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
```tsx
<CommentsSection
root={new URL("https://example.com/article")}
title="Comments on this article"
/>
```
## App Configuration
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
```typescript
const defaultConfig: AppConfig = {
theme: "light",
relayUrl: "wss://relay.nostr.band",
};
```
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
## Routing
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
1. Create your page component in `/src/pages/`
2. Import it in `AppRouter.tsx`
3. Add the route above the catch-all `*` route:
```tsx
<Route path="/your-path" element={<YourComponent />} />
```
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
## Development Practices
- Uses React Query for data fetching and caching
- Follows shadcn/ui component patterns
- Implements Path Aliases with `@/` prefix for cleaner imports
- Uses Vite for fast development and production builds
- Component-based architecture with React hooks
- Default connection to one Nostr relay for best performance
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
- **Never use the `any` type**: Always use proper TypeScript types for type safety
## Loading States
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
```tsx
// Skeleton example matching component structure
<Card>
<CardHeader>
<div className="flex items-center space-x-3">
<Skeleton className="h-10 w-10 rounded-full" />
<div className="space-y-1">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-3 w-16" />
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
</div>
</CardContent>
</Card>
```
### Empty States and No Content Found
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
```tsx
import { RelaySelector } from '@/components/RelaySelector';
import { Card, CardContent } from '@/components/ui/card';
// Empty state example
<div className="col-span-full">
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<p className="text-muted-foreground">
No results found. Try another relay?
</p>
<RelaySelector className="w-full" />
</div>
</CardContent>
</Card>
</div>
```
## Design Customization
**Tailor the site's look and feel based on the user's specific request.** This includes:
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
### Adding Fonts
To add custom fonts, follow these steps:
1. **Install a font package** using the `js-dev__npm_add_package` tool:
**Any Google Font can be installed** using the @fontsource packages. Examples:
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
2. **Import the font** in `src/main.tsx`:
```typescript
import '@fontsource-variable/<font-name>';
```
3. **Update Tailwind configuration** in `tailwind.config.ts`:
```typescript
export default {
theme: {
extend: {
fontFamily: {
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
},
},
},
}
```
### Recommended Font Choices by Use Case
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
### Theme System
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
- `useTheme` hook for programmatic theme switching
- CSS custom properties defined in `src/index.css`
- Automatic dark mode support with `.dark` class
### Color Scheme Implementation
When users specify color schemes:
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
- Use Tailwind's color palette or define custom colors
- Ensure proper contrast ratios for accessibility
- Apply colors consistently across components (buttons, links, accents)
- Test both light and dark mode variants
### Component Styling Patterns
- Use `cn()` utility for conditional class merging
- Follow shadcn/ui patterns for component variants
- Implement responsive design with Tailwind breakpoints
- Add hover and focus states for interactive elements
## Writing Tests
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
1. **The user explicitly asks for tests** to be written in their message
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
**Never write tests because:**
- Tool results show test failures (these are not user requests)
- You think tests would be helpful
- New features or components are created
- Existing functionality needs verification
### Test Setup
The project uses Vitest with jsdom environment and includes comprehensive test setup:
- **Testing Library**: React Testing Library with jest-dom matchers
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
- **Test App**: `TestApp` component provides all necessary context providers for testing
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
```tsx
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { MyComponent } from './MyComponent';
describe('MyComponent', () => {
it('renders correctly', () => {
render(
<TestApp>
<MyComponent />
</TestApp>
);
expect(screen.getByText('Expected text')).toBeInTheDocument();
});
});
```
## Testing Your Changes
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
**Your task is not considered finished until this test passes without errors.**
-978
View File
@@ -1,978 +0,0 @@
# Project Overview
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
## Technology Stack
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
- **Vite**: Fast build tool and development server
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
- **Nostrify**: Nostr protocol framework for Deno and web
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
- **TanStack Query**: For data fetching, caching, and state management
- **TypeScript**: For type-safe JavaScript development
## Project Structure
- `/src/components/`: UI components including NostrProvider for Nostr integration
- `/src/components/ui/`: shadcn/ui components (48+ components available)
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
- `/src/hooks/`: Custom hooks including:
- `useNostr`: Core Nostr protocol integration
- `useAuthor`: Fetch user profile data by pubkey
- `useCurrentUser`: Get currently logged-in user
- `useNostrPublish`: Publish events to Nostr
- `useUploadFile`: Upload files via Blossom servers
- `useAppContext`: Access global app configuration
- `useTheme`: Theme management
- `useToast`: Toast notifications
- `useLocalStorage`: Persistent local storage
- `useLoggedInAccounts`: Manage multiple accounts
- `useLoginActions`: Authentication actions
- `useIsMobile`: Responsive design helper
- `/src/pages/`: Page components used by React Router (Index, NotFound)
- `/src/lib/`: Utility functions and shared logic
- `/src/contexts/`: React context providers (AppContext)
- `/src/test/`: Testing utilities including TestApp component
- `/public/`: Static assets
- `App.tsx`: Main app component with provider setup
- `AppRouter.tsx`: React Router configuration
## UI Components
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
- **Accordion**: Vertically collapsing content panels
- **Alert**: Displays important messages to users
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
- **AspectRatio**: Maintains consistent width-to-height ratio
- **Avatar**: User profile pictures with fallback support
- **Badge**: Small status descriptors for UI elements
- **Breadcrumb**: Navigation aid showing current location in hierarchy
- **Button**: Customizable button with multiple variants and sizes
- **Calendar**: Date picker component
- **Card**: Container with header, content, and footer sections
- **Carousel**: Slideshow for cycling through elements
- **Chart**: Data visualization component
- **Checkbox**: Selectable input element
- **Collapsible**: Toggle for showing/hiding content
- **Command**: Command palette for keyboard-first interfaces
- **ContextMenu**: Right-click menu component
- **Dialog**: Modal window overlay
- **Drawer**: Side-sliding panel (using vaul)
- **DropdownMenu**: Menu that appears from a trigger element
- **Form**: Form validation and submission handling
- **HoverCard**: Card that appears when hovering over an element
- **InputOTP**: One-time password input field
- **Input**: Text input field
- **Label**: Accessible form labels
- **Menubar**: Horizontal menu with dropdowns
- **NavigationMenu**: Accessible navigation component
- **Pagination**: Controls for navigating between pages
- **Popover**: Floating content triggered by a button
- **Progress**: Progress indicator
- **RadioGroup**: Group of radio inputs
- **Resizable**: Resizable panels and interfaces
- **ScrollArea**: Scrollable container with custom scrollbars
- **Select**: Dropdown selection component
- **Separator**: Visual divider between content
- **Sheet**: Side-anchored dialog component
- **Sidebar**: Navigation sidebar component
- **Skeleton**: Loading placeholder
- **Slider**: Input for selecting a value from a range
- **Sonner**: Toast notification manager
- **Switch**: Toggle switch control
- **Table**: Data table with headers and rows
- **Tabs**: Tabbed interface component
- **Textarea**: Multi-line text input
- **Toast**: Toast notification component
- **ToggleGroup**: Group of toggle buttons
- **Toggle**: Two-state button
- **Tooltip**: Informational text that appears on hover
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
## System Prompt Management
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
1. Edit CONTEXT.md directly
2. The changes take effect in the next session
## "Vibed with MKStack"
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
## Nostr Protocol Integration
This project comes with custom hooks for querying and publishing events on the Nostr network.
### Nostr Implementation Guidelines
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
#### Choosing Between Existing NIPs and Custom Kinds
When implementing features that could use existing NIPs, follow this decision framework:
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
4. **Extension Strategy**: When existing NIPs are close but not perfect:
- Use the existing kind as the base
- Add domain-specific tags for additional metadata
- Document the extensions in `NIP.md`
5. **When to Generate Custom Kinds**:
- No existing NIP covers the core functionality
- The data structure is fundamentally different from existing patterns
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
**Example Decision Process**:
```
Need: Equipment marketplace for farmers
Options:
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
3. Custom kind - Perfect fit but no interoperability
Decision: Use NIP-99 + farming-specific tags for best balance
```
#### Tag Design Principles
When designing tags for Nostr events, follow these principles:
1. **Kind vs Tags Separation**:
- **Kind** = Schema/structure (how the data is organized)
- **Tags** = Semantics/categories (what the data represents)
- Don't create different kinds for the same data structure
2. **Use Single-Letter Tags for Categories**:
- **Relays only index single-letter tags** for efficient querying
- Use `t` tags for categorization, not custom multi-letter tags
- Multiple `t` tags allow items to belong to multiple categories
3. **Relay-Level Filtering**:
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
- Avoid client-side filtering when relay-level filtering is possible
- Consider query patterns when designing tag structure
4. **Tag Examples**:
```json
// ❌ Wrong: Multi-letter tag, not queryable at relay level
["product_type", "electronics"]
// ✅ Correct: Single-letter tag, relay-indexed and queryable
["t", "electronics"]
["t", "smartphone"]
["t", "android"]
```
5. **Querying Best Practices**:
```typescript
// ❌ Inefficient: Get all events, filter in JavaScript
const events = await nostr.query([{ kinds: [30402] }]);
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
// ✅ Efficient: Filter at relay level
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
```
#### `t` Tag Filtering for Community-Specific Content
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
**When to Use:**
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
- ❌ Generic platforms: Twitter clones, general Nostr clients
**Implementation:**
```typescript
// Publishing with community tag
createEvent({
kind: 1,
content: data.content,
tags: [['t', 'farming']]
});
// Querying community content
const events = await nostr.query([{
kinds: [1],
'#t': ['farming'],
limit: 20
}], { signal });
```
### Kind Ranges
An event's kind number determines the event's behavior and storage characteristics:
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
### Content Field Design Principles
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
#### Guidelines
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
- **Empty content is valid**: Many events need only tags with `content: ""`
- **Relays only index tags**: If you need to filter by a field, it must be a tag
#### Example
**✅ Good - queryable data in tags:**
```json
{
"kind": 30402,
"content": "",
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
}
```
**❌ Bad - structured data in content:**
```json
{
"kind": 30402,
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
"tags": [["d", "product-123"]]
}
```
### NIP.md
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
### The `useNostr` Hook
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
```typescript
import { useNostr } from '@nostrify/react';
function useCustomHook() {
const { nostr } = useNostr();
// ...
}
```
### Query Nostr Data with `useNostr` and Tanstack Query
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
```typescript
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/query';
function usePosts() {
const { nostr } = useNostr();
return useQuery({
queryKey: ['posts'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
return events; // these events could be transformed into another format
},
});
}
```
#### Efficient Query Design
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
**✅ Efficient - Single query with multiple kinds:**
```typescript
// Query multiple event types in one request
const events = await nostr.query([
{
kinds: [1, 6, 16], // All repost kinds in one query
'#e': [eventId],
limit: 150,
}
], { signal });
// Separate by type in JavaScript
const notes = events.filter((e) => e.kind === 1);
const reposts = events.filter((e) => e.kind === 6);
const genericReposts = events.filter((e) => e.kind === 16);
```
**❌ Inefficient - Multiple separate queries:**
```typescript
// This creates unnecessary load and can trigger rate limiting
const [notes, reposts, genericReposts] = await Promise.all([
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
]);
```
**Query Optimization Guidelines:**
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
3. **Adjust limits**: When combining queries, increase the limit appropriately
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
#### Event Validation
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
```typescript
// Example validator function for NIP-52 calendar events
function validateCalendarEvent(event: NostrEvent): boolean {
// Check if it's a calendar event kind
if (![31922, 31923].includes(event.kind)) return false;
// Check for required tags according to NIP-52
const d = event.tags.find(([name]) => name === 'd')?.[1];
const title = event.tags.find(([name]) => name === 'title')?.[1];
const start = event.tags.find(([name]) => name === 'start')?.[1];
// All calendar events require 'd', 'title', and 'start' tags
if (!d || !title || !start) return false;
// Additional validation for date-based events (kind 31922)
if (event.kind === 31922) {
// start tag should be in YYYY-MM-DD format for date-based events
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
if (!dateRegex.test(start)) return false;
}
// Additional validation for time-based events (kind 31923)
if (event.kind === 31923) {
// start tag should be a unix timestamp for time-based events
const timestamp = parseInt(start);
if (isNaN(timestamp) || timestamp <= 0) return false;
}
return true;
}
function useCalendarEvents() {
const { nostr } = useNostr();
return useQuery({
queryKey: ['calendar-events'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
// Filter events through validator to ensure they meet NIP-52 requirements
return events.filter(validateCalendarEvent);
},
});
}
```
### The `useAuthor` Hook
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
```tsx
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
function Post({ event }: { event: NostrEvent }) {
const author = useAuthor(event.pubkey);
const metadata: NostrMetadata | undefined = author.data?.metadata;
const displayName = metadata?.name ?? genUserName(event.pubkey);
const profileImage = metadata?.picture;
// ...render elements with this data
}
```
#### `NostrMetadata` type
```ts
/** Kind 0 metadata. */
interface NostrMetadata {
/** A short description of the user. */
about?: string;
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
banner?: string;
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
bot?: boolean;
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
display_name?: string;
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
lud06?: string;
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
lud16?: string;
/** A short name to be displayed for the user. */
name?: string;
/** An email-like Nostr address according to NIP-05. */
nip05?: string;
/** A URL to the user's avatar. */
picture?: string;
/** A web URL related in any way to the event author. */
website?: string;
}
```
### The `useNostrPublish` Hook
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
```tsx
import { useState } from 'react';
import { useCurrentUser } from "@/hooks/useCurrentUser";
import { useNostrPublish } from '@/hooks/useNostrPublish';
export function MyComponent() {
const [ data, setData] = useState<Record<string, string>>({});
const { user } = useCurrentUser();
const { mutate: createEvent } = useNostrPublish();
const handleSubmit = () => {
createEvent({ kind: 1, content: data.content });
};
if (!user) {
return <span>You must be logged in to use this form.</span>;
}
return (
<form onSubmit={handleSubmit} disabled={!user}>
{/* ...some input fields */}
</form>
);
}
```
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
### Nostr Login
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
```tsx
import { LoginArea } from "@/components/auth/LoginArea";
function MyComponent() {
return (
<div>
{/* other components ... */}
<LoginArea className="max-w-60" />
</div>
);
}
```
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
### `npub`, `naddr`, and other Nostr addresses
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
- `nrelay1`: **relay references** - Relay URLs (deprecated)
#### Key Differences Between Similar Identifiers
**`note1` vs `nevent1`:**
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
- Use `note1` for simple references to text notes and threads
- Use `nevent1` when you need to include relay hints or author context for any event type
**`npub1` vs `nprofile1`:**
- `npub1`: Contains only the public key (32 bytes)
- `nprofile1`: Contains public key plus optional relay hints and petname
- Use `npub1` for simple user references
- Use `nprofile1` when you need to include relay hints or display name context
#### NIP-19 Routing Implementation
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
**How it works:**
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
- `note1`: Note section with placeholder for kind:1 text note view
- `nevent1`: Event section with placeholder for any event type view
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
**Example URLs that work automatically:**
- `/npub1abc123...` - User profile (needs implementation)
- `/note1def456...` - Kind:1 text note (needs implementation)
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
- `/naddr1jkl012...` - Addressable event (needs implementation)
**Features included:**
- Basic NIP-19 identifier decoding and routing
- Type-specific sections for different identifier types
- Error handling for invalid identifiers
- Responsive container structure
- Comments indicating where to implement specific views
**Error handling:**
- Invalid NIP-19 format → 404 NotFound
- Unsupported identifier types (like `nsec1`) → 404 NotFound
- Empty or missing identifiers → 404 NotFound
To implement NIP-19 routing in your Nostr application:
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
2. **The route is already configured** in `AppRouter.tsx`
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
4. **Add specific components** for profile views, event displays, etc. as needed
#### Event Type Distinctions
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
- The event is not a kind:1 text note
- You need to include relay hints for better discoverability
- You want to include author context
#### Use in Filters
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
```ts
// ❌ Wrong: naddr is not decoded
const events = await nostr.query(
[{ ids: [naddr] }],
{ signal }
);
```
Corrected example:
```ts
// Import nip19 from nostr-tools
import { nip19 } from 'nostr-tools';
// Decode a NIP-19 identifier
const decoded = nip19.decode(value);
// Optional: guard certain types (depending on the use-case)
if (decoded.type !== 'naddr') {
throw new Error('Unsupported Nostr identifier');
}
// Get the addr object
const naddr = decoded.data;
// ✅ Correct: naddr is expanded into the correct filter
const events = await nostr.query(
[{
kinds: [naddr.kind],
authors: [naddr.pubkey],
'#d': [naddr.identifier],
}],
{ signal }
);
```
#### Implementation Guidelines
1. **Always decode NIP-19 identifiers** before using them in queries
2. **Use the appropriate identifier type** based on your needs:
- Use `note1` for kind:1 text notes specifically
- Use `nevent1` when including relay hints or for non-kind:1 events
- Use `naddr1` for addressable events (always includes author pubkey for security)
3. **Handle different identifier types** appropriately:
- `npub1`/`nprofile1`: Display user profiles
- `note1`: Display kind:1 text notes specifically
- `nevent1`: Display any event with optional relay context
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
### Nostr Edit Profile
To include an Edit Profile form, place the `EditProfileForm` component in the project:
```tsx
import { EditProfileForm } from "@/components/EditProfileForm";
function EditProfilePage() {
return (
<div>
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
<EditProfileForm />
</div>
);
}
```
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
### Uploading Files on Nostr
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
```tsx
import { useUploadFile } from "@/hooks/useUploadFile";
function MyComponent() {
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const handleUpload = async (file: File) => {
try {
// Provides an array of NIP-94 compatible tags
// The first tag in the array contains the URL
const [[_, url]] = await uploadFile(file);
// ...use the url
} catch (error) {
// ...handle errors
}
};
// ...rest of component
}
```
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
### Nostr Encryption and Decryption
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
```ts
// Get the current user
const { user } = useCurrentUser();
// Optional guard to check that nip44 is available
if (!user.signer.nip44) {
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
}
// Encrypt message to self
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
// Decrypt message to self
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
```
### Rendering Rich Text Content
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
```tsx
import { NoteContent } from "@/components/NoteContent";
export function Post(/* ...props */) {
// ...
return (
<CardContent className="pb-2">
<div className="whitespace-pre-wrap break-words">
<NoteContent event={post} className="text-sm" />
</div>
</CardContent>
);
}
```
### Adding Comments Sections
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
#### Basic Usage
```tsx
import { CommentsSection } from "@/components/comments/CommentsSection";
function ArticlePage({ article }: { article: NostrEvent }) {
return (
<div className="space-y-6">
{/* Your article content */}
<div>{/* article content */}</div>
{/* Comments section */}
<CommentsSection root={article} />
</div>
);
}
```
#### Props and Customization
The `CommentsSection` component accepts the following props:
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
- **`title`**: Custom title for the comments section (default: "Comments")
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
- **`className`**: Additional CSS classes for styling
- **`limit`**: Maximum number of comments to load (default: 500)
```tsx
<CommentsSection
root={event}
title="Discussion"
emptyStateMessage="Start the conversation"
emptyStateSubtitle="Share your thoughts about this post"
className="mt-8"
limit={100}
/>
```
#### Commenting on URLs
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
```tsx
<CommentsSection
root={new URL("https://example.com/article")}
title="Comments on this article"
/>
```
## App Configuration
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
```typescript
const defaultConfig: AppConfig = {
theme: "light",
relayUrl: "wss://relay.nostr.band",
};
```
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
## Routing
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
1. Create your page component in `/src/pages/`
2. Import it in `AppRouter.tsx`
3. Add the route above the catch-all `*` route:
```tsx
<Route path="/your-path" element={<YourComponent />} />
```
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
## Development Practices
- Uses React Query for data fetching and caching
- Follows shadcn/ui component patterns
- Implements Path Aliases with `@/` prefix for cleaner imports
- Uses Vite for fast development and production builds
- Component-based architecture with React hooks
- Default connection to one Nostr relay for best performance
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
- **Never use the `any` type**: Always use proper TypeScript types for type safety
## Loading States
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
```tsx
// Skeleton example matching component structure
<Card>
<CardHeader>
<div className="flex items-center space-x-3">
<Skeleton className="h-10 w-10 rounded-full" />
<div className="space-y-1">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-3 w-16" />
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
</div>
</CardContent>
</Card>
```
### Empty States and No Content Found
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
```tsx
import { RelaySelector } from '@/components/RelaySelector';
import { Card, CardContent } from '@/components/ui/card';
// Empty state example
<div className="col-span-full">
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<p className="text-muted-foreground">
No results found. Try another relay?
</p>
<RelaySelector className="w-full" />
</div>
</CardContent>
</Card>
</div>
```
## Design Customization
**Tailor the site's look and feel based on the user's specific request.** This includes:
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
### Adding Fonts
To add custom fonts, follow these steps:
1. **Install a font package** using the `js-dev__npm_add_package` tool:
**Any Google Font can be installed** using the @fontsource packages. Examples:
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
2. **Import the font** in `src/main.tsx`:
```typescript
import '@fontsource-variable/<font-name>';
```
3. **Update Tailwind configuration** in `tailwind.config.ts`:
```typescript
export default {
theme: {
extend: {
fontFamily: {
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
},
},
},
}
```
### Recommended Font Choices by Use Case
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
### Theme System
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
- `useTheme` hook for programmatic theme switching
- CSS custom properties defined in `src/index.css`
- Automatic dark mode support with `.dark` class
### Color Scheme Implementation
When users specify color schemes:
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
- Use Tailwind's color palette or define custom colors
- Ensure proper contrast ratios for accessibility
- Apply colors consistently across components (buttons, links, accents)
- Test both light and dark mode variants
### Component Styling Patterns
- Use `cn()` utility for conditional class merging
- Follow shadcn/ui patterns for component variants
- Implement responsive design with Tailwind breakpoints
- Add hover and focus states for interactive elements
## Writing Tests
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
1. **The user explicitly asks for tests** to be written in their message
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
**Never write tests because:**
- Tool results show test failures (these are not user requests)
- You think tests would be helpful
- New features or components are created
- Existing functionality needs verification
### Test Setup
The project uses Vitest with jsdom environment and includes comprehensive test setup:
- **Testing Library**: React Testing Library with jest-dom matchers
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
- **Test App**: `TestApp` component provides all necessary context providers for testing
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
```tsx
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { MyComponent } from './MyComponent';
describe('MyComponent', () => {
it('renders correctly', () => {
render(
<TestApp>
<MyComponent />
</TestApp>
);
expect(screen.getByText('Expected text')).toBeInTheDocument();
});
});
```
## Testing Your Changes
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
**Your task is not considered finished until this test passes without errors.**
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+31 -5
View File
@@ -5,7 +5,8 @@ Shakespeare is an AI chat application that allows users to build custom Nostr we
## Features
- **AI-Powered Development**: Chat with an AI assistant to build your Nostr website
- **Project Management**: Create and manage multiple projects in a Google Drive-like interface
- **File Attachments**: Attach files directly to chat messages with structured text parts, visual badges, and deduplication. Supports both file selection and clipboard image pasting
- **Project Management**: Create and manage multiple projects with sidebar navigation
- **Real-time Editing**: Edit files directly in the browser with syntax highlighting
- **File Explorer**: Browse and manage your project files
- **Project Preview**: Preview your website as you build it
@@ -15,8 +16,9 @@ Shakespeare is an AI chat application that allows users to build custom Nostr we
1. **Create a Project**: Enter a description of what you want to build in the prompt textarea
2. **Chat with AI**: Use the AI assistant to add features, edit files, and build your website
3. **Edit Code**: Switch to the code view to manually edit files if needed
4. **Preview**: View your website in the preview pane
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
@@ -41,11 +43,36 @@ The AI assistant can:
## Usage
1. **Homepage**: Create new projects and view existing ones
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:
@@ -54,6 +81,5 @@ Built with:
- Vite
- TailwindCSS
- shadcn/ui
- Vercel AI SDK
- LightningFS for filesystem
- isomorphic-git for template cloning
-11
View File
@@ -1,11 +0,0 @@
Please create Shakespeare, an AI chat application that allows users to build custom Nostr websites. On the landing page would be a prompt textarea. Upon entering a prompt, a template would be cloned with `isomorphic-git`. That template's clone URL is hardcoded to `https://relay.ngit.dev/npub1q3sle0kvfsehgsuexttt3ugjd8xdklxfwwkh559wxckmzddywnws6cd26p/mkstack.git`. A unique directory name would also be generated from the prompt since the user would be able to work on multiple projects within this app.
For the filesystem, use LightningFS (`@isomorphic-git/lightning-fs` on npm). Note that `isomorphic-git` requires a `Buffer` polyfill to work. isomorphic-git's http client should be added by using `import http from "isomorphic-git/http/web"` (not `fetch`).
After projects have been created, they'll show up in a grid on the homepage, below the prompt textarea, in a grid design similar to Google Drive. Clicking them navigates to the project view. Creating a project through the homepage prompt also redirects to its project view.
In the project view, there is a chat in the left pane, and a project preview in the right. Initially the project preview will be empty, because the site won't have been built yet. The project needs to be built with Vite (directly in the browser) and displayed in an iframe, but we'll figure that out later. Just include a placeholder for it in the UI for now.
In the project chat pane, the user is able to chat with an AI assistant. The assistant will have tools that allow it to work on the project, including editing files and running the Vite build (again, just a stub). In the right preview pane, the user would also be able to switch to a "Code" view, which would display the list of files in the project.
For the AI implementation, use Vercel's ai-sdk (`ai` on npm). It should use the openai provider (`@ai-sdk/openai` on npm) and include a tool set for working on the project.
-16
View File
@@ -1,16 +0,0 @@
{
"model": "claude-sonnet-4",
"temperature": 0.2,
"mcpServers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@nostrbook/mcp@latest"]
}
}
}
-978
View File
@@ -1,978 +0,0 @@
# Project Overview
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
## Technology Stack
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
- **Vite**: Fast build tool and development server
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
- **Nostrify**: Nostr protocol framework for Deno and web
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
- **TanStack Query**: For data fetching, caching, and state management
- **TypeScript**: For type-safe JavaScript development
## Project Structure
- `/src/components/`: UI components including NostrProvider for Nostr integration
- `/src/components/ui/`: shadcn/ui components (48+ components available)
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
- `/src/hooks/`: Custom hooks including:
- `useNostr`: Core Nostr protocol integration
- `useAuthor`: Fetch user profile data by pubkey
- `useCurrentUser`: Get currently logged-in user
- `useNostrPublish`: Publish events to Nostr
- `useUploadFile`: Upload files via Blossom servers
- `useAppContext`: Access global app configuration
- `useTheme`: Theme management
- `useToast`: Toast notifications
- `useLocalStorage`: Persistent local storage
- `useLoggedInAccounts`: Manage multiple accounts
- `useLoginActions`: Authentication actions
- `useIsMobile`: Responsive design helper
- `/src/pages/`: Page components used by React Router (Index, NotFound)
- `/src/lib/`: Utility functions and shared logic
- `/src/contexts/`: React context providers (AppContext)
- `/src/test/`: Testing utilities including TestApp component
- `/public/`: Static assets
- `App.tsx`: Main app component with provider setup
- `AppRouter.tsx`: React Router configuration
## UI Components
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
- **Accordion**: Vertically collapsing content panels
- **Alert**: Displays important messages to users
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
- **AspectRatio**: Maintains consistent width-to-height ratio
- **Avatar**: User profile pictures with fallback support
- **Badge**: Small status descriptors for UI elements
- **Breadcrumb**: Navigation aid showing current location in hierarchy
- **Button**: Customizable button with multiple variants and sizes
- **Calendar**: Date picker component
- **Card**: Container with header, content, and footer sections
- **Carousel**: Slideshow for cycling through elements
- **Chart**: Data visualization component
- **Checkbox**: Selectable input element
- **Collapsible**: Toggle for showing/hiding content
- **Command**: Command palette for keyboard-first interfaces
- **ContextMenu**: Right-click menu component
- **Dialog**: Modal window overlay
- **Drawer**: Side-sliding panel (using vaul)
- **DropdownMenu**: Menu that appears from a trigger element
- **Form**: Form validation and submission handling
- **HoverCard**: Card that appears when hovering over an element
- **InputOTP**: One-time password input field
- **Input**: Text input field
- **Label**: Accessible form labels
- **Menubar**: Horizontal menu with dropdowns
- **NavigationMenu**: Accessible navigation component
- **Pagination**: Controls for navigating between pages
- **Popover**: Floating content triggered by a button
- **Progress**: Progress indicator
- **RadioGroup**: Group of radio inputs
- **Resizable**: Resizable panels and interfaces
- **ScrollArea**: Scrollable container with custom scrollbars
- **Select**: Dropdown selection component
- **Separator**: Visual divider between content
- **Sheet**: Side-anchored dialog component
- **Sidebar**: Navigation sidebar component
- **Skeleton**: Loading placeholder
- **Slider**: Input for selecting a value from a range
- **Sonner**: Toast notification manager
- **Switch**: Toggle switch control
- **Table**: Data table with headers and rows
- **Tabs**: Tabbed interface component
- **Textarea**: Multi-line text input
- **Toast**: Toast notification component
- **ToggleGroup**: Group of toggle buttons
- **Toggle**: Two-state button
- **Tooltip**: Informational text that appears on hover
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
## System Prompt Management
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
1. Edit CONTEXT.md directly
2. The changes take effect in the next session
## "Vibed with MKStack"
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
## Nostr Protocol Integration
This project comes with custom hooks for querying and publishing events on the Nostr network.
### Nostr Implementation Guidelines
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
#### Choosing Between Existing NIPs and Custom Kinds
When implementing features that could use existing NIPs, follow this decision framework:
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
4. **Extension Strategy**: When existing NIPs are close but not perfect:
- Use the existing kind as the base
- Add domain-specific tags for additional metadata
- Document the extensions in `NIP.md`
5. **When to Generate Custom Kinds**:
- No existing NIP covers the core functionality
- The data structure is fundamentally different from existing patterns
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
**Example Decision Process**:
```
Need: Equipment marketplace for farmers
Options:
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
3. Custom kind - Perfect fit but no interoperability
Decision: Use NIP-99 + farming-specific tags for best balance
```
#### Tag Design Principles
When designing tags for Nostr events, follow these principles:
1. **Kind vs Tags Separation**:
- **Kind** = Schema/structure (how the data is organized)
- **Tags** = Semantics/categories (what the data represents)
- Don't create different kinds for the same data structure
2. **Use Single-Letter Tags for Categories**:
- **Relays only index single-letter tags** for efficient querying
- Use `t` tags for categorization, not custom multi-letter tags
- Multiple `t` tags allow items to belong to multiple categories
3. **Relay-Level Filtering**:
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
- Avoid client-side filtering when relay-level filtering is possible
- Consider query patterns when designing tag structure
4. **Tag Examples**:
```json
// ❌ Wrong: Multi-letter tag, not queryable at relay level
["product_type", "electronics"]
// ✅ Correct: Single-letter tag, relay-indexed and queryable
["t", "electronics"]
["t", "smartphone"]
["t", "android"]
```
5. **Querying Best Practices**:
```typescript
// ❌ Inefficient: Get all events, filter in JavaScript
const events = await nostr.query([{ kinds: [30402] }]);
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
// ✅ Efficient: Filter at relay level
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
```
#### `t` Tag Filtering for Community-Specific Content
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
**When to Use:**
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
- ❌ Generic platforms: Twitter clones, general Nostr clients
**Implementation:**
```typescript
// Publishing with community tag
createEvent({
kind: 1,
content: data.content,
tags: [['t', 'farming']]
});
// Querying community content
const events = await nostr.query([{
kinds: [1],
'#t': ['farming'],
limit: 20
}], { signal });
```
### Kind Ranges
An event's kind number determines the event's behavior and storage characteristics:
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
### Content Field Design Principles
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
#### Guidelines
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
- **Empty content is valid**: Many events need only tags with `content: ""`
- **Relays only index tags**: If you need to filter by a field, it must be a tag
#### Example
**✅ Good - queryable data in tags:**
```json
{
"kind": 30402,
"content": "",
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
}
```
**❌ Bad - structured data in content:**
```json
{
"kind": 30402,
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
"tags": [["d", "product-123"]]
}
```
### NIP.md
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
### The `useNostr` Hook
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
```typescript
import { useNostr } from '@nostrify/react';
function useCustomHook() {
const { nostr } = useNostr();
// ...
}
```
### Query Nostr Data with `useNostr` and Tanstack Query
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
```typescript
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/query';
function usePosts() {
const { nostr } = useNostr();
return useQuery({
queryKey: ['posts'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
return events; // these events could be transformed into another format
},
});
}
```
#### Efficient Query Design
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
**✅ Efficient - Single query with multiple kinds:**
```typescript
// Query multiple event types in one request
const events = await nostr.query([
{
kinds: [1, 6, 16], // All repost kinds in one query
'#e': [eventId],
limit: 150,
}
], { signal });
// Separate by type in JavaScript
const notes = events.filter((e) => e.kind === 1);
const reposts = events.filter((e) => e.kind === 6);
const genericReposts = events.filter((e) => e.kind === 16);
```
**❌ Inefficient - Multiple separate queries:**
```typescript
// This creates unnecessary load and can trigger rate limiting
const [notes, reposts, genericReposts] = await Promise.all([
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
]);
```
**Query Optimization Guidelines:**
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
3. **Adjust limits**: When combining queries, increase the limit appropriately
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
#### Event Validation
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
```typescript
// Example validator function for NIP-52 calendar events
function validateCalendarEvent(event: NostrEvent): boolean {
// Check if it's a calendar event kind
if (![31922, 31923].includes(event.kind)) return false;
// Check for required tags according to NIP-52
const d = event.tags.find(([name]) => name === 'd')?.[1];
const title = event.tags.find(([name]) => name === 'title')?.[1];
const start = event.tags.find(([name]) => name === 'start')?.[1];
// All calendar events require 'd', 'title', and 'start' tags
if (!d || !title || !start) return false;
// Additional validation for date-based events (kind 31922)
if (event.kind === 31922) {
// start tag should be in YYYY-MM-DD format for date-based events
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
if (!dateRegex.test(start)) return false;
}
// Additional validation for time-based events (kind 31923)
if (event.kind === 31923) {
// start tag should be a unix timestamp for time-based events
const timestamp = parseInt(start);
if (isNaN(timestamp) || timestamp <= 0) return false;
}
return true;
}
function useCalendarEvents() {
const { nostr } = useNostr();
return useQuery({
queryKey: ['calendar-events'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
// Filter events through validator to ensure they meet NIP-52 requirements
return events.filter(validateCalendarEvent);
},
});
}
```
### The `useAuthor` Hook
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
```tsx
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
function Post({ event }: { event: NostrEvent }) {
const author = useAuthor(event.pubkey);
const metadata: NostrMetadata | undefined = author.data?.metadata;
const displayName = metadata?.name ?? genUserName(event.pubkey);
const profileImage = metadata?.picture;
// ...render elements with this data
}
```
#### `NostrMetadata` type
```ts
/** Kind 0 metadata. */
interface NostrMetadata {
/** A short description of the user. */
about?: string;
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
banner?: string;
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
bot?: boolean;
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
display_name?: string;
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
lud06?: string;
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
lud16?: string;
/** A short name to be displayed for the user. */
name?: string;
/** An email-like Nostr address according to NIP-05. */
nip05?: string;
/** A URL to the user's avatar. */
picture?: string;
/** A web URL related in any way to the event author. */
website?: string;
}
```
### The `useNostrPublish` Hook
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
```tsx
import { useState } from 'react';
import { useCurrentUser } from "@/hooks/useCurrentUser";
import { useNostrPublish } from '@/hooks/useNostrPublish';
export function MyComponent() {
const [ data, setData] = useState<Record<string, string>>({});
const { user } = useCurrentUser();
const { mutate: createEvent } = useNostrPublish();
const handleSubmit = () => {
createEvent({ kind: 1, content: data.content });
};
if (!user) {
return <span>You must be logged in to use this form.</span>;
}
return (
<form onSubmit={handleSubmit} disabled={!user}>
{/* ...some input fields */}
</form>
);
}
```
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
### Nostr Login
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
```tsx
import { LoginArea } from "@/components/auth/LoginArea";
function MyComponent() {
return (
<div>
{/* other components ... */}
<LoginArea className="max-w-60" />
</div>
);
}
```
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
### `npub`, `naddr`, and other Nostr addresses
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
- `nrelay1`: **relay references** - Relay URLs (deprecated)
#### Key Differences Between Similar Identifiers
**`note1` vs `nevent1`:**
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
- Use `note1` for simple references to text notes and threads
- Use `nevent1` when you need to include relay hints or author context for any event type
**`npub1` vs `nprofile1`:**
- `npub1`: Contains only the public key (32 bytes)
- `nprofile1`: Contains public key plus optional relay hints and petname
- Use `npub1` for simple user references
- Use `nprofile1` when you need to include relay hints or display name context
#### NIP-19 Routing Implementation
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
**How it works:**
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
- `note1`: Note section with placeholder for kind:1 text note view
- `nevent1`: Event section with placeholder for any event type view
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
**Example URLs that work automatically:**
- `/npub1abc123...` - User profile (needs implementation)
- `/note1def456...` - Kind:1 text note (needs implementation)
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
- `/naddr1jkl012...` - Addressable event (needs implementation)
**Features included:**
- Basic NIP-19 identifier decoding and routing
- Type-specific sections for different identifier types
- Error handling for invalid identifiers
- Responsive container structure
- Comments indicating where to implement specific views
**Error handling:**
- Invalid NIP-19 format → 404 NotFound
- Unsupported identifier types (like `nsec1`) → 404 NotFound
- Empty or missing identifiers → 404 NotFound
To implement NIP-19 routing in your Nostr application:
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
2. **The route is already configured** in `AppRouter.tsx`
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
4. **Add specific components** for profile views, event displays, etc. as needed
#### Event Type Distinctions
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
- The event is not a kind:1 text note
- You need to include relay hints for better discoverability
- You want to include author context
#### Use in Filters
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
```ts
// ❌ Wrong: naddr is not decoded
const events = await nostr.query(
[{ ids: [naddr] }],
{ signal }
);
```
Corrected example:
```ts
// Import nip19 from nostr-tools
import { nip19 } from 'nostr-tools';
// Decode a NIP-19 identifier
const decoded = nip19.decode(value);
// Optional: guard certain types (depending on the use-case)
if (decoded.type !== 'naddr') {
throw new Error('Unsupported Nostr identifier');
}
// Get the addr object
const naddr = decoded.data;
// ✅ Correct: naddr is expanded into the correct filter
const events = await nostr.query(
[{
kinds: [naddr.kind],
authors: [naddr.pubkey],
'#d': [naddr.identifier],
}],
{ signal }
);
```
#### Implementation Guidelines
1. **Always decode NIP-19 identifiers** before using them in queries
2. **Use the appropriate identifier type** based on your needs:
- Use `note1` for kind:1 text notes specifically
- Use `nevent1` when including relay hints or for non-kind:1 events
- Use `naddr1` for addressable events (always includes author pubkey for security)
3. **Handle different identifier types** appropriately:
- `npub1`/`nprofile1`: Display user profiles
- `note1`: Display kind:1 text notes specifically
- `nevent1`: Display any event with optional relay context
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
### Nostr Edit Profile
To include an Edit Profile form, place the `EditProfileForm` component in the project:
```tsx
import { EditProfileForm } from "@/components/EditProfileForm";
function EditProfilePage() {
return (
<div>
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
<EditProfileForm />
</div>
);
}
```
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
### Uploading Files on Nostr
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
```tsx
import { useUploadFile } from "@/hooks/useUploadFile";
function MyComponent() {
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const handleUpload = async (file: File) => {
try {
// Provides an array of NIP-94 compatible tags
// The first tag in the array contains the URL
const [[_, url]] = await uploadFile(file);
// ...use the url
} catch (error) {
// ...handle errors
}
};
// ...rest of component
}
```
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
### Nostr Encryption and Decryption
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
```ts
// Get the current user
const { user } = useCurrentUser();
// Optional guard to check that nip44 is available
if (!user.signer.nip44) {
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
}
// Encrypt message to self
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
// Decrypt message to self
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
```
### Rendering Rich Text Content
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
```tsx
import { NoteContent } from "@/components/NoteContent";
export function Post(/* ...props */) {
// ...
return (
<CardContent className="pb-2">
<div className="whitespace-pre-wrap break-words">
<NoteContent event={post} className="text-sm" />
</div>
</CardContent>
);
}
```
### Adding Comments Sections
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
#### Basic Usage
```tsx
import { CommentsSection } from "@/components/comments/CommentsSection";
function ArticlePage({ article }: { article: NostrEvent }) {
return (
<div className="space-y-6">
{/* Your article content */}
<div>{/* article content */}</div>
{/* Comments section */}
<CommentsSection root={article} />
</div>
);
}
```
#### Props and Customization
The `CommentsSection` component accepts the following props:
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
- **`title`**: Custom title for the comments section (default: "Comments")
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
- **`className`**: Additional CSS classes for styling
- **`limit`**: Maximum number of comments to load (default: 500)
```tsx
<CommentsSection
root={event}
title="Discussion"
emptyStateMessage="Start the conversation"
emptyStateSubtitle="Share your thoughts about this post"
className="mt-8"
limit={100}
/>
```
#### Commenting on URLs
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
```tsx
<CommentsSection
root={new URL("https://example.com/article")}
title="Comments on this article"
/>
```
## App Configuration
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
```typescript
const defaultConfig: AppConfig = {
theme: "light",
relayUrl: "wss://relay.nostr.band",
};
```
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
## Routing
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
1. Create your page component in `/src/pages/`
2. Import it in `AppRouter.tsx`
3. Add the route above the catch-all `*` route:
```tsx
<Route path="/your-path" element={<YourComponent />} />
```
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
## Development Practices
- Uses React Query for data fetching and caching
- Follows shadcn/ui component patterns
- Implements Path Aliases with `@/` prefix for cleaner imports
- Uses Vite for fast development and production builds
- Component-based architecture with React hooks
- Default connection to one Nostr relay for best performance
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
- **Never use the `any` type**: Always use proper TypeScript types for type safety
## Loading States
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
```tsx
// Skeleton example matching component structure
<Card>
<CardHeader>
<div className="flex items-center space-x-3">
<Skeleton className="h-10 w-10 rounded-full" />
<div className="space-y-1">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-3 w-16" />
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
</div>
</CardContent>
</Card>
```
### Empty States and No Content Found
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
```tsx
import { RelaySelector } from '@/components/RelaySelector';
import { Card, CardContent } from '@/components/ui/card';
// Empty state example
<div className="col-span-full">
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<p className="text-muted-foreground">
No results found. Try another relay?
</p>
<RelaySelector className="w-full" />
</div>
</CardContent>
</Card>
</div>
```
## Design Customization
**Tailor the site's look and feel based on the user's specific request.** This includes:
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
### Adding Fonts
To add custom fonts, follow these steps:
1. **Install a font package** using the `js-dev__npm_add_package` tool:
**Any Google Font can be installed** using the @fontsource packages. Examples:
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
2. **Import the font** in `src/main.tsx`:
```typescript
import '@fontsource-variable/<font-name>';
```
3. **Update Tailwind configuration** in `tailwind.config.ts`:
```typescript
export default {
theme: {
extend: {
fontFamily: {
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
},
},
},
}
```
### Recommended Font Choices by Use Case
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
### Theme System
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
- `useTheme` hook for programmatic theme switching
- CSS custom properties defined in `src/index.css`
- Automatic dark mode support with `.dark` class
### Color Scheme Implementation
When users specify color schemes:
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
- Use Tailwind's color palette or define custom colors
- Ensure proper contrast ratios for accessibility
- Apply colors consistently across components (buttons, links, accents)
- Test both light and dark mode variants
### Component Styling Patterns
- Use `cn()` utility for conditional class merging
- Follow shadcn/ui patterns for component variants
- Implement responsive design with Tailwind breakpoints
- Add hover and focus states for interactive elements
## Writing Tests
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
1. **The user explicitly asks for tests** to be written in their message
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
**Never write tests because:**
- Tool results show test failures (these are not user requests)
- You think tests would be helpful
- New features or components are created
- Existing functionality needs verification
### Test Setup
The project uses Vitest with jsdom environment and includes comprehensive test setup:
- **Testing Library**: React Testing Library with jest-dom matchers
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
- **Test App**: `TestApp` component provides all necessary context providers for testing
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
```tsx
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { MyComponent } from './MyComponent';
describe('MyComponent', () => {
it('renders correctly', () => {
render(
<TestApp>
<MyComponent />
</TestApp>
);
expect(screen.getByText('Expected text')).toBeInTheDocument();
});
});
```
## Testing Your Changes
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
**Your task is not considered finished until this test passes without errors.**
+8 -8
View File
@@ -1,5 +1,5 @@
import fs from 'fs';
import path from 'path';
import fs from 'node:fs';
import path from 'node:path';
export default {
meta: {
@@ -19,7 +19,7 @@ export default {
create(context) {
const filename = context.getFilename();
// Only run this rule on HTML files
if (!filename.endsWith('.html')) {
return {};
@@ -29,11 +29,11 @@ export default {
Program(node) {
const sourceCode = context.getSourceCode();
const htmlContent = sourceCode.getText();
// Check for manifest link tag in HTML
const manifestLinkRegex = /<link[^>]*rel=["']manifest["'][^>]*>/i;
const manifestMatch = htmlContent.match(manifestLinkRegex);
if (!manifestMatch) {
context.report({
node,
@@ -53,11 +53,11 @@ export default {
}
const manifestPath = hrefMatch[1];
// Resolve the manifest file path relative to the project root
const htmlDir = path.dirname(filename);
let resolvedManifestPath;
if (manifestPath.startsWith('/')) {
// Absolute path - check in public directory first, then project root
const publicPath = path.resolve(htmlDir, 'public' + manifestPath);
@@ -67,7 +67,7 @@ export default {
// Relative path
resolvedManifestPath = path.resolve(htmlDir, manifestPath);
}
// Check if the manifest file exists
if (!fs.existsSync(resolvedManifestPath)) {
context.report({
+1
View File
@@ -27,6 +27,7 @@ export default tseslint.config(
},
rules: {
...reactHooks.configs.recommended.rules,
"react-hooks/exhaustive-deps": "error",
"react-refresh/only-export-components": [
"warn",
{ allowConstantExport: true },
+135 -26
View File
@@ -41,7 +41,7 @@ All messages follow JSON-RPC 2.0 specification:
{
"jsonrpc": "2.0",
"method": "fetch",
"params": {
"params": {
"request": {
"url": "https://app123.example.com/assets/main.js",
"method": "GET",
@@ -54,6 +54,23 @@ All messages follow JSON-RPC 2.0 specification:
"id": 123
}
// POST Request with JSON body
{
"jsonrpc": "2.0",
"method": "fetch",
"params": {
"request": {
"url": "https://app123.example.com/api/data",
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"body": "eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9" // base64 encoded: {"name":"John","age":30}
}
},
"id": 124
}
// Success Response
{
"jsonrpc": "2.0",
@@ -64,7 +81,7 @@ All messages follow JSON-RPC 2.0 specification:
"Content-Type": "application/javascript",
"Cache-Control": "no-cache"
},
"body": "console.log('hello');"
"body": "Y29uc29sZS5sb2coJ2hlbGxvJyk7" // base64 encoded: console.log('hello');
},
"id": 123
}
@@ -94,14 +111,14 @@ full request body support
- `url` (string): Full URL of the request
- `method` (string): HTTP method (GET, POST, etc.)
- `headers` (object): Request headers as key-value pairs
- `body` (string|null): Request body as string, or null if no body
- `body` (string|null): Request body as base64 encoded string, or null if no body
**Result:**
- `status` (number): HTTP status code (200, 404, etc.)
- `statusText` (string): HTTP status text ("OK", "Not Found", etc.)
- `headers` (object): Response headers as key-value pairs
- `body` (string|null): Response body content (null if status is 204)
- `body` (string|null): Response body content as base64 encoded string (null if status is 204)
**Error Codes:**
@@ -117,19 +134,61 @@ full request body support
- File uploads (as base64 strings)
- Any HTTP method with body content
Request bodies are serialized as strings, so binary data should be
base64-encoded.
Request bodies must be base64-encoded strings when not null. This ensures
consistent handling of both text and binary data across the messaging protocol.
### `console`
**Purpose:** Forward console messages from iframe to parent for display
**Parameters:**
- `level` (string): Log level - "log", "warn", "error", "info", "debug"
- `message` (string): The log message
**Result:** None (notification only, no response expected)
### Navigation Methods
#### `navigate`
**Purpose:** Navigate iframe to a new URL within the same origin
**Parameters:** `url` (string) - Target URL (must be same origin)
**Result:** None (notification only)
#### `refresh`
**Purpose:** Refresh/reload the current page in the iframe
**Parameters:** None
**Result:** None (notification only)
#### `goBack`
**Purpose:** Navigate back in the iframe's history
**Parameters:** None
**Result:** None (notification only)
#### `goForward`
**Purpose:** Navigate forward in the iframe's history
**Parameters:** None
**Result:** None (notification only)
#### `updateNavigationState`
**Purpose:** Update parent about iframe's current navigation state
**Parameters:**
- `currentUrl` (string) - Current URL of the iframe
- `canGoBack` (boolean) - Whether iframe can go back in history
- `canGoForward` (boolean) - Whether iframe can go forward in history
**Result:** None (notification only)
## Implementation
### Parent Page
In this example, the parent page acts as a static file server.
The parent page acts as a static file server and console log collector:
```javascript
class FetchClientParent {
constructor(files) {
this.files = files; // Map of path -> {content, contentType}
this.consoleLogs = []; // Store console messages
this.setupMessageListener();
}
@@ -139,12 +198,43 @@ class FetchClientParent {
if (event.origin !== "https://app123.example.com") return;
const message = event.data;
// Handle fetch requests
if (message.jsonrpc === "2.0" && message.method === "fetch") {
this.handleFetch(message);
}
// Handle console messages
if (message.jsonrpc === "2.0" && message.method === "console") {
this.handleConsoleMessage(message);
}
});
}
handleConsoleMessage(message) {
const { params } = message;
const { level, message: logMessage } = params;
// Store the log message
this.consoleLogs.push({
level,
message: logMessage,
timestamp: Date.now(),
id: Date.now()
});
// Update UI to show new logs
this.updateConsoleUI();
// Also log to parent's console for debugging
console[level](`[IFRAME] ${logMessage}`);
}
updateConsoleUI() {
// Implementation depends on your UI framework
console.log(`Total console logs: ${this.consoleLogs.length}`);
}
handleFetch(request) {
const { params, id } = request;
const { request: fetchRequest } = params;
@@ -166,11 +256,10 @@ class FetchClientParent {
"Content-Type": file.contentType,
"Cache-Control": "no-cache",
},
body: file.content,
body: btoa(file.content),
},
});
} else {
// Return 404 response (not a JSON-RPC error)
this.sendResponse({
id,
jsonrpc: "2.0",
@@ -180,7 +269,7 @@ class FetchClientParent {
headers: {
"Content-Type": "text/plain",
},
body: `File not found: ${path}`,
body: btoa(`File not found: ${path}`),
},
});
}
@@ -190,22 +279,15 @@ class FetchClientParent {
const iframe = document.getElementById("preview-iframe");
iframe.contentWindow.postMessage(message, "https://app123.example.com");
}
sendError(message) {
const iframe = document.getElementById("preview-iframe");
iframe.contentWindow.postMessage(message, "https://app123.example.com");
}
}
```
### Preview Page
### iframe Client Communication
Below is a simplified RPC client that could be used inside the iframe's main
thread to test functionality of the parent. In practice, requests originate from
the ServiceWorker and the main thread acts as a relay, so multiple steps of
communication are involved.
The iframe client uses a simplified JSON-RPC client for communication. In the actual implementation, the ServiceWorker makes requests and the main thread acts as a relay:
```javascript
// Simplified JSON-RPC client (actual implementation in _iframe-client/main.js)
class JSONRPCClient {
constructor() {
this.requestId = 0;
@@ -216,7 +298,7 @@ class JSONRPCClient {
setupMessageListener() {
window.addEventListener("message", (event) => {
const message = event.data;
if (message.jsonrpc === "2.0" && message.id) {
if (message.jsonrpc === "2.0" && message.id !== undefined) {
this.handleResponse(message);
}
});
@@ -228,7 +310,6 @@ class JSONRPCClient {
return new Promise((resolve, reject) => {
this.pendingRequests.set(id, { resolve, reject });
// Send request to parent
window.parent.postMessage({
jsonrpc: "2.0",
method: "fetch",
@@ -236,7 +317,6 @@ class JSONRPCClient {
id,
}, "*");
// Timeout after 10 seconds
setTimeout(() => {
if (this.pendingRequests.has(id)) {
this.pendingRequests.delete(id);
@@ -255,15 +335,36 @@ class JSONRPCClient {
this.pendingRequests.delete(id);
if (error) {
pending.reject(new Error(error.message));
pending.reject(new Error(`${error.message} (code: ${error.code})`));
} else {
// Result is a serialized response
pending.resolve(result);
}
}
}
```
## Base64 Encoding
All request and response bodies are base64 encoded when not null to ensure proper transmission through JSON-RPC:
- **Consistent Data Handling:** Both text and binary data are handled uniformly
- **JSON Compatibility:** Avoids issues with special characters in JSON messages
- **Binary Data Support:** Enables transmission of images, files, and other binary content
**Encoding/Decoding:**
```javascript
// Encoding text content (parent side)
const encodedBody = btoa(textContent);
// Encoding binary content (ServiceWorker side)
const bytes = new Uint8Array(arrayBuffer);
const encodedBody = btoa(String.fromCharCode(...bytes));
// Decoding (receiver side)
const decodedText = atob(encodedBody);
const decodedBytes = new Uint8Array(atob(encodedBody).split('').map(c => c.charCodeAt(0)));
```
## Security
- **Origin Validation:** Always verify message origin
@@ -287,9 +388,17 @@ class JSONRPCClient {
content: "<!DOCTYPE html><html><body>Hello world!</body></html>",
contentType: "text/html",
}],
["/app.js", {
content: "console.log('App loaded');",
contentType: "application/javascript",
}],
]);
// Example static file server
// Initialize the fetch client parent
new FetchClientParent(files);
</script>
```
## Console Logging Implementation
The iframe client automatically intercepts console messages and forwards them to the parent. The implementation (in `_iframe-client/main.js`) overrides console methods.
+64 -22
View File
@@ -54,30 +54,31 @@ blocked.
```
/
├── index.html # Main iframe client page
├── _iframe-client.js # Main coordination script
├── _iframe-client.css # Styles for the iframe client
├── sw.js # ServiceWorker
├── MESSAGING_PROTOCOL.md # Communication protocol docs
├── example-parent.html # Example parent implementation
└── README.md # This file
├── index.html # Main iframe client page
├── _iframe-client/
│ ├── main.js # Main coordination script
│ └── client.css # Styles for the iframe client
├── sw.js # ServiceWorker
├── MESSAGING_PROTOCOL.md # Communication protocol docs
└── README.md # This file
```
## Simplified JSON-RPC Protocol
The system now uses a drastically simplified JSON-RPC 2.0 protocol with only one
method:
The system now uses a simplified JSON-RPC 2.0 protocol with two methods:
- **`fetch(request)`** - Handle HTTP requests with serialized fetch
request/response
- **`console(level, message)`** - Forward console messages from
iframe to parent for display
**Request:**
```javascript
{
"jsonrpc": "2.0",
"method": "fetch",
"params": {
"method": "fetch",
"params": {
"request": {
"url": "https://app123.example.com/assets/main.js",
"method": "GET",
@@ -106,6 +107,19 @@ method:
}
```
**Console Message:**
```javascript
{
"jsonrpc": "2.0",
"method": "console",
"params": {
"level": "error",
"message": "Failed to load module"
}
}
```
## How It Works
1. **Initialization:**
@@ -122,7 +136,27 @@ method:
- Parent responds with serialized HTTP responses
- ServiceWorker creates Response objects and returns them to the client app
3. **Content Replacement:**
3. **SPA Routing Support:**
- ServiceWorker detects navigation requests (HTML page requests with `mode: "navigate"`)
- For SPA routes like `/about`, `/contact`, etc., the ServiceWorker serves the site's `index.html`
- This allows the SPA's client-side router to handle the route properly
- All other requests (assets, API calls, etc.) are handled normally via JSON-RPC
4. **Semantic Path Navigation:**
- **Key Concept**: iframe stays on base URL (`/`) while communicating semantic paths to parent
- When user navigates to `/about` in address bar, iframe doesn't actually change URL
- Instead, NavigationHandler tracks semantic path (`/about`) and communicates it to parent
- Parent displays semantic path while iframe remains on base URL
- SPA's client-side router handles navigation internally without page reloads
- This prevents 404 errors from literal path navigation
5. **SPA Navigation Tracking:**
- NavigationHandler overrides `history.pushState()` and `history.replaceState()` to detect SPA navigation
- When SPAs change URLs via history methods, NavigationHandler detects the change and sends navigation state to parent
- Navigation state includes semantic path, back/forward capability, and history tracking
- Parent can display current semantic path and enable proper back/forward navigation controls
6. **Content Replacement:**
- Main thread requests `/` from parent via JSON-RPC fetch
- Replaces its own content with the site index
- Site runs normally, with all requests handled by SW via JSON-RPC
@@ -136,8 +170,9 @@ Deploy these files to your iframe client subdomain:
```
https://*.example.com/
├── index.html
├── _iframe-client.js
├── _iframe-client.css
├── _iframe-client/
│ ├── main.js
│ └── client.css
└── sw.js
```
@@ -158,8 +193,7 @@ Include the iframe client in your parent page:
</iframe>
```
Implement the JSON-RPC protocol (see `example-parent.html` for a complete
example):
Implement the JSON-RPC protocol:
```javascript
class FetchClientParent {
@@ -270,9 +304,9 @@ function handleRequest(fetchRequest) {
## Testing
1. Open `example-parent.html` in a browser
2. Click "Load Sample Site"
3. The iframe client should load and display the sample app
1. Create a parent page implementing the JSON-RPC protocol (see example in MESSAGING_PROTOCOL.md)
2. Load the iframe client in an iframe pointing to your deployed client domain
3. The iframe client should load and display the served content
4. Test navigation and functionality within the iframe client
## Browser Support
@@ -308,14 +342,22 @@ function handleRequest(fetchRequest) {
- Check that JSON-RPC messages are properly formatted
- Ensure iframe has appropriate sandbox permissions
### SPA routes don't work
- Ensure the parent page serves the correct `index.html` for the root path `/`
- Check that the SPA's client-side router is properly configured
- Verify that navigation requests are being detected correctly by the ServiceWorker
- Make sure the parent page returns the same `index.html` content for SPA routes as it does for the root path
- **Important**: iframe should stay on base URL (`/`) while semantic paths are communicated to parent. If you see literal path navigation (iframe URL changing to `/about`), this indicates a configuration issue.
## Development
To modify the system:
1. **iframe Client:** Edit `index.html`, `_iframe-client.js`,
`_iframe-client.css`, `sw.js`
1. **iframe Client:** Edit `index.html`, `_iframe-client/main.js`,
`_iframe-client/client.css`, `sw.js`
2. **Protocol:** Update `MESSAGING_PROTOCOL.md` for any changes
3. **Testing:** Use `example-parent.html` for testing changes
3. **Testing:** Create a parent page implementing the JSON-RPC protocol for testing changes
## License
-260
View File
@@ -1,260 +0,0 @@
/**
* iframe Fetch Client Main Script
* JSON-RPC based communication with parent page
*/
class JSONRPCClient {
constructor() {
this.requestId = 0;
this.pendingRequests = new Map();
this.setupMessageListener();
}
setupMessageListener() {
window.addEventListener("message", (event) => {
const message = event.data;
if (message.jsonrpc === "2.0" && message.id !== undefined) {
// Check if this is a response to our own request or a ServiceWorker request
if (this.pendingRequests.has(message.id)) {
this.handleResponse(message);
} else {
// This is a response to a ServiceWorker request, relay it back
this.relayJSONRPCToServiceWorker(message);
}
}
});
}
relayJSONRPCToServiceWorker(response) {
// Forward the JSON-RPC response to ServiceWorker
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage(response);
}
}
async fetch(request) {
const id = ++this.requestId;
return new Promise((resolve, reject) => {
this.pendingRequests.set(id, { resolve, reject });
// Send JSON-RPC request to parent
window.parent.postMessage({
jsonrpc: "2.0",
method: "fetch",
params: { request },
id,
}, "*");
// Timeout after 10 seconds
setTimeout(() => {
if (this.pendingRequests.has(id)) {
this.pendingRequests.delete(id);
reject(new Error(`Timeout fetching: ${request.url}`));
}
}, 10000);
});
}
handleResponse(message) {
const { id, result, error } = message;
const pending = this.pendingRequests.get(id);
if (!pending) return;
this.pendingRequests.delete(id);
if (error) {
pending.reject(new Error(`${error.message} (code: ${error.code})`));
} else {
pending.resolve(result);
}
}
}
class FetchClient {
constructor() {
this.rpcClient = new JSONRPCClient();
this.swReady = false;
this.init();
}
async init() {
try {
await this.registerServiceWorker();
this.setupServiceWorkerCommunication();
await this.waitForServiceWorker();
await this.fetchSiteIndex();
} catch (error) {
this.showError("Failed to initialize fetch client", error);
}
}
async registerServiceWorker() {
if (!("serviceWorker" in navigator)) {
throw new Error("ServiceWorker not supported");
}
// Check if SW is already registered
const existingRegistration = await navigator.serviceWorker
.getRegistration();
if (existingRegistration) {
console.log("ServiceWorker already registered");
this.swReady = true;
return;
}
try {
const registration = await navigator.serviceWorker.register("/sw.js", {
scope: "/",
});
console.log("ServiceWorker registered:", registration);
// Wait for SW to be ready
await navigator.serviceWorker.ready;
this.swReady = true;
// Block future registrations to prevent site from registering its own SW
this.blockFutureRegistrations();
} catch (error) {
throw new Error(`ServiceWorker registration failed: ${error.message}`);
}
}
blockFutureRegistrations() {
navigator.serviceWorker.register = function () {
console.log("Blocked ServiceWorker registration attempt");
return Promise.resolve({
scope: "/",
active: navigator.serviceWorker.controller,
installing: null,
waiting: null,
addEventListener: () => {},
removeEventListener: () => {},
});
};
}
setupServiceWorkerCommunication() {
// Listen for JSON-RPC requests from ServiceWorker and relay them to parent
navigator.serviceWorker.addEventListener("message", async (event) => {
const { data } = event;
// Check if this is a JSON-RPC request from ServiceWorker
if (data.jsonrpc === "2.0" && data.method && data.id !== undefined) {
this.relayJSONRPCToParent(data);
}
});
}
relayJSONRPCToParent(request) {
// Forward the JSON-RPC request directly to parent
window.parent.postMessage(request, "*");
}
async waitForServiceWorker() {
const timeout = 10000; // 10 seconds
const start = Date.now();
while (!this.swReady) {
if (Date.now() - start > timeout) {
throw new Error("Timeout waiting for ServiceWorker readiness");
}
await new Promise((resolve) => setTimeout(resolve, 100));
}
console.log("ServiceWorker is ready");
}
async fetchSiteIndex() {
try {
// Request site index from parent via JSON-RPC fetch
const serializedRequest = {
url: `${location.origin}/`,
method: "GET",
body: null,
headers: {},
};
const response = await this.rpcClient.fetch(serializedRequest);
// Replace current document with the site index content
this.replaceDocument(response.body);
} catch (error) {
this.showError("Failed to load site index", error);
}
}
replaceDocument(htmlContent) {
// Create a new document from the HTML content
const parser = new DOMParser();
const newDoc = parser.parseFromString(htmlContent, "text/html");
const scripts = [];
newDoc.querySelectorAll("script").forEach((script) => {
scripts.push({
src: script.src,
type: script.type,
async: script.hasAttribute("async"),
defer: script.hasAttribute("defer"),
});
script.parentNode.removeChild(script);
});
// Replace the entire document
document.head.innerHTML = newDoc.head.innerHTML;
document.body.innerHTML = newDoc.body.innerHTML;
// Re-add scripts (this is necessary to execute them)
scripts.forEach((script) => {
const newScript = document.createElement("script");
newScript.src = script.src;
newScript.type = script.type;
if (script.async) newScript.async = true;
if (script.defer) newScript.defer = true;
document.body.appendChild(newScript);
});
console.log("Document replaced with site content");
}
showError(message, error) {
console.error(message, error);
document.body.innerHTML = `
<div style="
font-family: system-ui, -apple-system, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
border-left: 4px solid #dc3545;
">
<h2 style="color: #dc3545; margin-top: 0;">Fetch Client Error</h2>
<p><strong>${message}</strong></p>
<p style="color: #6c757d;">${error.message || error}</p>
<details style="margin-top: 20px;">
<summary style="cursor: pointer; color: #007bff;">Technical Details</summary>
<pre style="
background: #f1f3f4;
padding: 10px;
border-radius: 4px;
overflow-x: auto;
font-size: 12px;
margin-top: 10px;
">${error.stack || JSON.stringify(error, null, 2)}</pre>
</details>
</div>
`;
}
}
// Initialize when DOM is ready
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => new FetchClient());
} else {
new FetchClient();
}
+576
View File
@@ -0,0 +1,576 @@
/**
* iframe Fetch Client - Simplified Implementation
* Implements JSON-RPC 2.0 messaging protocol per MESSAGING_PROTOCOL.md
*/
// JSON-RPC Client for communication with parent
class JSONRPCClient {
constructor() {
this.requestId = 0;
this.pendingRequests = new Map();
this.setupMessageListener();
}
setupMessageListener() {
window.addEventListener("message", (event) => {
// Only accept messages from parent window for security
if (event.source !== window.parent) {
return;
}
const message = event.data;
// Check if this is a response to our own request or a ServiceWorker request
if (message.jsonrpc === "2.0" && message.id !== undefined) {
if (this.pendingRequests.has(message.id)) {
this.handleResponse(message);
} else {
// This is a response to a ServiceWorker request, relay it back
this.relayToServiceWorker(message);
}
}
});
}
relayToServiceWorker(response) {
// Forward the JSON-RPC response to ServiceWorker
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage(response);
}
}
async fetch(request) {
const id = ++this.requestId;
return new Promise((resolve, reject) => {
this.pendingRequests.set(id, { resolve, reject });
// Send JSON-RPC request to parent
window.parent.postMessage({
jsonrpc: "2.0",
method: "fetch",
params: { request },
id,
}, "*");
// Timeout after 10 seconds
setTimeout(() => {
if (this.pendingRequests.has(id)) {
this.pendingRequests.delete(id);
reject(new Error(`Timeout fetching: ${request.url}`));
}
}, 10000);
});
}
handleResponse(message) {
const { id, result, error } = message;
const pending = this.pendingRequests.get(id);
if (!pending) return;
this.pendingRequests.delete(id);
if (error) {
pending.reject(new Error(`${error.message} (code: ${error.code})`));
} else {
pending.resolve(result);
}
}
}
// Console Interceptor - forwards console messages to parent
class ConsoleInterceptor {
constructor() {
this.originalConsole = {};
this.methods = ['log', 'warn', 'error', 'info', 'debug'];
this.init();
}
init() {
// Store original methods and override in single pass
this.methods.forEach((method) => {
if (typeof console[method] === 'function') {
this.originalConsole[method] = console[method];
console[method] = (...args) => {
// Call original method
try {
this.originalConsole[method](...args);
} catch (e) {
// Continue if original fails
}
// Send to parent
this.sendConsoleMessage(method, ...args);
};
}
});
}
sendConsoleMessage(level, ...args) {
const message = args.map((arg) => {
if (arg === undefined) return 'undefined';
if (arg === null) return 'null';
if (typeof arg === 'object') {
try {
return JSON.stringify(arg, (key, value) => {
if (value instanceof Error) {
return {
name: value.name,
message: value.message,
stack: value.stack
};
}
return value;
});
} catch {
return String(arg);
}
}
return String(arg);
}).join(' ');
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: { level, message }
}, "*");
} catch (error) {
// Retry once after delay if postMessage fails
setTimeout(() => {
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: { level: "error", message: `[DELAYED] ${message}` }
}, "*");
} catch {
// Give up if retry fails
}
}, 100);
}
}
}
// Navigation Handler - manages iframe navigation and history
class NavigationHandler {
constructor() {
// Get initial path from window property or default to root
this.currentSemanticPath = window.__IFRAME_INITIAL_PATH__ || '/';
this.setupMessageListener();
this.setupHistoryListeners();
this.overrideHistoryMethods();
this.updateNavigationState();
}
// Extract semantic path from URL or string
extractSemanticPath(urlOrString) {
try {
const url = typeof urlOrString === 'string'
? new URL(urlOrString, window.location.origin)
: urlOrString;
return url.pathname + url.search + url.hash;
} catch {
return window.location.pathname + window.location.search + window.location.hash;
}
}
setupMessageListener() {
window.addEventListener("message", (event) => {
// Only accept messages from parent window for security
if (event.source !== window.parent) {
return;
}
const message = event.data;
if (message.jsonrpc === "2.0") {
switch (message.method) {
case "navigate":
this.handleNavigate(message.params.url);
break;
case "refresh":
this.handleRefresh();
break;
case "goBack":
this.handleGoBack();
break;
case "goForward":
this.handleGoForward();
break;
}
}
});
}
setupHistoryListeners() {
// Listen for popstate events (back/forward navigation)
window.addEventListener('popstate', () => {
this.currentSemanticPath = this.extractSemanticPath(window.location);
this.updateNavigationState();
});
// Listen for hash changes
window.addEventListener('hashchange', () => {
this.currentSemanticPath = this.extractSemanticPath(window.location);
this.updateNavigationState();
});
}
overrideHistoryMethods() {
// Override history.pushState and history.replaceState to detect SPA navigation
this.originalPushState = window.history.pushState;
this.originalReplaceState = window.history.replaceState;
window.history.pushState = (...args) => {
const result = this.originalPushState.apply(window.history, args);
// Extract semantic path from URL argument or use current location
const semanticPath = args[2]
? this.extractSemanticPath(args[2])
: this.extractSemanticPath(window.location);
this.currentSemanticPath = semanticPath;
this.updateNavigationState();
return result;
};
window.history.replaceState = (...args) => {
const result = this.originalReplaceState.apply(window.history, args);
const semanticPath = args[2]
? this.extractSemanticPath(args[2])
: this.extractSemanticPath(window.location);
this.currentSemanticPath = semanticPath;
this.updateNavigationState();
return result;
};
}
handleNavigate(url) {
try {
// Validate URL - must be same origin
const targetUrl = new URL(url, window.location.origin);
if (targetUrl.origin !== window.location.origin) {
console.error('Navigation to different origin not allowed:', url);
return;
}
const semanticPath = this.extractSemanticPath(targetUrl);
this.currentSemanticPath = semanticPath;
this.updateNavigationState();
// Trigger SPA navigation
window.history.pushState({}, '', semanticPath);
window.dispatchEvent(new PopStateEvent('popstate', { state: {} }));
} catch (error) {
console.error('Invalid navigation URL:', url, error);
}
}
handleRefresh() {
// Store current semantic path for reload
const currentPath = this.currentSemanticPath || '/';
// Save the current path to sessionStorage so it persists across reload
try {
sessionStorage.setItem('iframe_initial_path', currentPath);
} catch (error) {
console.warn('Failed to store initial path in sessionStorage:', error);
}
// Actually reload the iframe to get a fresh SPA instance
window.location.reload();
}
handleGoBack() {
window.history.back();
}
handleGoForward() {
window.history.forward();
}
updateNavigationState() {
// Use tracked semantic path, fallback to current location if needed
const semanticPath = this.currentSemanticPath || this.extractSemanticPath(window.location);
const state = {
currentUrl: semanticPath,
canGoBack: false, // Let parent handle history tracking
canGoForward: false // Let parent handle history tracking
};
// Send navigation state to parent
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "updateNavigationState",
params: state
}, "*");
} catch (error) {
console.error('Failed to send navigation state:', error);
}
}
}
// Main Fetch Client
class FetchClient {
constructor() {
this.rpcClient = new JSONRPCClient();
this.consoleInterceptor = new ConsoleInterceptor();
this.navigationHandler = new NavigationHandler();
this.init();
}
// Ensure SPA navigates to initial path after document is loaded
ensureInitialNavigation() {
// Wait for the SPA to initialize, then navigate to the initial path
setTimeout(() => {
const initialPath = window.__IFRAME_INITIAL_PATH__;
if (initialPath && initialPath !== '/') {
const currentPath = window.location.pathname + window.location.search + window.location.hash;
// If we're not already at the initial path, navigate there
if (currentPath !== initialPath) {
this.navigationHandler.handleNavigate(initialPath);
}
}
}, 150); // Give SPA more time to initialize
}
async init() {
try {
await this.setupServiceWorker();
await this.loadSiteIndex();
} catch (error) {
console.error("FetchClient: Initialization failed:", error);
this.showError("Failed to initialize fetch client", error);
}
}
async setupServiceWorker() {
if (!("serviceWorker" in navigator)) {
throw new Error("ServiceWorker not supported");
}
// Check if already registered
const existing = await navigator.serviceWorker.getRegistration();
if (existing) {
console.log("ServiceWorker already registered");
this.setupServiceWorkerCommunication();
return;
}
// Register new ServiceWorker
const registration = await navigator.serviceWorker.register("/sw.js", { scope: "/" });
console.log("ServiceWorker registered:", registration);
await navigator.serviceWorker.ready;
this.setupServiceWorkerCommunication();
this.blockFutureRegistrations(); // Block future registrations to prevent site from registering its own SW
}
setupServiceWorkerCommunication() {
// Relay JSON-RPC requests from ServiceWorker to parent
navigator.serviceWorker.addEventListener("message", (event) => {
const { data } = event;
if (data.jsonrpc === "2.0" && data.method && data.id !== undefined) {
window.parent.postMessage(data, "*");
}
});
}
blockFutureRegistrations() {
navigator.serviceWorker.register = () => {
console.log("Blocked ServiceWorker registration attempt");
return Promise.resolve({
scope: "/",
active: navigator.serviceWorker.controller,
installing: null,
waiting: null,
addEventListener: () => {},
removeEventListener: () => {},
});
};
}
async loadSiteIndex() {
// Check if we have a stored initial path from a refresh
let initialPath = '/';
try {
const storedPath = sessionStorage.getItem('iframe_initial_path');
if (storedPath) {
initialPath = storedPath;
// Clear the stored path after using it
sessionStorage.removeItem('iframe_initial_path');
}
} catch (error) {
console.warn('loadSiteIndex: Failed to read initial path from sessionStorage:', error);
}
const serializedRequest = {
url: `${location.origin}/`,
method: "GET",
body: null,
headers: {},
};
const response = await this.rpcClient.fetch(serializedRequest);
if (response?.status !== 200) {
throw new Error(`Failed to fetch site index: ${response?.status || 'Invalid response from site: ' + response} ${response?.statusText || ''}`);
}
if (response.headers["Content-Type"] !== "text/html") {
throw new Error(`Unexpected Content-Type: ${response.headers["Content-Type"]}`);
}
const bytes = new Uint8Array(atob(response.body).split('').map(c => c.charCodeAt(0)));
const text = new TextDecoder().decode(bytes);
// Set the initial path on window before replacing the document
// This will be available to the NavigationHandler when it initializes
if (initialPath && initialPath !== '/') {
window.__IFRAME_INITIAL_PATH__ = initialPath;
}
this.replaceDocument(text);
}
replaceDocument(htmlContent) {
console.log("replaceDocument: Starting...");
// Restore the initial path from sessionStorage before replacing document
let initialPath = '/';
try {
const storedPath = sessionStorage.getItem('spa_initial_path');
if (storedPath) {
initialPath = storedPath;
sessionStorage.removeItem('spa_initial_path');
console.log('replaceDocument: Restored initial path:', initialPath);
// Set it on window for the new document
window.__IFRAME_INITIAL_PATH__ = initialPath;
}
} catch (error) {
console.warn('replaceDocument: Failed to restore initial path:', error);
}
// Create a new document from the HTML content
const parser = new DOMParser();
const newDoc = parser.parseFromString(htmlContent, "text/html");
// Extract scripts for re-execution
const scripts = [];
newDoc.querySelectorAll("script").forEach((script) => {
scripts.push({
src: script.src,
type: script.type,
async: script.hasAttribute("async"),
defer: script.hasAttribute("defer"),
});
script.remove();
});
// Replace document content
document.head.innerHTML = newDoc.head.innerHTML;
document.body.innerHTML = newDoc.body.innerHTML;
// Re-add scripts to execute them
scripts.forEach((script) => {
const newScript = document.createElement("script");
newScript.src = script.src;
newScript.type = script.type;
if (script.async) newScript.async = true;
if (script.defer) newScript.defer = true;
document.body.appendChild(newScript);
});
// Ensure initial navigation after document is loaded
this.ensureInitialNavigation();
}
showError(message, error) {
console.error(message, error);
document.body.innerHTML = `
<div style="
font-family: system-ui, -apple-system, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
border-left: 4px solid #dc3545;
">
<h2 style="color: #dc3545; margin-top: 0;">Fetch Client Error</h2>
<p><strong>${message}</strong></p>
<p style="color: #6c757d;">${error.message || error}</p>
<details style="margin-top: 20px;">
<summary style="cursor: pointer; color: #007bff;">Technical Details</summary>
<pre style="
background: #f1f3f4;
padding: 10px;
border-radius: 4px;
overflow-x: auto;
font-size: 12px;
margin-top: 10px;
">${error.stack || JSON.stringify(error, null, 2)}</pre>
</details>
</div>
`;
}
}
// Global error handlers
const setupGlobalErrorHandlers = () => {
window.addEventListener('error', (event) => {
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: {
level: "error",
message: `Uncaught Error: ${event.message}`,
source: event.filename,
lineno: event.lineno,
colno: event.colno,
stack: event.error?.stack
}
}, "*");
} catch {
// Ignore postMessage errors
}
});
window.addEventListener('unhandledrejection', (event) => {
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: {
level: "error",
message: "Unhandled Promise Rejection",
reason: event.reason,
promise: event.promise ? 'Promise object' : 'No promise object'
}
}, "*");
} catch {
// Ignore postMessage errors
}
});
};
// Initialize
setupGlobalErrorHandlers();
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => new FetchClient());
} else {
new FetchClient();
}
+2 -2
View File
@@ -4,7 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Site Preview</title>
<link rel="stylesheet" href="/_iframe-client.css">
<link rel="stylesheet" href="/_iframe-client/client.css">
</head>
<body>
<div class="loading">
@@ -12,6 +12,6 @@
<p>Loading preview...</p>
<p><small>Waiting for ServiceWorker and parent communication</small></p>
</div>
<script src="/_iframe-client.js"></script>
<script type="module" src="/_iframe-client/main.js"></script>
</body>
</html>
+68 -14
View File
@@ -48,7 +48,14 @@ function handleJSONRPCResponse(message) {
// Create response from serialized response
const { status, statusText, headers, body } = result;
const response = new Response(body, {
// Decode base64 body if present
let decoded = null;
if (typeof body === "string") {
decoded = new Uint8Array(atob(body).split('').map(c => c.charCodeAt(0)));
}
const response = new Response(decoded, {
status: status || 200,
statusText: statusText || "OK",
headers: headers || {},
@@ -61,22 +68,37 @@ async function requestViaJSONRPC(request) {
return new Promise(async (resolve, reject) => {
const id = ++requestIdCounter;
// Serialize the fetch request
let body = null;
if (request.body) {
try {
// Convert body to string (JSON-serializable)
body = await request.text();
} catch (error) {
reject(new Error(`Failed to serialize request body: ${error.message}`));
return;
// Check if request is a plain object or Request object
let url, method, headers, body;
if (request instanceof Request) {
// Handle Request object
url = request.url;
method = request.method;
headers = Object.fromEntries(request.headers.entries());
if (request.body) {
try {
// Convert body to Uint8Array then base64 encode
const bytes = await request.bytes();
body = btoa(String.fromCharCode(...bytes));
} catch (error) {
reject(new Error(`Failed to serialize request body: ${error.message}`));
return;
}
}
} else {
// Handle plain request object
url = request.url;
method = request.method || 'GET';
headers = request.headers || {};
body = request.body || null;
}
const serializedRequest = {
url: request.url,
method: request.method,
headers: Object.fromEntries(request.headers.entries()),
url: url,
method: method,
headers: headers,
body: body,
};
@@ -101,7 +123,7 @@ async function requestViaJSONRPC(request) {
setTimeout(() => {
if (pendingRequests.has(id)) {
pendingRequests.delete(id);
reject(new Error(`Timeout requesting: ${request.url}`));
reject(new Error(`Timeout requesting: ${url}`));
}
}, 10000);
});
@@ -126,6 +148,38 @@ self.addEventListener("fetch", (event) => {
return;
}
// Let iframe client assets be handled normally (anything in _iframe-client directory and common assets)
if (url.pathname.startsWith("/_iframe-client/") ||
url.pathname === "/favicon.ico" ||
url.pathname === "/manifest.webmanifest") {
return;
}
// For SPA routes, check if this is a navigation request (HTML page request)
// But first check if we need to load the iframe client (this happens during refresh)
if (event.request.mode === "navigate" &&
(event.request.headers.get("accept") || "").includes("text/html")) {
// Check if this is a request for the iframe client itself
// We need to serve the iframe client HTML first, which will then load the SPA
if (url.pathname !== "/") {
// Redirect to root to load the iframe client, which will then navigate to the target path
const response = Response.redirect(new URL("/", event.request.url).href, 302);
event.respondWith(response);
return;
}
// This is a request for the root path, serve the site's index.html via JSON-RPC
const rootRequest = {
url: new URL("/", event.request.url).href,
method: event.request.method,
headers: Object.fromEntries(event.request.headers.entries()),
body: event.request.body
};
event.respondWith(handleRequest(rootRequest));
return;
}
// Handle all other requests through JSON-RPC communication
event.respondWith(handleRequest(event.request));
});
+3 -3
View File
@@ -2,14 +2,14 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
<title>Shakespeare - AI-Powered Nostr Development</title>
<meta name="description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment">
<meta property="og:type" content="website">
<meta property="og:title" content="Shakespeare - AI-Powered Nostr Development">
<meta property="og:description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment">
<!-- <meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:"> -->
<link rel="icon" type="image/png" href="/favicon.png">
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
<link rel="icon" type="image/png" href="/shakespeare.png">
<link rel="manifest" href="/manifest.webmanifest">
</head>
<body>
+1189 -876
View File
File diff suppressed because it is too large. Load diff
+31 -15
View File
@@ -4,18 +4,23 @@
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "npm i && vite",
"build": "npm i && vite build && cp dist/index.html dist/404.html",
"test": "npm i && tsc -p tsconfig.app.json --noEmit && eslint && vitest run && vite build",
"dev": "npm i --silent && vite",
"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",
"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"
},
"dependencies": {
"@ai-sdk/openai": "^1.3.23",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^6.0.1",
"@hookform/resolvers": "^3.9.0",
"@isomorphic-git/lightning-fs": "^4.6.2",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.5",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.9",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -43,38 +48,45 @@
"@radix-ui/react-toggle": "^1.1.0",
"@radix-ui/react-toggle-group": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.4",
"@std/path": "npm:@jsr/std__path@^1.1.1",
"@std/encoding": "npm:@jsr/std__encoding@^1.0.10",
"@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
"@webcontainer/api": "^1.6.1",
"ai": "^4.3.19",
"buffer": "^6.0.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.0.0",
"date-fns": "^3.6.0",
"decimal.js": "^10.6.0",
"embla-carousel-react": "^8.3.0",
"esbuild-wasm": "^0.25.8",
"i18next": "^25.5.2",
"ignore": "^7.0.5",
"input-otp": "^1.2.4",
"isomorphic-git": "^1.32.1",
"jszip": "^3.10.1",
"lucide-react": "^0.525.0",
"next-themes": "^0.3.0",
"nostr-tools": "^2.15.1",
"nostr-tools": "^2.15.2",
"openai": "^5.15.0",
"path-browserify": "^1.0.1",
"qrcode": "^1.5.4",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.53.0",
"react-i18next": "^15.7.3",
"react-markdown": "^10.1.0",
"react-resizable-panels": "^3.0.3",
"react-router-dom": "^6.26.2",
"react-syntax-highlighter": "^15.6.1",
"recharts": "^2.12.7",
"remark-gfm": "^4.0.1",
"sonner": "^1.5.0",
"streamdown": "~1.0.0",
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"turndown": "^7.2.1",
"uri-templates": "^0.2.0",
"use-stick-to-bottom": "^1.1.1",
"vaul": "^0.9.3",
"webln": "^0.3.2",
"zod": "^3.25.76"
},
"devDependencies": {
@@ -84,11 +96,15 @@
"@tailwindcss/typography": "^0.5.15",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^14.6.1",
"@types/jszip": "^3.4.0",
"@types/node": "^22.5.5",
"@types/path-browserify": "^1.0.3",
"@types/qrcode": "^1.5.5",
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@types/react-syntax-highlighter": "^15.5.13",
"@types/turndown": "^5.0.5",
"@types/uri-templates": "^0.1.34",
"@vitejs/plugin-react-swc": "^3.5.0",
"autoprefixer": "^10.4.20",
"eslint": "^9.9.0",
+40
View File
@@ -0,0 +1,40 @@
export default {
async fetch(request: Request): Promise<Response> {
const url = new URL(request.url);
const target = url.searchParams.get("url");
if (!target) {
return new Response("Include a `url` query parameter", { status: 400 });
}
// Handle CORS preflight requests
if (request.method === "OPTIONS") {
return new Response(null, {
status: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS",
"Access-Control-Allow-Headers": "*", // Or specify specific headers
"Access-Control-Max-Age": "86400", // Cache preflight for 24 hours
}
});
}
const headers = new Headers(request.headers);
headers.set('User-Agent', 'Shakespeare Proxy <https://proxy.shakespeare.diy/>');
const targetResponse = await fetch(target, {
method: request.method,
headers: headers,
body: request.body,
});
const response = new Response(targetResponse.body, targetResponse);
response.headers.set("Access-Control-Allow-Origin", "*");
response.headers.set("Access-Control-Allow-Methods", "GET,HEAD,POST,OPTIONS");
response.headers.set("Access-Control-Allow-Headers", "*");
return response;
}
};
+688
View File
@@ -0,0 +1,688 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- saved from url=(0053)https://www.gnu.org/licenses/agpl-3.0-standalone.html -->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>GNU Affero General Public License - GNU Project - Free Software Foundation (FSF)</title>
<link rel="alternate" type="application/rdf+xml" href="http://www.gnu.org/licenses/agpl-3.0.rdf">
</head>
<body>
<h3 style="text-align: center;">GNU AFFERO GENERAL PUBLIC LICENSE</h3>
<p style="text-align: center;">Version 3, 19 November 2007</p>
<p>Copyright © 2007 Free Software Foundation,
Inc. &lt;<a href="https://fsf.org/">https://fsf.org/</a>&gt;
<br>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.</p>
<h4 id="preamble">Preamble</h4>
<p>The GNU Affero General Public License is a free, copyleft license
for software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.</p>
<p>The licenses for most software and other practical works are
designed to take away your freedom to share and change the works. By
contrast, our General Public Licenses are intended to guarantee your
freedom to share and change all versions of a program--to make sure it
remains free software for all its users.</p>
<p>When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.</p>
<p>Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.</p>
<p>A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.</p>
<p>The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.</p>
<p>An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.</p>
<p>The precise terms and conditions for copying, distribution and
modification follow.</p>
<h4 id="terms">TERMS AND CONDITIONS</h4>
<h4 id="section0">0. Definitions.</h4>
<p>"This License" refers to version 3 of the GNU Affero General Public
License.</p>
<p>"Copyright" also means copyright-like laws that apply to other kinds
of works, such as semiconductor masks.</p>
<p>"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.</p>
<p>To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.</p>
<p>A "covered work" means either the unmodified Program or a work based
on the Program.</p>
<p>To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.</p>
<p>To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.</p>
<p>An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.</p>
<h4 id="section1">1. Source Code.</h4>
<p>The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.</p>
<p>A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.</p>
<p>The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.</p>
<p>The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.</p>
<p>The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.</p>
<p>The Corresponding Source for a work in source code form is that
same work.</p>
<h4 id="section2">2. Basic Permissions.</h4>
<p>All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.</p>
<p>You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.</p>
<p>Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.</p>
<h4 id="section3">3. Protecting Users' Legal Rights From Anti-Circumvention Law.</h4>
<p>No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.</p>
<p>When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.</p>
<h4 id="section4">4. Conveying Verbatim Copies.</h4>
<p>You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.</p>
<p>You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.</p>
<h4 id="section5">5. Conveying Modified Source Versions.</h4>
<p>You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:</p>
<ul>
<li>a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.</li>
<li>b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".</li>
<li>c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.</li>
<li>d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.</li>
</ul>
<p>A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.</p>
<h4 id="section6">6. Conveying Non-Source Forms.</h4>
<p>You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:</p>
<ul>
<li>a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.</li>
<li>b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.</li>
<li>c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.</li>
<li>d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.</li>
<li>e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.</li>
</ul>
<p>A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.</p>
<p>A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.</p>
<p>"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.</p>
<p>If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).</p>
<p>The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.</p>
<p>Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.</p>
<h4 id="section7">7. Additional Terms.</h4>
<p>"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.</p>
<p>When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.</p>
<p>Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:</p>
<ul>
<li>a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or</li>
<li>b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or</li>
<li>c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or</li>
<li>d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or</li>
<li>e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or</li>
<li>f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.</li>
</ul>
<p>All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further restriction,
you may remove that term. If a license document contains a further
restriction but permits relicensing or conveying under this License, you
may add to a covered work material governed by the terms of that license
document, provided that the further restriction does not survive such
relicensing or conveying.</p>
<p>If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.</p>
<p>Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.</p>
<h4 id="section8">8. Termination.</h4>
<p>You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).</p>
<p>However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.</p>
<p>Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.</p>
<p>Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.</p>
<h4 id="section9">9. Acceptance Not Required for Having Copies.</h4>
<p>You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.</p>
<h4 id="section10">10. Automatic Licensing of Downstream Recipients.</h4>
<p>Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.</p>
<p>An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.</p>
<p>You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.</p>
<h4 id="section11">11. Patents.</h4>
<p>A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".</p>
<p>A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.</p>
<p>Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.</p>
<p>In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.</p>
<p>If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.</p>
<p>If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.</p>
<p>A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.</p>
<p>Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.</p>
<h4 id="section12">12. No Surrender of Others' Freedom.</h4>
<p>If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.</p>
<h4 id="section13">13. Remote Network Interaction; Use with the GNU General Public License.</h4>
<p>Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.</p>
<p>Notwithstanding any other provision of this License, you have permission
to link or combine any covered work with a work licensed under version 3
of the GNU General Public License into a single combined work, and to
convey the resulting work. The terms of this License will continue to
apply to the part which is the covered work, but the work with which it is
combined will remain governed by version 3 of the GNU General Public
License.</p>
<h4 id="section14">14. Revised Versions of this License.</h4>
<p>The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may differ
in detail to address new problems or concerns.</p>
<p>Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero
General Public License "or any later version" applies to it, you have
the option of following the terms and conditions either of that
numbered version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number
of the GNU Affero General Public License, you may choose any version
ever published by the Free Software Foundation.</p>
<p>If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that
proxy's public statement of acceptance of a version permanently
authorizes you to choose that version for the Program.</p>
<p>Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.</p>
<h4 id="section15">15. Disclaimer of Warranty.</h4>
<p>THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.</p>
<h4 id="section16">16. Limitation of Liability.</h4>
<p>IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.</p>
<h4 id="section17">17. Interpretation of Sections 15 and 16.</h4>
<p>If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.</p>
<p>END OF TERMS AND CONDITIONS</p>
<h4 id="howto">How to Apply These Terms to Your New Programs</h4>
<p>If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.</p>
<p>To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.</p>
<pre> &lt;one line to give the program's name and a brief idea of what it does.&gt;
Copyright (C) &lt;year&gt; &lt;name of author&gt;
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;.
</pre>
<p>Also add information on how to contact you by electronic and paper mail.</p>
<p>If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.</p>
<p>You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
&lt;<a href="https://www.gnu.org/licenses/">https://www.gnu.org/licenses/</a>&gt;.</p>
</body></html>
+27
View File
@@ -0,0 +1,27 @@
<svg xmlns="http://www.w3.org/2000/svg" width="166" height="20" role="img" aria-label="🎭 Edit with: Shakespeare">
<title>🎭 Edit with: Shakespeare</title>
<defs>
<mask id="round">
<rect width="166" height="20" rx="3" fill="#fff"/>
</mask>
<linearGradient id="shine" x2="0" y2="100%">
<stop offset="0" stop-color="#fff" stop-opacity=".2"/>
<stop offset="0.1" stop-color="#fff" stop-opacity=".05"/>
<stop offset="1" stop-color="#fff" stop-opacity="0"/>
</linearGradient>
</defs>
<g mask="url(#round)">
<!-- Left label background -->
<rect width="78" height="20" fill="#555"/>
<!-- Right label background -->
<rect x="78" width="88" height="20" fill="#6f42c1"/>
<rect width="166" height="20" fill="url(#shine)"/>
</g>
<!-- Text -->
<g fill="#fff" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,Ubuntu,Cantarell,Noto Sans,sans-serif" font-size="11">
<text x="39" y="14">🎭 Edit with</text>
<text x="122" y="14" font-weight="600">Shakespeare</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

+2 -2
View File
@@ -8,12 +8,12 @@
"theme_color": "#000000",
"icons": [
{
"src": "/icon-192.png",
"src": "/shakespeare.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/icon-512.png",
"src": "/shakespeare.png",
"sizes": "512x512",
"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

+35 -22
View File
@@ -4,20 +4,21 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createHead, UnheadProvider } from '@unhead/react/client';
import { InferSeoMetaPlugin } from '@unhead/addons';
import { Suspense } from 'react';
import { Suspense, useEffect } from 'react';
import LightningFS from '@isomorphic-git/lightning-fs';
import NostrProvider from '@/components/NostrProvider';
import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import { NostrLoginProvider } from '@nostrify/react/login';
import { AppProvider } from '@/components/AppProvider';
import { AppConfig } from '@/contexts/AppContext';
import { AISettingsProvider } from '@/components/AISettingsProvider';
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
import { FSProvider } from '@/components/FSProvider';
import { JSRuntimeProvider } from '@/components/JSRuntimeProvider';
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
import { WebContainerAdapter } from '@/lib/WebContainerAdapter';
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
import AppRouter from './AppRouter';
const head = createHead({
@@ -37,8 +38,9 @@ const queryClient = new QueryClient({
});
const defaultConfig: AppConfig = {
theme: "light",
theme: "system",
relayUrl: "wss://relay.primal.net",
deployServer: "shakespeare.wtf",
};
const presetRelays = [
@@ -52,33 +54,44 @@ const presetRelays = [
const lightningFS = new LightningFS('shakespeare-fs');
const fs = new LightningFSAdapter(lightningFS.promises);
// Initialize JSRuntime with WebContainer adapter
const jsRuntime = new WebContainerAdapter();
// Component to handle filesystem cleanup on startup
// Automatically removes files older than 1 hour from /tmp directory
function FSCleanupHandler() {
useEffect(() => {
// Run cleanup on application startup to remove stale temporary files
// This helps prevent the VFS from accumulating old files over time
cleanupTmpDirectory(fs).catch(console.error);
}, []);
return null;
}
export function App() {
return (
<UnheadProvider head={head}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
<FSProvider fs={fs}>
<JSRuntimeProvider runtime={jsRuntime}>
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<AISettingsProvider>
<QueryClientProvider client={queryClient}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
<FSProvider fs={fs}>
<FSCleanupHandler />
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<AISettingsProvider>
<GitSettingsProvider>
<SessionManagerProvider>
<TooltipProvider>
<Toaster />
<Sonner />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</AISettingsProvider>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>
</JSRuntimeProvider>
</FSProvider>
</AppProvider>
</SessionManagerProvider>
</GitSettingsProvider>
</AISettingsProvider>
</NostrProvider>
</NostrLoginProvider>
</FSProvider>
</AppProvider>
</QueryClientProvider>
</UnheadProvider>
);
}
+24
View File
@@ -1,17 +1,41 @@
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop";
import { SessionMonitor } from "./components/SessionMonitor";
import Index from "./pages/Index";
import Clone from "./pages/Clone";
import Settings from "./pages/Settings";
import Preferences from "./pages/Preferences";
import NostrSettings from "./pages/NostrSettings";
import AISettings from "./pages/AISettings";
import GitSettings from "./pages/GitSettings";
import DataSettings from "./pages/DataSettings";
import AboutSettings from "./pages/AboutSettings";
import GitHubOAuth from "./pages/GitHubOAuth";
import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound";
import { ProjectView } from "./pages/ProjectView";
import { SettingsLayout } from "./components/SettingsLayout";
export function AppRouter() {
return (
<BrowserRouter>
<ScrollToTop />
<SessionMonitor />
<Routes>
<Route path="/" element={<Index />} />
<Route path="/clone" element={<Clone />} />
<Route path="/oauth/github" element={<GitHubOAuth />} />
<Route path="/settings" element={<SettingsLayout />}>
<Route index element={<Settings />} />
<Route path="preferences" element={<Preferences />} />
<Route path="nostr" element={<NostrSettings />} />
<Route path="ai" element={<AISettings />} />
<Route path="git" element={<GitSettings />} />
<Route path="data" element={<DataSettings />} />
<Route path="about" element={<AboutSettings />} />
</Route>
<Route path="/project/:projectId" element={<ProjectView />} />
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
<Route path="/:nip19" element={<NIP19Page />} />
+114
View File
@@ -0,0 +1,114 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="500px" height="500px" style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd" xmlns:xlink="http://www.w3.org/1999/xlink">
<g><path style="opacity:0.004" fill="#fefffe" d="M 1.5,10.5 C 2.83333,11.1667 2.83333,11.1667 1.5,10.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 287.5,14.5 C 288.833,15.1667 288.833,15.1667 287.5,14.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 393.5,19.5 C 394.833,20.1667 394.833,20.1667 393.5,19.5 Z"/></g>
<g><path style="opacity:0.067" fill="#d8d5d1" d="M 257.5,33.5 C 252.167,33.5 246.833,33.5 241.5,33.5C 246.567,32.8118 251.733,32.1451 257,31.5C 257.464,32.0944 257.631,32.7611 257.5,33.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 304.5,37.5 C 305.833,38.1667 305.833,38.1667 304.5,37.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 199.5,52.5 C 198.833,51.1667 198.833,51.1667 199.5,52.5 Z"/></g>
<g><path style="opacity:1" fill="#272422" d="M 241.5,33.5 C 246.833,33.5 252.167,33.5 257.5,33.5C 269.508,34.507 280.508,38.3403 290.5,45C 294,47.3342 297,50.1675 299.5,53.5C 298.21,54.0577 297.377,55.0577 297,56.5C 294.888,52.8729 293.221,52.8729 292,56.5C 291.086,55.3463 290.253,55.513 289.5,57C 292.321,58.6213 292.987,60.788 291.5,63.5C 281.078,49.3135 266.911,42.3135 249,42.5C 229.512,42.5414 213.845,50.2081 202,65.5C 196.198,75.0401 193.698,85.3734 194.5,96.5C 193.546,91.1876 192.546,85.1876 191.5,78.5C 189.508,78.6715 187.842,78.0049 186.5,76.5C 183.867,77.7822 183.867,79.1156 186.5,80.5C 185.234,81.3624 183.901,82.0291 182.5,82.5C 183.047,79.2976 184.047,76.2976 185.5,73.5C 186.906,73.0269 187.573,72.0269 187.5,70.5C 188.498,66.4945 190.498,63.1612 193.5,60.5C 194.906,60.0269 195.573,59.0269 195.5,57.5C 196.833,55.8333 198.167,54.1667 199.5,52.5C 211.392,41.6322 225.392,35.2989 241.5,33.5 Z"/></g>
<g><path style="opacity:0.435" fill="#9b9895" d="M 195.5,57.5 C 195.573,59.0269 194.906,60.0269 193.5,60.5C 193.427,58.9731 194.094,57.9731 195.5,57.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 404.5,60.5 C 405.833,61.1667 405.833,61.1667 404.5,60.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 92.5,61.5 C 93.8333,62.1667 93.8333,62.1667 92.5,61.5 Z"/></g>
<g><path style="opacity:1" fill="#1c1a18" d="M 299.5,53.5 C 305.302,58.4362 309.635,64.4362 312.5,71.5C 312.343,72.8734 312.51,74.2068 313,75.5C 313.876,77.7582 315.043,79.7582 316.5,81.5C 318.737,87.0285 320.903,92.6952 323,98.5C 328.732,104.725 334.232,111.058 339.5,117.5C 339.427,119.027 340.094,120.027 341.5,120.5C 343.293,122.426 344.293,124.759 344.5,127.5C 345.22,133.138 345.553,138.804 345.5,144.5C 344.999,150.505 342.499,155.505 338,159.5C 338.33,165.569 338.164,171.569 337.5,177.5C 336.732,178.263 336.232,179.263 336,180.5C 335.261,178.779 334.427,177.113 333.5,175.5C 333.034,177.705 333.034,179.705 333.5,181.5C 332.23,180.438 331.063,179.438 330,178.5C 329.667,178.833 329.333,179.167 329,179.5C 328.333,178.5 328.333,177.5 329,176.5C 329.718,177.451 330.551,177.617 331.5,177C 330.418,175.67 329.751,174.17 329.5,172.5C 329.799,170.396 329.466,168.396 328.5,166.5C 317.499,170.764 306.666,170.431 296,165.5C 295.617,166.056 295.117,166.389 294.5,166.5C 293.533,167.806 292.199,168.473 290.5,168.5C 290.688,170.103 290.188,171.437 289,172.5C 287.477,170.431 286.643,168.097 286.5,165.5C 287.351,161.435 288.517,157.435 290,153.5C 293.306,151.968 296.806,150.801 300.5,150C 303.708,147.229 305.708,143.729 306.5,139.5C 305.527,137.36 304.027,135.693 302,134.5C 299.684,135.367 297.684,134.701 296,132.5C 293.685,129.223 292.351,125.556 292,121.5C 292.692,108.983 293.858,96.4825 295.5,84C 295.554,78.7227 294.887,73.556 293.5,68.5C 293.771,66.6203 293.104,65.287 291.5,64.5C 291.5,64.1667 291.5,63.8333 291.5,63.5C 292.987,60.788 292.321,58.6213 289.5,57C 290.253,55.513 291.086,55.3463 292,56.5C 293.221,52.8729 294.888,52.8729 297,56.5C 297.377,55.0577 298.21,54.0577 299.5,53.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 448.5,63.5 C 449.833,64.1667 449.833,64.1667 448.5,63.5 Z"/></g>
<g><path style="opacity:0.141" fill="#b0abaa" d="M 291.5,64.5 C 293.104,65.287 293.771,66.6203 293.5,68.5C 292.326,67.4863 291.66,66.153 291.5,64.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 426.5,69.5 C 427.833,70.1667 427.833,70.1667 426.5,69.5 Z"/></g>
<g><path style="opacity:0.09" fill="#c3bbb9" d="M 187.5,70.5 C 187.573,72.0269 186.906,73.0269 185.5,73.5C 185.427,71.9731 186.094,70.9731 187.5,70.5 Z"/></g>
<g><path style="opacity:0.824" fill="#726e69" d="M 312.5,71.5 C 314.729,74.3538 316.062,77.6871 316.5,81.5C 315.043,79.7582 313.876,77.7582 313,75.5C 312.51,74.2068 312.343,72.8734 312.5,71.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 487.5,76.5 C 488.833,77.1667 488.833,77.1667 487.5,76.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 387.5,78.5 C 388.833,79.1667 388.833,79.1667 387.5,78.5 Z"/></g>
<g><path style="opacity:1" fill="#1e1d1b" d="M 194.5,96.5 C 205.307,90.5958 215.64,91.2624 225.5,98.5C 227.97,102.11 229.304,106.11 229.5,110.5C 227.359,120.522 224.859,130.522 222,140.5C 221.176,143.882 221.343,147.216 222.5,150.5C 223.607,151.022 224.774,151.355 226,151.5C 229.926,150.727 233.759,149.727 237.5,148.5C 240.135,147.461 242.135,145.794 243.5,143.5C 247.778,147.659 247.111,151.159 241.5,154C 245.303,156.071 248.97,158.404 252.5,161C 255.77,162.66 259.103,162.994 262.5,162C 263.935,164.267 263.602,166.267 261.5,168C 258.448,169.211 255.281,170.045 252,170.5C 244.065,169.521 236.398,167.521 229,164.5C 222.843,167.108 216.51,169.108 210,170.5C 207.815,170.079 205.649,169.579 203.5,169C 202.424,167.274 202.257,165.441 203,163.5C 207.408,161.43 211.575,158.93 215.5,156C 213.504,151.729 213.004,147.229 214,142.5C 216.819,132.558 219.319,122.558 221.5,112.5C 221.81,108.306 220.143,105.139 216.5,103C 208.667,100.569 201.501,101.736 195,106.5C 191.661,123.896 191.827,141.229 195.5,158.5C 194.895,160.026 193.729,161.026 192,161.5C 191.14,156.863 188.307,154.697 183.5,155C 184.833,154.333 184.833,153.667 183.5,153C 181.934,152.7 180.601,153.2 179.5,154.5C 166.076,151.07 158.742,142.403 157.5,128.5C 158.051,123.851 159.385,119.518 161.5,115.5C 162.906,115.027 163.573,114.027 163.5,112.5C 167.455,107.373 171.622,102.373 176,97.5C 178.486,92.5113 180.652,87.5113 182.5,82.5C 183.901,82.0291 185.234,81.3624 186.5,80.5C 183.867,79.1156 183.867,77.7822 186.5,76.5C 187.842,78.0049 189.508,78.6715 191.5,78.5C 192.546,85.1876 193.546,91.1876 194.5,96.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 20.5,86.5 C 21.8333,87.1667 21.8333,87.1667 20.5,86.5 Z"/></g>
<g><path style="opacity:0.792" fill="#97938f" d="M 272.5,96.5 C 275.189,97.1894 276.856,98.856 277.5,101.5C 275.451,100.118 273.785,98.4516 272.5,96.5 Z"/></g>
<g><path style="opacity:1" fill="#23201e" d="M 272.5,96.5 C 273.785,98.4516 275.451,100.118 277.5,101.5C 279.574,103.715 279.907,106.215 278.5,109C 275.758,109.295 273.425,108.462 271.5,106.5C 271.167,105.5 270.5,104.833 269.5,104.5C 265.505,102.79 261.339,101.456 257,100.5C 252.701,101.544 248.535,102.878 244.5,104.5C 237.97,101.229 237.97,97.7288 244.5,94C 251.789,91.6687 259.122,91.3353 266.5,93C 268.727,93.941 270.727,95.1077 272.5,96.5 Z"/></g>
<g><path style="opacity:0.004" fill="#d7d2ce" d="M 269.5,104.5 C 270.5,104.833 271.167,105.5 271.5,106.5C 270.167,106.5 269.5,105.833 269.5,104.5 Z"/></g>
<g><path style="opacity:1" fill="#242220" d="M 216.5,118.5 C 215.603,119.598 214.77,119.598 214,118.5C 213.59,119.901 213.09,121.234 212.5,122.5C 209.43,122.632 206.43,122.299 203.5,121.5C 200.197,118.335 199.697,114.668 202,110.5C 209.746,105.174 214.913,107.008 217.5,116C 217.257,116.902 216.923,117.735 216.5,118.5 Z"/></g>
<g><path style="opacity:1" fill="#272422" d="M 254.5,107.5 C 262.982,107.765 266.149,112.099 264,120.5C 258.514,126.08 253.514,125.747 249,119.5C 247.486,113.877 249.319,109.877 254.5,107.5 Z"/></g>
<g><path style="opacity:0.137" fill="#a59b96" d="M 163.5,112.5 C 163.573,114.027 162.906,115.027 161.5,115.5C 161.427,113.973 162.094,112.973 163.5,112.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 89.5,117.5 C 90.8333,118.167 90.8333,118.167 89.5,117.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 437.5,118.5 C 438.833,119.167 438.833,119.167 437.5,118.5 Z"/></g>
<g><path style="opacity:0.992" fill="#72716a" d="M 216.5,118.5 C 216.167,120.833 214.833,122.167 212.5,122.5C 213.09,121.234 213.59,119.901 214,118.5C 214.77,119.598 215.603,119.598 216.5,118.5 Z"/></g>
<g><path style="opacity:0.098" fill="#bfb8b7" d="M 339.5,117.5 C 340.906,117.973 341.573,118.973 341.5,120.5C 340.094,120.027 339.427,119.027 339.5,117.5 Z"/></g>
<g><path style="opacity:0.508" fill="#7f7a74" d="M 203.5,121.5 C 206.43,122.299 209.43,122.632 212.5,122.5C 210.034,123.634 207.367,123.801 204.5,123C 203.944,122.617 203.611,122.117 203.5,121.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 408.5,124.5 C 409.833,125.167 409.833,125.167 408.5,124.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 424.5,133.5 C 425.833,134.167 425.833,134.167 424.5,133.5 Z"/></g>
<g><path style="opacity:0.333" fill="#9e9894" d="M 344.5,127.5 C 345.954,130.718 346.621,134.218 346.5,138C 346.496,140.361 346.163,142.527 345.5,144.5C 345.553,138.804 345.22,133.138 344.5,127.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 140.5,135.5 C 141.833,136.167 141.833,136.167 140.5,135.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 53.5,137.5 C 54.8333,138.167 54.8333,138.167 53.5,137.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 353.5,140.5 C 354.833,141.167 354.833,141.167 353.5,140.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 493.5,141.5 C 494.833,142.167 494.833,142.167 493.5,141.5 Z"/></g>
<g><path style="opacity:0.455" fill="#918f8b" d="M 243.5,143.5 C 242.135,145.794 240.135,147.461 237.5,148.5C 239.385,146.947 240.385,144.947 240.5,142.5C 241.791,142.263 242.791,142.596 243.5,143.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 437.5,153.5 C 438.833,154.167 438.833,154.167 437.5,153.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 438.5,183.5 C 439.833,184.167 439.833,184.167 438.5,183.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 446.5,183.5 C 447.833,184.167 447.833,184.167 446.5,183.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 123.5,185.5 C 124.833,186.167 124.833,186.167 123.5,185.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 129.5,186.5 C 130.833,187.167 130.833,187.167 129.5,186.5 Z"/></g>
<g><path style="opacity:0.839" fill="#756a67" d="M 333.5,187.5 C 333.346,189.97 332.346,191.97 330.5,193.5C 330.455,190.923 331.455,188.923 333.5,187.5 Z"/></g>
<g><path style="opacity:1" fill="#262321" d="M 329.5,172.5 C 329.751,174.17 330.418,175.67 331.5,177C 330.551,177.617 329.718,177.451 329,176.5C 328.333,177.5 328.333,178.5 329,179.5C 329.333,179.167 329.667,178.833 330,178.5C 331.063,179.438 332.23,180.438 333.5,181.5C 333.034,179.705 333.034,177.705 333.5,175.5C 334.427,177.113 335.261,178.779 336,180.5C 336.232,179.263 336.732,178.263 337.5,177.5C 337.657,178.873 337.49,180.207 337,181.5C 336.124,183.758 334.957,185.758 333.5,187.5C 331.455,188.923 330.455,190.923 330.5,193.5C 321.603,207.727 311.937,221.394 301.5,234.5C 301.785,232.712 301.452,231.045 300.5,229.5C 297.606,230.909 296.606,230.242 297.5,227.5C 298.167,225.833 298.833,224.167 299.5,222.5C 306.66,212.186 313.827,201.853 321,191.5C 324.438,185.303 327.271,178.969 329.5,172.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 26.5,198.5 C 27.8333,199.167 27.8333,199.167 26.5,198.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 413.5,204.5 C 414.833,205.167 414.833,205.167 413.5,204.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 74.5,209.5 C 75.8333,210.167 75.8333,210.167 74.5,209.5 Z"/></g>
<g><path style="opacity:0.965" fill="#272422" d="M 195.5,158.5 C 199.127,167.099 202.794,175.765 206.5,184.5C 206.427,186.027 207.094,187.027 208.5,187.5C 213.391,196.567 220.558,202.9 230,206.5C 254.97,200.996 273.803,187.329 286.5,165.5C 286.643,168.097 287.477,170.431 289,172.5C 290.188,171.437 290.688,170.103 290.5,168.5C 292.199,168.473 293.533,167.806 294.5,166.5C 290.454,177.733 283.787,187.233 274.5,195C 259.369,206.946 243.036,214.112 225.5,216.5C 222.868,215.466 220.201,214.466 217.5,213.5C 217.5,212.833 217.5,212.167 217.5,211.5C 211.822,206.986 206.989,201.653 203,195.5C 198.434,187.483 194.434,179.15 191,170.5C 175.85,181.982 164.684,196.482 157.5,214C 164.095,213.183 170.762,212.683 177.5,212.5C 174.695,213.319 171.695,213.819 168.5,214C 170.167,214.333 171.833,214.667 173.5,215C 171.136,216.012 169.802,217.345 169.5,219C 170.448,219.483 171.448,219.649 172.5,219.5C 172.5,219.833 172.5,220.167 172.5,220.5C 164.95,221.221 157.617,222.888 150.5,225.5C 148.06,224.726 146.727,223.06 146.5,220.5C 146.886,218.068 147.553,215.734 148.5,213.5C 149.906,213.027 150.573,212.027 150.5,210.5C 153.084,202.664 156.751,195.331 161.5,188.5C 169.649,178.517 178.649,169.351 188.5,161C 187.62,159.644 187.286,158.144 187.5,156.5C 184.505,156.706 181.838,156.04 179.5,154.5C 180.601,153.2 181.934,152.7 183.5,153C 184.833,153.667 184.833,154.333 183.5,155C 188.307,154.697 191.14,156.863 192,161.5C 193.729,161.026 194.895,160.026 195.5,158.5 Z M 217.5,211.5 C 216.221,212.968 214.554,213.635 212.5,213.5C 211.167,213.5 209.833,213.5 208.5,213.5C 202.225,212.066 195.725,211.4 189,211.5C 184.985,211.501 181.151,211.835 177.5,212.5C 170.762,212.683 164.095,213.183 157.5,214C 164.684,196.482 175.85,181.982 191,170.5C 194.434,179.15 198.434,187.483 203,195.5C 206.989,201.653 211.822,206.986 217.5,211.5 Z"/></g>
<g><path style="opacity:0.129" fill="#b5b4af" d="M 206.5,184.5 C 207.906,184.973 208.573,185.973 208.5,187.5C 207.094,187.027 206.427,186.027 206.5,184.5 Z"/></g>
<g><path style="opacity:1" fill="#35312f" d="M 221.5,184.5 C 224.113,183.565 226.779,183.398 229.5,184C 227.709,184.415 226.376,185.415 225.5,187C 228.167,187.667 230.833,187.667 233.5,187C 230.983,183.799 231.483,180.966 235,178.5C 235.667,177.167 235.667,175.833 235,174.5C 232.323,172.959 229.49,171.959 226.5,171.5C 232.176,171.072 237.843,170.905 243.5,171C 245.283,172.067 245.783,173.567 245,175.5C 243.247,176.627 241.413,177.627 239.5,178.5C 238.303,181.934 236.636,185.1 234.5,188C 231.167,188.667 227.833,188.667 224.5,188C 223.29,186.961 222.29,185.794 221.5,184.5 Z"/></g>
<g><path style="opacity:1" fill="#171513" d="M 226.5,171.5 C 229.49,171.959 232.323,172.959 235,174.5C 235.667,175.833 235.667,177.167 235,178.5C 231.483,180.966 230.983,183.799 233.5,187C 230.833,187.667 228.167,187.667 225.5,187C 226.376,185.415 227.709,184.415 229.5,184C 226.779,183.398 224.113,183.565 221.5,184.5C 221.5,183.833 221.5,183.167 221.5,182.5C 221.656,179.934 221.322,177.434 220.5,175C 220.905,174.055 221.572,173.388 222.5,173C 221.5,172.667 220.5,172.333 219.5,172C 221.81,171.503 224.143,171.337 226.5,171.5 Z"/></g>
<g><path style="opacity:1" fill="#413d38" d="M 226.5,171.5 C 224.143,171.337 221.81,171.503 219.5,172C 220.5,172.333 221.5,172.667 222.5,173C 221.572,173.388 220.905,174.055 220.5,175C 221.322,177.434 221.656,179.934 221.5,182.5C 220.916,180.257 219.75,178.257 218,176.5C 217.333,174.833 217.333,173.167 218,171.5C 220.937,170.183 223.77,170.183 226.5,171.5 Z"/></g>
<g><path style="opacity:0.098" fill="#cecbc4" d="M 177.5,212.5 C 181.151,211.835 184.985,211.501 189,211.5C 195.725,211.4 202.225,212.066 208.5,213.5C 198.183,212.774 187.85,212.44 177.5,212.5 Z"/></g>
<g><path style="opacity:0.149" fill="#adaaa7" d="M 150.5,210.5 C 150.573,212.027 149.906,213.027 148.5,213.5C 148.427,211.973 149.094,210.973 150.5,210.5 Z"/></g>
<g><path style="opacity:0.122" fill="#c4b9b8" d="M 217.5,211.5 C 217.5,212.167 217.5,212.833 217.5,213.5C 215.833,214.833 214.167,214.833 212.5,213.5C 214.554,213.635 216.221,212.968 217.5,211.5 Z"/></g>
<g><path style="opacity:1" fill="#181614" d="M 177.5,212.5 C 187.85,212.44 198.183,212.774 208.5,213.5C 209.833,213.5 211.167,213.5 212.5,213.5C 214.167,214.833 215.833,214.833 217.5,213.5C 220.201,214.466 222.868,215.466 225.5,216.5C 225.034,218.201 225.034,219.701 225.5,221C 224.429,221.852 223.429,222.685 222.5,223.5C 219.43,223.632 216.43,223.299 213.5,222.5C 213.44,221.957 213.107,221.624 212.5,221.5C 211.516,224.428 211.183,227.428 211.5,230.5C 209.859,228.797 208.859,226.63 208.5,224C 207.258,223.689 206.258,224.189 205.5,225.5C 204.692,225.192 204.025,224.692 203.5,224C 204.833,222.667 204.833,221.333 203.5,220C 201.866,219.506 200.199,219.34 198.5,219.5C 195.102,219.18 191.768,219.513 188.5,220.5C 188.624,221.107 188.957,221.44 189.5,221.5C 188.891,224.878 190.224,226.878 193.5,227.5C 195.288,228.622 197.288,228.789 199.5,228C 200.756,227.583 201.423,226.75 201.5,225.5C 202.995,225.415 203.995,226.081 204.5,227.5C 203.092,228.243 201.759,229.077 200.5,230C 202.249,232.213 204.249,233.213 206.5,233C 204.881,233.236 203.881,234.069 203.5,235.5C 202.5,235.5 201.5,235.5 200.5,235.5C 198.167,235.5 195.833,235.5 193.5,235.5C 193.333,285.168 193.5,334.834 194,384.5C 194.232,385.737 194.732,386.737 195.5,387.5C 197.821,396.471 201.488,404.805 206.5,412.5C 207.956,415.431 207.123,416.098 204,414.5C 203.333,416.167 203.333,417.833 204,419.5C 204.333,418.833 204.667,418.167 205,417.5C 206.109,420.947 205.109,423.614 202,425.5C 200.086,424.324 200.252,423.324 202.5,422.5C 202.167,422.167 201.833,421.833 201.5,421.5C 199.557,421.535 197.557,421.202 195.5,420.5C 186.876,409.404 181.876,396.738 180.5,382.5C 180.5,328.167 180.5,273.833 180.5,219.5C 177.833,219.5 175.167,219.5 172.5,219.5C 171.448,219.649 170.448,219.483 169.5,219C 169.802,217.345 171.136,216.012 173.5,215C 171.833,214.667 170.167,214.333 168.5,214C 171.695,213.819 174.695,213.319 177.5,212.5 Z M 189.5,221.5 C 192.287,220.523 195.287,220.19 198.5,220.5C 203.5,220.134 204.5,221.8 201.5,225.5C 199.087,227.051 196.421,227.717 193.5,227.5C 191.71,225.728 190.377,223.728 189.5,221.5 Z"/></g>
<g><path style="opacity:0.047" fill="#e0dfd7" d="M 198.5,219.5 C 198.5,219.833 198.5,220.167 198.5,220.5C 195.287,220.19 192.287,220.523 189.5,221.5C 188.957,221.44 188.624,221.107 188.5,220.5C 191.768,219.513 195.102,219.18 198.5,219.5 Z"/></g>
<g><path style="opacity:0.592" fill="#7d7976" d="M 299.5,222.5 C 298.833,224.167 298.167,225.833 297.5,227.5C 296.833,227.5 296.167,227.5 295.5,227.5C 296.124,225.246 297.457,223.579 299.5,222.5 Z"/></g>
<g><path style="opacity:0.592" fill="#94908e" d="M 189.5,221.5 C 190.377,223.728 191.71,225.728 193.5,227.5C 190.224,226.878 188.891,224.878 189.5,221.5 Z"/></g>
<g><path style="opacity:0.247" fill="#837f7a" d="M 201.5,225.5 C 201.423,226.75 200.756,227.583 199.5,228C 197.288,228.789 195.288,228.622 193.5,227.5C 196.421,227.717 199.087,227.051 201.5,225.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 32.5,229.5 C 33.8333,230.167 33.8333,230.167 32.5,229.5 Z"/></g>
<g><path style="opacity:1" fill="#252421" d="M 325.5,381.5 C 324.176,384.148 322.843,386.814 321.5,389.5C 318.621,387.559 315.788,388.226 313,391.5C 311.798,389.323 311.298,386.989 311.5,384.5C 311.333,336.832 311.5,289.166 312,241.5C 313.399,235.938 316.899,234.105 322.5,236C 324.049,237.214 325.215,238.714 326,240.5C 326.832,287.668 326.665,334.668 325.5,381.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 490.5,245.5 C 491.833,246.167 491.833,246.167 490.5,245.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 230.5,246.5 C 231.833,247.167 231.833,247.167 230.5,246.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 223.5,250.5 C 224.833,251.167 224.833,251.167 223.5,250.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 485.5,254.5 C 486.833,255.167 486.833,255.167 485.5,254.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 411.5,255.5 C 412.833,256.167 412.833,256.167 411.5,255.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 144.5,270.5 C 145.833,271.167 145.833,271.167 144.5,270.5 Z"/></g>
<g><path style="opacity:1" fill="#22201e" d="M 225.5,216.5 C 247.583,219.231 268.249,225.898 287.5,236.5C 289.507,234.467 291.507,232.467 293.5,230.5C 294.906,230.027 295.573,229.027 295.5,227.5C 296.167,227.5 296.833,227.5 297.5,227.5C 296.606,230.242 297.606,230.909 300.5,229.5C 301.452,231.045 301.785,232.712 301.5,234.5C 300.585,236.754 299.252,238.754 297.5,240.5C 296.667,276.829 296.167,313.162 296,349.5C 295.065,357.682 292.231,365.016 287.5,371.5C 286.118,372.801 284.452,373.634 282.5,374C 283.252,374.671 283.586,375.504 283.5,376.5C 272.573,387.751 259.239,391.917 243.5,389C 219.325,381.522 207.825,365.022 209,339.5C 208.333,313.833 208.333,288.167 209,262.5C 209.391,257.944 211.891,255.61 216.5,255.5C 219.037,255.435 221.037,256.435 222.5,258.5C 223.333,289.495 223.833,320.495 224,351.5C 227.652,365.323 236.485,373.323 250.5,375.5C 251.793,376.158 253.293,376.492 255,376.5C 257.821,376.592 260.321,375.926 262.5,374.5C 272.878,370.283 279.044,362.616 281,351.5C 281.5,315.835 281.667,280.168 281.5,244.5C 281.027,243.094 280.027,242.427 278.5,242.5C 272.117,238.977 265.451,235.977 258.5,233.5C 257.558,233.608 256.725,233.941 256,234.5C 251.175,245.334 243.342,248.501 232.5,244C 230.622,242.457 229.122,240.624 228,238.5C 226.992,240.259 225.492,241.426 223.5,242C 220.167,242.667 216.833,242.667 213.5,242C 209.903,240.048 206.569,237.881 203.5,235.5C 203.881,234.069 204.881,233.236 206.5,233C 204.249,233.213 202.249,232.213 200.5,230C 201.759,229.077 203.092,228.243 204.5,227.5C 203.995,226.081 202.995,225.415 201.5,225.5C 204.5,221.8 203.5,220.134 198.5,220.5C 198.5,220.167 198.5,219.833 198.5,219.5C 200.199,219.34 201.866,219.506 203.5,220C 204.833,221.333 204.833,222.667 203.5,224C 204.025,224.692 204.692,225.192 205.5,225.5C 206.258,224.189 207.258,223.689 208.5,224C 208.859,226.63 209.859,228.797 211.5,230.5C 211.5,231.167 211.833,231.5 212.5,231.5C 215.518,234.97 218.852,235.304 222.5,232.5C 223.965,230.401 225.299,228.234 226.5,226C 225.644,224.405 224.311,223.572 222.5,223.5C 223.429,222.685 224.429,221.852 225.5,221C 225.034,219.701 225.034,218.201 225.5,216.5 Z M 244.5,228.5 C 245.609,229.29 246.942,229.79 248.5,230C 247.663,231.011 247.33,232.178 247.5,233.5C 238.193,240.515 234.36,238.181 236,226.5C 238.778,227.325 241.611,227.992 244.5,228.5 Z M 213.5,222.5 C 216.43,223.299 219.43,223.632 222.5,223.5C 224.311,223.572 225.644,224.405 226.5,226C 225.299,228.234 223.965,230.401 222.5,232.5C 218.852,235.304 215.518,234.97 212.5,231.5C 212.19,228.287 212.523,225.287 213.5,222.5 Z"/></g>
<g><path style="opacity:0.184" fill="#a6a29e" d="M 278.5,242.5 C 280.027,242.427 281.027,243.094 281.5,244.5C 279.973,244.573 278.973,243.906 278.5,242.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 257.5,237.5 C 258.833,238.167 258.833,238.167 257.5,237.5 Z"/></g>
<g><path style="opacity:0.247" fill="#aca7a5" d="M 295.5,227.5 C 295.573,229.027 294.906,230.027 293.5,230.5C 293.427,228.973 294.094,227.973 295.5,227.5 Z"/></g>
<g><path style="opacity:0.306" fill="#7f7772" d="M 244.5,228.5 C 246.167,228.5 247.833,228.5 249.5,228.5C 249.598,230.553 248.931,232.22 247.5,233.5C 247.33,232.178 247.663,231.011 248.5,230C 246.942,229.79 245.609,229.29 244.5,228.5 Z"/></g>
<g><path style="opacity:0.114" fill="#bcb6b2" d="M 213.5,222.5 C 212.523,225.287 212.19,228.287 212.5,231.5C 211.833,231.5 211.5,231.167 211.5,230.5C 211.183,227.428 211.516,224.428 212.5,221.5C 213.107,221.624 213.44,221.957 213.5,222.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 202.5,272.5 C 203.833,273.167 203.833,273.167 202.5,272.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 32.5,280.5 C 33.8333,281.167 33.8333,281.167 32.5,280.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 255.5,283.5 C 256.833,284.167 256.833,284.167 255.5,283.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 239.5,290.5 C 240.833,291.167 240.833,291.167 239.5,290.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 110.5,295.5 C 111.833,296.167 111.833,296.167 110.5,295.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 405.5,295.5 C 406.833,296.167 406.833,296.167 405.5,295.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 330.5,302.5 C 331.833,303.167 331.833,303.167 330.5,302.5 Z"/></g>
<g><path style="opacity:0.342" fill="#837e7a" d="M 172.5,220.5 C 172.5,220.167 172.5,219.833 172.5,219.5C 175.167,219.5 177.833,219.5 180.5,219.5C 180.5,273.833 180.5,328.167 180.5,382.5C 179.501,328.669 179.168,274.669 179.5,220.5C 177.167,220.5 174.833,220.5 172.5,220.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 394.5,307.5 C 395.833,308.167 395.833,308.167 394.5,307.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 406.5,308.5 C 407.833,309.167 407.833,309.167 406.5,308.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 63.5,320.5 C 64.8333,321.167 64.8333,321.167 63.5,320.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 105.5,321.5 C 106.833,322.167 106.833,322.167 105.5,321.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 400.5,323.5 C 401.833,324.167 401.833,324.167 400.5,323.5 Z"/></g>
<g><path style="opacity:0.224" fill="#6b6662" d="M 200.5,235.5 C 198.735,236.461 196.735,236.795 194.5,236.5C 194.185,286.857 194.518,337.19 195.5,387.5C 194.732,386.737 194.232,385.737 194,384.5C 193.5,334.834 193.333,285.168 193.5,235.5C 195.833,235.5 198.167,235.5 200.5,235.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 492.5,372.5 C 493.833,373.167 493.833,373.167 492.5,372.5 Z"/></g>
<g><path style="opacity:1" fill="#706d68" d="M 287.5,371.5 C 286.92,373.749 285.587,375.415 283.5,376.5C 283.586,375.504 283.252,374.671 282.5,374C 284.452,373.634 286.118,372.801 287.5,371.5 Z"/></g>
<g><path style="opacity:0.471" fill="#89837d" d="M 262.5,374.5 C 260.321,375.926 257.821,376.592 255,376.5C 253.293,376.492 251.793,376.158 250.5,375.5C 254.534,375.495 258.534,375.162 262.5,374.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 308.5,385.5 C 309.833,386.167 309.833,386.167 308.5,385.5 Z"/></g>
<g><path style="opacity:0.039" fill="#cdc9c7" d="M 308.5,397.5 C 308.573,399.027 307.906,400.027 306.5,400.5C 306.427,398.973 307.094,397.973 308.5,397.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 384.5,401.5 C 385.833,402.167 385.833,402.167 384.5,401.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 130.5,431.5 C 131.833,432.167 131.833,432.167 130.5,431.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 129.5,437.5 C 130.833,438.167 130.833,438.167 129.5,437.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 172.5,437.5 C 173.833,438.167 173.833,438.167 172.5,437.5 Z"/></g>
<g><path style="opacity:0.998" fill="#1f1d1b" d="M 325.5,381.5 C 322.774,410.382 308.44,431.215 282.5,444C 280.564,444.813 278.564,445.313 276.5,445.5C 274.447,445.402 272.78,446.069 271.5,447.5C 243.945,453.656 220.111,446.99 200,427.5C 198.25,425.266 196.75,422.932 195.5,420.5C 197.557,421.202 199.557,421.535 201.5,421.5C 201.833,421.833 202.167,422.167 202.5,422.5C 200.252,423.324 200.086,424.324 202,425.5C 205.109,423.614 206.109,420.947 205,417.5C 204.667,418.167 204.333,418.833 204,419.5C 203.333,417.833 203.333,416.167 204,414.5C 207.123,416.098 207.956,415.431 206.5,412.5C 217.31,425.907 231.31,433.573 248.5,435.5C 253.65,436.651 258.984,436.817 264.5,436C 265.416,435.722 266.082,435.222 266.5,434.5C 284.985,429.357 298.318,418.024 306.5,400.5C 307.906,400.027 308.573,399.027 308.5,397.5C 309.598,393.089 310.598,388.755 311.5,384.5C 311.298,386.989 311.798,389.323 313,391.5C 315.788,388.226 318.621,387.559 321.5,389.5C 322.843,386.814 324.176,384.148 325.5,381.5 Z"/></g>
<g><path style="opacity:0.755" fill="#706a67" d="M 266.5,434.5 C 266.082,435.222 265.416,435.722 264.5,436C 258.984,436.817 253.65,436.651 248.5,435.5C 254.545,435.697 260.545,435.363 266.5,434.5 Z"/></g>
<g><path style="opacity:0.165" fill="#a6a19f" d="M 276.5,445.5 C 275.22,446.931 273.553,447.598 271.5,447.5C 272.78,446.069 274.447,445.402 276.5,445.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 496.5,448.5 C 497.833,449.167 497.833,449.167 496.5,448.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 485.5,449.5 C 486.833,450.167 486.833,450.167 485.5,449.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 295.5,468.5 C 296.833,469.167 296.833,469.167 295.5,468.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 31.5,477.5 C 32.8333,478.167 32.8333,478.167 31.5,477.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 78.5,478.5 C 79.8333,479.167 79.8333,479.167 78.5,478.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 135.5,485.5 C 136.833,486.167 136.833,486.167 135.5,485.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 67.5,492.5 C 68.8333,493.167 68.8333,493.167 67.5,492.5 Z"/></g>
<g><path style="opacity:0.004" fill="#fefffe" d="M 11.5,495.5 C 12.8333,496.167 12.8333,496.167 11.5,495.5 Z"/></g>
</svg>

After

Width:  |  Height:  |  Size: 29 KiB

+368
View File
@@ -0,0 +1,368 @@
import { memo, useState } from 'react';
import { Streamdown } from 'streamdown';
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2, Logs } from 'lucide-react';
import type { AIMessage } from '@/lib/SessionManager';
import { cn } from '@/lib/utils';
import { UserMessage } from '@/components/UserMessage';
import OpenAI from 'openai';
import { useTheme } from '@/hooks/useTheme';
// Type guard to check if message has reasoning content
function hasReasoningContent(message: AIMessage): message is AIMessage & { reasoning_content: string } {
return message.role === 'assistant' && 'reasoning_content' in message && typeof (message as { reasoning_content?: unknown }).reasoning_content === 'string';
}
interface AIMessageItemProps {
message: AIMessage;
isCurrentlyLoading?: boolean;
toolCall?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined; // Tool call data passed from the assistant message
}
export const AIMessageItem = memo(({
message,
isCurrentlyLoading = false,
toolCall,
}: AIMessageItemProps) => {
const [isToolExpanded, setIsToolExpanded] = useState(false);
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
const { displayTheme } = useTheme();
// Get content to display
const getContent = () => {
if (typeof message.content === 'string') {
return message.content;
}
if (Array.isArray(message.content)) {
// Handle array content (like images, text blocks)
return message.content
.map(item => {
if (typeof item === 'string') return item;
if (item.type === 'text') return item.text;
if (item.type === 'image_url') return `[Image: ${item.image_url.url}]`;
return '[Unknown content]';
})
.join('\n');
}
return '';
};
// Get tool info including icon and title
const getToolInfo = () => {
if (message.role === 'tool' && toolCall) {
if (toolCall.type === 'function') {
const toolName = toolCall.function.name;
let args;
try {
args = JSON.parse(toolCall.function.arguments);
} catch {
args = {};
}
// Generate icons and titles based on tool name and arguments
switch (toolName) {
case 'shell':
return {
icon: Terminal,
title: args.command ? args.command : 'Shell Command'
};
case 'text_editor_view': {
const title = args.path
? (args.start_line || args.end_line
? `Viewed ${args.path} (lines ${args.start_line || 1}-${args.end_line || 'end'})`
: `Viewed ${args.path}`)
: 'Viewed File';
return { icon: Eye, title };
}
case 'text_editor_write':
return {
icon: FileText,
title: args.path ? `Wrote ${args.path}` : 'Wrote File'
};
case 'text_editor_str_replace':
return {
icon: Edit,
title: args.path ? `Edited ${args.path}` : 'Edited File'
};
case 'npm_add_package': {
const installTitle = args.name
? (args.dev ? `Installed ${args.name} (dev)` : `Installed ${args.name}`)
: 'Installed Package';
return { icon: Package, title: installTitle };
}
case 'npm_remove_package':
return {
icon: PackageMinus,
title: args.name ? `Removed ${args.name}` : 'Removed Package'
};
case 'git_commit':
return {
icon: GitCommit,
title: args.message ? `Committed: ${args.message}` : 'Committed Changes'
};
case 'build_project':
return {
icon: Package,
title: 'Built Project'
};
case 'nostr_read_nip':
return {
icon: BookOpen,
title: args.nip ? `Read NIP-${args.nip}` : 'Read NIP'
};
case 'nostr_fetch_event':
return {
icon: Download,
title: args.identifier ? `Fetched ${args.identifier.slice(0, 16)}...` : 'Fetched Event'
};
case 'nostr_read_kind':
return {
icon: Hash,
title: args.kind !== undefined ? `Read Kind ${args.kind}` : 'Read Kind'
};
case 'nostr_read_tag':
return {
icon: Tag,
title: args.tag ? `Read Tag "${args.tag}"` : 'Read Tag'
};
case 'nostr_read_protocol':
return {
icon: Network,
title: args.doc ? `Read Protocol: ${args.doc}` : 'Read Protocol'
};
case 'nostr_read_nips_index':
return {
icon: List,
title: 'Read NIPs Index'
};
case 'nostr_generate_kind':
return {
icon: Plus,
title: args.range ? `Generated ${args.range} kind` : 'Generated Kind'
};
case 'deploy_project':
return {
icon: Globe,
title: args.deployServer ? `Deployed to ${args.deployServer}` : 'Deployed Project'
};
case 'typecheck':
return {
icon: CheckCircle,
title: 'TypeScript'
};
case 'read_console_messages':
return {
icon: Logs,
title: 'Read Console'
};
default:
return {
icon: Wrench,
title: toolName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())
};
}
}
}
// Fallback to extracting from content
if (message.role === 'tool') {
const content = getContent();
const lines = content.split('\n');
const firstLine = lines[0];
if (firstLine && firstLine.length < 100) {
return {
icon: Wrench,
title: firstLine.replace(/^(Error |Tool |Executing |Result: )/i, '').trim()
};
}
return { icon: Wrench, title: 'Tool Result' };
}
return { icon: Wrench, title: 'Tool' };
};
// Special rendering for tool messages
if (message.role === 'tool') {
const content = getContent();
const toolInfo = getToolInfo();
const IconComponent = toolInfo.icon;
// Get tool call arguments for special rendering
let toolArgs: Record<string, unknown> = {};
let toolName = '';
if (toolCall?.type === 'function') {
toolName = toolCall.function.name;
try {
toolArgs = JSON.parse(toolCall.function.arguments);
} catch {
toolArgs = {};
}
}
// Special rendering for tools
const renderSpecialContent = () => {
if (toolName === 'text_editor_write' && toolArgs.file_text) {
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
<div className="whitespace-pre-wrap break-words font-mono">
{toolArgs.file_text as string}
</div>
</div>
);
}
if (toolName === 'text_editor_str_replace' && toolArgs.old_str && toolArgs.new_str) {
const oldLines = (toolArgs.old_str as string).split('\n');
const newLines = (toolArgs.new_str as string).split('\n');
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs font-mono">
<div className="space-y-1">
{/* Old content (removed) */}
<div className="space-y-0">
{oldLines.map((line, index) => (
<div key={`old-${index}`} className="flex">
<span className="text-red-500 select-none mr-2">-</span>
<span className="bg-red-50 dark:bg-red-950/30 text-red-700 dark:text-red-300 flex-1 whitespace-pre-wrap break-words">
{line}
</span>
</div>
))}
</div>
{/* New content (added) */}
<div className="space-y-0">
{newLines.map((line, index) => (
<div key={`new-${index}`} className="flex">
<span className="text-green-500 select-none mr-2">+</span>
<span className="bg-green-50 dark:bg-green-950/30 text-green-700 dark:text-green-300 flex-1 whitespace-pre-wrap break-words">
{line}
</span>
</div>
))}
</div>
</div>
</div>
);
}
// Default rendering for other tools
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
<div className="whitespace-pre-wrap break-words font-mono">
{content}
</div>
</div>
);
};
// Regular tool message rendering
return (
<div className="-mt-2"> {/* -mt-2 to make it snug with the previous assistant message */}
<button
onClick={() => setIsToolExpanded(!isToolExpanded)}
className={cn(
"w-full flex items-center gap-2 px-2 py-1 text-xs",
"hover:bg-muted/30 rounded transition-colors duration-200"
)}
>
<IconComponent className="h-3 w-3 text-muted-foreground flex-shrink-0" />
<span className="text-muted-foreground font-medium truncate flex-1 text-left">
{toolInfo.title}
</span>
</button>
{isToolExpanded && renderSpecialContent()}
</div>
);
}
// Regular rendering for non-tool messages
if (message.role === 'user') {
// User messages: right-aligned bubble without avatar/name
const userContent = typeof message.content === 'string'
? message.content
: Array.isArray(message.content)
? message.content.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[]
: '';
return (
<div className="flex justify-end py-6">
<div className="max-w-[80%] bg-secondary rounded-2xl rounded-br-md px-4 py-3">
<div className="text-sm break-words">
<UserMessage content={userContent} />
</div>
</div>
</div>
);
}
// If there's no reasoning content and the main content is empty, render nothing
if (!hasReasoningContent(message) && !getContent().trim()) {
return null;
}
// Assistant messages: left-aligned without avatar/name
return (
<div className="flex">
<div className="flex-1 min-w-0">
<div className="text-sm space-y-3">
{/* Reasoning content display */}
{hasReasoningContent(message) && message.reasoning_content.trim() && (
<div>
<button
onClick={() => setIsReasoningExpanded(!isReasoningExpanded)}
className={cn(
"w-full flex items-center gap-2 px-2 py-1 text-xs",
"hover:bg-muted/30 rounded transition-colors duration-200"
)}
>
{!getContent().trim() && isCurrentlyLoading ? (
<Loader2 className="h-3 w-3 text-muted-foreground flex-shrink-0 animate-spin" />
) : (
<Lightbulb className="h-3 w-3 text-muted-foreground flex-shrink-0" />
)}
<span className="text-muted-foreground font-medium flex-1 text-left">
Thinking
</span>
</button>
{isReasoningExpanded && (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
<div className="whitespace-pre-wrap break-words">
<Streamdown
className='size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0'
parseIncompleteMarkdown={isCurrentlyLoading}
shikiTheme={displayTheme === 'dark' ? 'github-dark' : 'github-light'}
>
{message.reasoning_content}
</Streamdown>
</div>
</div>
)}
</div>
)}
{/* Main content display */}
{getContent().trim() && (
<div className="break-words">
<Streamdown
className='size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0'
parseIncompleteMarkdown={isCurrentlyLoading}
shikiTheme={displayTheme === 'dark' ? 'github-dark' : 'github-light'}
>
{getContent()}
</Streamdown>
</div>
)}
{/* Tool calls are now hidden from assistant messages */}
</div>
</div>
</div>
);
});
AIMessageItem.displayName = 'AIMessageItem';
+217
View File
@@ -0,0 +1,217 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { renderHook, act, waitFor } from '@testing-library/react';
import { useQueryClient } from '@tanstack/react-query';
import React from 'react';
import { useAISettings } from '@/hooks/useAISettings';
import { TestApp } from '@/test/TestApp';
// Mock localStorage
const localStorageMock = {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn(),
clear: vi.fn(),
};
Object.defineProperty(window, 'localStorage', {
value: localStorageMock,
});
// Mock the config utils
vi.mock('@/lib/configUtils', () => ({
readAISettings: vi.fn(),
writeAISettings: vi.fn(),
}));
describe('AISettingsProvider', () => {
beforeEach(async () => {
vi.clearAllMocks();
localStorageMock.getItem.mockReturnValue(null);
// Mock the read function to return default settings
const { readAISettings } = await import('@/lib/configUtils');
vi.mocked(readAISettings).mockResolvedValue({
providers: [],
recentlyUsedModels: [],
});
});
it('should initialize with empty recentlyUsedModels array', async () => {
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
await waitFor(() => {
expect(result.current.settings.recentlyUsedModels).toEqual([]);
});
});
it('should add recently used models correctly', async () => {
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
await waitFor(() => {
expect(result.current.settings.recentlyUsedModels).toEqual([]);
});
act(() => {
result.current.addRecentlyUsedModel('openrouter/anthropic/claude-3.5-sonnet');
});
expect(result.current.settings.recentlyUsedModels).toEqual([
'openrouter/anthropic/claude-3.5-sonnet'
]);
});
it('should move existing model to front when used again', async () => {
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
await waitFor(() => {
expect(result.current.settings.recentlyUsedModels).toEqual([]);
});
// Add multiple models
act(() => {
result.current.addRecentlyUsedModel('openrouter/anthropic/claude-3.5-sonnet');
result.current.addRecentlyUsedModel('openrouter/openai/gpt-4');
result.current.addRecentlyUsedModel('openrouter/google/gemini-pro');
});
expect(result.current.settings.recentlyUsedModels).toEqual([
'openrouter/google/gemini-pro',
'openrouter/openai/gpt-4',
'openrouter/anthropic/claude-3.5-sonnet'
]);
// Use the first model again - it should move to front
act(() => {
result.current.addRecentlyUsedModel('openrouter/anthropic/claude-3.5-sonnet');
});
expect(result.current.settings.recentlyUsedModels).toEqual([
'openrouter/anthropic/claude-3.5-sonnet',
'openrouter/google/gemini-pro',
'openrouter/openai/gpt-4'
]);
});
it('should limit recently used models to 10 items', async () => {
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
await waitFor(() => {
expect(result.current.settings.recentlyUsedModels).toEqual([]);
});
// Add 12 models
act(() => {
for (let i = 1; i <= 12; i++) {
result.current.addRecentlyUsedModel(`provider/model-${i}`);
}
});
// Should only keep the last 10
expect(result.current.settings.recentlyUsedModels).toHaveLength(10);
expect(result.current.settings.recentlyUsedModels[0]).toBe('provider/model-12');
expect(result.current.settings.recentlyUsedModels[9]).toBe('provider/model-3');
});
it('should migrate old settings without recentlyUsedModels', async () => {
const oldSettings = {
providers: [
{
id: 'openrouter',
baseURL: 'https://openrouter.ai/api/v1',
apiKey: 'test-key'
}
],
recentlyUsedModels: []
};
const { readAISettings } = await import('@/lib/configUtils');
vi.mocked(readAISettings).mockResolvedValue(oldSettings);
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
await waitFor(() => {
expect(result.current.settings.recentlyUsedModels).toEqual([]);
expect(result.current.settings.providers).toEqual(oldSettings.providers);
});
});
it('should invalidate provider-models query when updateSettings is called with providers', async () => {
// Mock the QueryClient.invalidateQueries method
const mockInvalidateQueries = vi.fn();
// Create a custom TestApp that mocks the query client
const MockedTestApp = ({ children }: { children: React.ReactNode }) => {
const queryClient = useQueryClient();
vi.spyOn(queryClient, 'invalidateQueries').mockImplementation(mockInvalidateQueries);
return <>{children}</>;
};
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => (
<TestApp>
<MockedTestApp>{children}</MockedTestApp>
</TestApp>
),
});
await waitFor(() => {
expect(result.current.settings.recentlyUsedModels).toEqual([]);
});
act(() => {
result.current.updateSettings({
providers: [
{
id: 'test-provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key'
}
]
});
});
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['provider-models'] });
});
it('should not invalidate provider-models query when updateSettings is called without providers', async () => {
// Mock the QueryClient.invalidateQueries method
const mockInvalidateQueries = vi.fn();
// Create a custom TestApp that mocks the query client
const MockedTestApp = ({ children }: { children: React.ReactNode }) => {
const queryClient = useQueryClient();
vi.spyOn(queryClient, 'invalidateQueries').mockImplementation(mockInvalidateQueries);
return <>{children}</>;
};
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => (
<TestApp>
<MockedTestApp>{children}</MockedTestApp>
</TestApp>
),
});
await waitFor(() => {
expect(result.current.settings.recentlyUsedModels).toEqual([]);
});
act(() => {
result.current.updateSettings({
recentlyUsedModels: ['test-model']
});
});
expect(mockInvalidateQueries).not.toHaveBeenCalled();
});
});
+116 -20
View File
@@ -1,44 +1,140 @@
import { useQueryClient } from '@tanstack/react-query';
import { ReactNode, useState, useEffect } from 'react';
import { AISettingsContext, type AISettings, type AISettingsContextType } from '@/contexts/AISettingsContext';
import { AISettingsContext, type AISettings, type AIProvider, type AISettingsContextType } from '@/contexts/AISettingsContext';
import { useFS } from '@/hooks/useFS';
import { readAISettings, writeAISettings } from '@/lib/configUtils';
interface AISettingsProviderProps {
children: ReactNode;
}
const DEFAULT_SETTINGS: AISettings = {
apiKey: '',
baseUrl: 'https://openrouter.ai/api/v1',
model: 'anthropic/claude-sonnet-4',
providers: [],
recentlyUsedModels: [],
};
const STORAGE_KEY = 'ai-settings';
export function AISettingsProvider({ children }: AISettingsProviderProps) {
const [settings, setSettings] = useState<AISettings>(() => {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
try {
return { ...DEFAULT_SETTINGS, ...JSON.parse(stored) };
} catch {
return DEFAULT_SETTINGS;
}
}
return DEFAULT_SETTINGS;
});
const queryClient = useQueryClient();
const { fs } = useFS();
const [settings, setSettings] = useState<AISettings>(DEFAULT_SETTINGS);
const [isInitialized, setIsInitialized] = useState(false);
// Initialize settings from VFS on mount
useEffect(() => {
localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
}, [settings]);
const initializeSettings = async () => {
try {
const settings = await readAISettings(fs);
setSettings(settings);
} catch (error) {
console.error('Failed to initialize AI settings:', error);
setSettings(DEFAULT_SETTINGS);
} finally {
setIsInitialized(true);
}
};
initializeSettings();
}, [fs]);
// Save settings to VFS whenever they change (but not during initialization)
useEffect(() => {
if (!isInitialized) return;
const saveSettings = async () => {
try {
await writeAISettings(fs, settings);
} catch (error) {
console.error('Failed to save AI settings:', error);
}
};
saveSettings();
}, [fs, settings, isInitialized]);
const updateSettings = (newSettings: Partial<AISettings>) => {
setSettings(prev => ({ ...prev, ...newSettings }));
// If providers are being updated, invalidate the provider-models query
if ('providers' in newSettings) {
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
}
};
const isConfigured = Boolean(settings.apiKey);
const setProvider = (provider: AIProvider) => {
setSettings(prev => {
const existingIndex = prev.providers.findIndex(p => p.id === provider.id);
if (existingIndex >= 0) {
// Update existing provider
return {
...prev,
providers: prev.providers.map(p =>
p.id === provider.id ? provider : p
),
};
} else {
// Add new provider
return {
...prev,
providers: [...prev.providers, provider],
};
}
});
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
};
const removeProvider = (id: string) => {
setSettings(prev => ({
...prev,
providers: prev.providers.filter(provider => provider.id !== id),
}));
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
};
const setProviders = (providers: AIProvider[]) => {
setSettings(prev => ({
...prev,
providers,
}));
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
};
const addRecentlyUsedModel = (modelId: string) => {
setSettings(prev => {
const existingIndex = prev.recentlyUsedModels.indexOf(modelId);
if (existingIndex === 0) {
return prev;
} else if (existingIndex === -1) {
// Add new model to front, keep only last 10
return {
...prev,
recentlyUsedModels: [modelId, ...prev.recentlyUsedModels].slice(0, 10),
}
} else {
// Move existing model to front
return {
...prev,
recentlyUsedModels: [
modelId,
...prev.recentlyUsedModels.filter((_, index) => index !== existingIndex)
]
}
}
});
};
const isConfigured = settings.providers.length > 0;
const contextValue: AISettingsContextType = {
settings,
updateSettings,
setProvider,
removeProvider,
setProviders,
addRecentlyUsedModel,
isConfigured,
};
+350
View File
@@ -0,0 +1,350 @@
import { useState, useEffect } from 'react';
import { ArrowRight, ArrowLeft, Download, Upload, ExternalLink, Sparkles } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
// import { useAISettings } from '@/hooks/useAISettings';
import { useAICredits } from '@/hooks/useAICredits';
// import { useLocalStorage } from '@/hooks/useLocalStorage';
interface Act1DialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
type DialogStep = 'welcome' | 'migration' | 'credits' | 'conclusion';
const SHAKESPEARE_PROVIDER = {
id: "shakespeare",
baseURL: "https://ai.shakespeare.diy/v1",
nostr: true,
};
// const MKSTACK_NSP_ADDR = '31999:4bcaa7b5606e3c14df05cd497e588f5d3fe559b4e9a425e8b418a43af1ffb015:mkstack';
export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
const [step, setStep] = useState<DialogStep>('welcome');
// const { setProvider, updateSettings } = useAISettings();
// // Get the selectedNSPAddr from localStorage
// const [selectedNSPAddr] = useLocalStorage<string | null>('selectedNSPAddr', null);
// Get user's credits
const { data: creditsData } = useAICredits(SHAKESPEARE_PROVIDER);
const handleGetStarted = async () => {
try {
// // Add Shakespeare provider to their config
// setProvider(SHAKESPEARE_PROVIDER);
// // Configure recently used models based on credits or NSP
// const hasCredits = creditsData?.amount && creditsData.amount > 0;
// const hasMKStackNSP = selectedNSPAddr === MKSTACK_NSP_ADDR;
// if (hasCredits || hasMKStackNSP) {
// // User has credits or MKStack NSP - set to shakespeare model
// updateSettings({ recentlyUsedModels: ['shakespeare/shakespeare'] });
// } else {
// // No credits - set to tybalt model (free)
// updateSettings({ recentlyUsedModels: ['shakespeare/tybalt'] });
// }
// Move to migration step
setStep('migration');
} catch (error) {
console.error('Failed to configure Shakespeare provider:', error);
}
};
const handleContinue = () => {
setStep('credits');
};
const handleCreditsNext = () => {
setStep('conclusion');
};
const handleFinish = () => {
// Mark that the user is a previous Act 1 user
localStorage.setItem('act1', 'true');
// Remove the selectedNSPAddr from localStorage
localStorage.removeItem('selectedNSPAddr');
onOpenChange(false);
};
const handleVisitAct1 = () => {
window.open('https://act1.shakespeare.diy', '_blank');
};
// Reset state when dialog opens/closes
useEffect(() => {
if (open) {
setStep('welcome');
}
}, [open]);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-hidden">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
{step === 'migration' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('welcome')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{step === 'credits' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('migration')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{step === 'conclusion' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('credits')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
</DialogTitle>
</DialogHeader>
<div className="overflow-y-auto max-h-[calc(90vh-120px)] pr-2">
<div className="space-y-6 py-4">
{step === 'welcome' && (
<div className="text-center space-y-6">
<div className="text-6xl mb-4">🎭✨</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Welcome to Act 2!
</h2>
<p className="text-lg text-muted-foreground max-w-lg mx-auto">
We're excited to see you again! Shakespeare has been completely rebuilt
with new features, improved performance, and a better development experience.
</p>
</div>
<Card className="max-w-lg mx-auto text-left">
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<span className="text-2xl">🔄</span>
What's Changed
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="flex items-start gap-3">
<Badge variant="secondary" className="mt-0.5">New</Badge>
<div>
<p className="font-medium">Use any AI Provider</p>
<p className="text-sm text-muted-foreground">Your browser connects to AI providers directly</p>
</div>
</div>
<div className="flex items-start gap-3">
<Badge variant="secondary" className="mt-0.5">New</Badge>
<div>
<p className="font-medium">Git Integration</p>
<p className="text-sm text-muted-foreground">Push to GitHub, Nostr relays, and more</p>
</div>
</div>
<div className="flex items-start gap-3">
<Badge variant="secondary" className="mt-0.5">New</Badge>
<div>
<p className="font-medium">Your Files</p>
<p className="text-sm text-muted-foreground">Files are stored on your device directly in your browser</p>
</div>
</div>
</CardContent>
</Card>
<div className="bg-amber-50 dark:bg-amber-950/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4 max-w-lg mx-auto">
<div className="flex items-start gap-3">
<span className="text-amber-600 dark:text-amber-400 text-lg">⚠️</span>
<div className="text-left">
<p className="font-medium text-amber-800 dark:text-amber-200">Act 2 is in Development</p>
<p className="text-sm text-amber-700 dark:text-amber-300">
While we're working hard to make Act 2 stable, you may encounter bugs.
Your Act 1 projects remain safe and accessible.
</p>
</div>
</div>
</div>
<Button
onClick={handleGetStarted}
size="lg"
className="gap-2"
>
Next
</Button>
</div>
)}
{step === 'migration' && (
<div className="space-y-6">
<div className="text-center space-y-3">
<h2 className="text-xl font-bold">Your Act 1 Projects & Credits</h2>
<p className="text-muted-foreground max-w-lg mx-auto">
All your Act 1 projects and credits are safe and still accessible.
Here's how to work with them in Act 2.
</p>
</div>
<div className="text-center">
<Button
variant="outline"
onClick={handleVisitAct1}
className="gap-2"
>
<ExternalLink className="h-4 w-4" />
Visit Act 1
</Button>
</div>
<div className="grid gap-4">
<Card>
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<Download className="h-5 w-5 text-green-500" />
Export from Act 1
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-sm text-muted-foreground">
In Act 1, you can export your projects as ZIP files using the project menu.
</p>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<Upload className="h-5 w-5 text-purple-500" />
Import to Act 2
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-sm text-muted-foreground">
In Act 2, use the "Import Project" option in the sidebar to upload your exported ZIP files.
</p>
</CardContent>
</Card>
</div>
<div className="flex justify-end pt-4">
<Button
onClick={handleContinue}
className="gap-2"
>
Continue
<ArrowRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
{step === 'credits' && (
<div className="text-center space-y-6">
<div className="text-6xl mb-4">💳</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold">Your Credits</h2>
<p className="text-lg text-muted-foreground max-w-md mx-auto">
Your Act 1 credits are still available through the Shakespeare AI provider.
</p>
</div>
<Card className="max-w-md mx-auto">
<CardContent className="pt-6">
{creditsData?.amount && creditsData.amount > 0 ? (
<div className="text-center space-y-4">
<div className="space-y-2">
<div className="text-3xl font-bold text-green-600 dark:text-green-400">
${creditsData.amount.toFixed(2)}
</div>
<p className="text-sm text-muted-foreground">
Available credits
</p>
</div>
<div className="bg-green-50 dark:bg-green-950/20 border border-green-200 dark:border-green-800 rounded-lg p-3">
<p className="text-sm text-green-800 dark:text-green-200">
✅ You're all set! We've configured the premium Shakespeare model for you.
</p>
</div>
</div>
) : (
<div className="text-center space-y-4">
<div className="space-y-2">
<div className="text-2xl">🆓</div>
<p className="font-medium">Free Access</p>
</div>
<div className="bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800 rounded-lg p-3">
<p className="text-sm text-blue-800 dark:text-blue-200">
You can continue using Shakespeare for free with the Tybalt model.
It's perfect for learning and building amazing projects!
</p>
</div>
</div>
)}
</CardContent>
</Card>
<div className="flex justify-end pt-4">
<Button
onClick={handleCreditsNext}
className="gap-2"
>
Continue
<ArrowRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
{step === 'conclusion' && (
<div className="text-center space-y-6">
<div className="text-5xl mb-4">🎉</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold">Welcome to the Future!</h2>
<p className="text-lg text-muted-foreground max-w-md mx-auto">
You're all up to speed with Act 2! Get ready to build amazing Nostr applications.
</p>
</div>
<div className="space-y-3">
<Button onClick={handleFinish} size="lg" className="gap-2">
<Sparkles className="h-4 w-4" />
Start Building in Act 2
</Button>
<div className="text-xs text-muted-foreground">
Remember: You can always access Act 1 at{' '}
<button
onClick={handleVisitAct1}
className="text-primary hover:underline"
>
act1.shakespeare.diy
</button>
</div>
</div>
</div>
)}
</div>
</div>
</DialogContent>
</Dialog>
);
}
+118
View File
@@ -0,0 +1,118 @@
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
GitBranch,
MoreHorizontal,
MessageSquarePlus,
History,
Folder,
} from 'lucide-react';
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
import { GitDialog } from '@/components/GitDialog';
interface ActionsMenuProps {
projectId: string;
projectName: string;
onNewChat: () => void;
onProjectDetails?: () => void;
isLoading?: boolean;
isBuildLoading?: boolean;
disabled?: boolean;
onFirstInteraction?: () => void;
}
export function ActionsMenu({
projectId,
projectName: _projectName,
onNewChat,
onProjectDetails,
isLoading = false,
isBuildLoading = false,
disabled = false,
onFirstInteraction: _onFirstInteraction,
}: ActionsMenuProps) {
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
const [gitDialogOpen, setGitDialogOpen] = useState(false);
const isAnyLoading = isLoading || isBuildLoading;
return (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
disabled={disabled}
>
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">Open menu</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem
onClick={onNewChat}
disabled={isLoading}
className="gap-2"
>
<MessageSquarePlus className="h-4 w-4" />
New Chat
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setGitHistoryOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<History className="h-4 w-4" />
Rollback
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setGitDialogOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<GitBranch className="h-4 w-4" />
Repository
</DropdownMenuItem>
<DropdownMenuItem
onClick={onProjectDetails}
disabled={isAnyLoading}
className="gap-2"
>
<Folder className="h-4 w-4" />
Project Details
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
{/* Dialogs */}
<GitDialog
projectId={projectId}
open={gitDialogOpen}
onOpenChange={setGitDialogOpen}
/>
<GitHistoryDialog
projectId={projectId}
open={gitHistoryOpen}
onOpenChange={setGitHistoryOpen}
/>
</>
);
}
+157
View File
@@ -0,0 +1,157 @@
import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { type Project } from '@/lib/ProjectsManager';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { ProjectSidebar } from '@/components/ProjectSidebar';
import { Button } from '@/components/ui/button';
import { Menu } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
interface AppLayoutProps {
children: React.ReactNode;
selectedProject?: Project | null;
title?: string;
showSidebar?: boolean;
headerContent?: React.ReactNode;
}
export function AppLayout({
children,
selectedProject = null,
showSidebar = true,
headerContent
}: AppLayoutProps) {
const [_projects, setProjects] = useState<Project[]>([]);
const projectsManager = useProjectsManager();
const navigate = useNavigate();
const isMobile = useIsMobile();
const [isSidebarVisible, setIsSidebarVisible] = useState(!isMobile);
// Track if we've set the initial state based on projects
const [hasSetInitialState, setHasSetInitialState] = useState(false);
const loadProjects = useCallback(async () => {
try {
await projectsManager.init();
const projectList = await projectsManager.getProjects();
setProjects(projectList);
// Set initial sidebar state based on projects and device type
if (!hasSetInitialState && !isMobile) {
// On desktop, show sidebar if there are projects
setIsSidebarVisible(projectList.length > 0);
setHasSetInitialState(true);
} else if (!hasSetInitialState && isMobile) {
// On mobile, always start hidden
setIsSidebarVisible(false);
setHasSetInitialState(true);
}
} catch (error) {
console.error('Failed to load projects:', error);
if (!hasSetInitialState) {
setHasSetInitialState(true);
}
}
}, [projectsManager, hasSetInitialState, isMobile]);
useEffect(() => {
loadProjects();
}, [loadProjects]);
const handleProjectSelect = (project: Project | null) => {
if (project) {
setIsSidebarVisible(false); // Collapse sidebar on mobile navigation
navigate(`/project/${project.id}`);
} else {
navigate('/');
}
};
if (isMobile) {
return (
<div className="min-h-dvh bg-gradient-to-br from-primary/5 to-accent/5">
{/* 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">
<div className="flex items-center space-x-2">
{showSidebar && (
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
aria-label="Toggle sidebar"
>
<Menu className="h-4 w-4" />
</Button>
)}
</div>
{headerContent}
</header>
{/* Mobile Sidebar Overlay - show if showSidebar is true and sidebar is visible */}
{showSidebar && isSidebarVisible && (
<div className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm">
{/* Backdrop - only covers the area not occupied by the sidebar */}
<div
className="absolute inset-0"
onClick={() => setIsSidebarVisible(false)}
/>
{/* Sidebar - positioned above the backdrop */}
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
<ProjectSidebar
selectedProject={selectedProject}
onSelectProject={(project) => {
setIsSidebarVisible(false); // Always collapse sidebar on mobile navigation
handleProjectSelect(project);
}}
onClose={() => setIsSidebarVisible(false)}
/>
</div>
</div>
)}
<div className="container mx-auto px-4 py-6 md:py-8">
{children}
</div>
</div>
);
}
return (
<div className="min-h-screen flex bg-background">
{/* Fixed Sidebar - show if showSidebar is true and sidebar is visible */}
{showSidebar && isSidebarVisible && (
<div className="w-80 border-r bg-sidebar transition-all duration-300">
<ProjectSidebar
selectedProject={selectedProject}
onSelectProject={handleProjectSelect}
className="h-screen sticky top-0"
onToggleSidebar={() => setIsSidebarVisible(false)}
/>
</div>
)}
{/* Main Content Area */}
<div className="flex-1 flex flex-col bg-background">
<div className="min-h-screen bg-gradient-to-br from-primary/5 to-accent/5 relative">
{/* Show open button when sidebar is collapsed */}
{showSidebar && !isSidebarVisible && (
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(true)}
className="absolute top-2 left-4 h-8 w-8 p-0 z-10 bg-transparent backdrop-blur-sm hover:bg-transparent text-foreground/70 hover:text-foreground"
aria-label="Open sidebar"
>
<Menu className="h-4 w-4" />
</Button>
)}
<div className="container mx-auto px-4 py-6 md:py-8">
{children}
</div>
</div>
</div>
</div>
);
}
+17 -2
View File
@@ -2,6 +2,7 @@ import { ReactNode, useEffect } from 'react';
import { z } from 'zod';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext';
import i18n from '@/lib/i18n';
interface AppProviderProps {
children: ReactNode;
@@ -17,6 +18,8 @@ interface AppProviderProps {
const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
theme: z.enum(['dark', 'light', 'system']),
relayUrl: z.string().url(),
deployServer: z.string().min(1),
language: z.string().optional(),
});
export function AppProvider(props: AppProviderProps) {
@@ -54,6 +57,9 @@ export function AppProvider(props: AppProviderProps) {
// Apply theme effects to document
useApplyTheme(config.theme);
// Apply language effects to i18n
useApplyLanguage(config.language);
return (
<AppContext.Provider value={appContextValue}>
{children}
@@ -88,11 +94,11 @@ function useApplyTheme(theme: Theme) {
if (theme !== 'system') return;
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleChange = () => {
const root = window.document.documentElement;
root.classList.remove('light', 'dark');
const systemTheme = mediaQuery.matches ? 'dark' : 'light';
root.classList.add(systemTheme);
};
@@ -100,4 +106,13 @@ function useApplyTheme(theme: Theme) {
mediaQuery.addEventListener('change', handleChange);
return () => mediaQuery.removeEventListener('change', handleChange);
}, [theme]);
}
/**
* Hook to apply language changes to i18n
*/
function useApplyLanguage(language?: string): void {
useEffect(() => {
i18n.changeLanguage(language ?? navigator.language);
}, [language]);
}
+75
View File
@@ -0,0 +1,75 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { CreditsBadge } from './CreditsBadge';
// Mock the useAICredits hook
vi.mock('@/hooks/useAICredits', () => ({
useAICredits: () => ({
data: { amount: 10.50 },
isLoading: false,
error: null,
}),
}));
// Mock the fetch function
global.fetch = vi.fn();
const mockProvider = {
id: 'test-provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
};
describe('CreditsBadge', () => {
it('renders the credits amount', () => {
render(
<TestApp>
<CreditsBadge provider={mockProvider} />
</TestApp>
);
expect(screen.getByText('$10.50')).toBeInTheDocument();
});
it('calls onOpenDialog when badge is clicked', () => {
const mockCallback = vi.fn();
render(
<TestApp>
<CreditsBadge
provider={mockProvider}
onOpenDialog={mockCallback}
/>
</TestApp>
);
const badge = screen.getByText('$10.50');
fireEvent.click(badge);
expect(mockCallback).toHaveBeenCalled();
});
it('has proper styling for clickable badge', () => {
render(
<TestApp>
<CreditsBadge provider={mockProvider} />
</TestApp>
);
const badge = screen.getByText('$10.50');
expect(badge).toHaveClass('cursor-pointer');
expect(badge).toHaveClass('hover:bg-secondary/80');
});
it('does not render dialog directly', () => {
render(
<TestApp>
<CreditsBadge provider={mockProvider} />
</TestApp>
);
// Dialog should not be rendered by CreditsBadge itself
expect(screen.queryByText('Credits - test-provider')).not.toBeInTheDocument();
});
});
+47
View File
@@ -0,0 +1,47 @@
import { Badge } from '@/components/ui/badge';
import { AIProvider } from '@/contexts/AISettingsContext';
import { useAICredits } from '@/hooks/useAICredits';
interface CreditsBadgeProps {
provider: AIProvider;
className?: string;
onOpenDialog?: () => void;
}
/**
* Displays a clickable credits badge showing the remaining credits for an AI provider
*/
export function CreditsBadge({ provider, className, onOpenDialog }: CreditsBadgeProps) {
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
if (!credits) {
return null;
}
// Format the amount as currency
const formattedAmount = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(credits.amount);
return (
<Badge
variant="secondary"
className={`cursor-pointer hover:bg-secondary/80 transition-colors ${className}`}
onClick={(e) => {
e.stopPropagation();
onOpenDialog?.();
}}
>
{formattedAmount}
</Badge>
);
}
+108
View File
@@ -0,0 +1,108 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { CreditsDialog } from './CreditsDialog';
import type { AIProvider } from '@/contexts/AISettingsContext';
// Mock the fetch function
global.fetch = vi.fn();
const mockProvider: AIProvider = {
id: 'test-provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
nostr: false,
};
describe('CreditsDialog', () => {
it('renders dialog when open', () => {
render(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={() => {}}
provider={mockProvider}
/>
</TestApp>
);
expect(screen.getByText('Credits')).toBeInTheDocument();
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
expect(screen.getByText('Recent Transactions')).toBeInTheDocument();
});
it('does not render when closed', () => {
render(
<TestApp>
<CreditsDialog
open={false}
onOpenChange={() => {}}
provider={mockProvider}
/>
</TestApp>
);
expect(screen.queryByText('Credits')).not.toBeInTheDocument();
});
it('shows payment method options', () => {
render(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={() => {}}
provider={mockProvider}
/>
</TestApp>
);
expect(screen.getByText('Payment Method')).toBeInTheDocument();
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
});
it('shows preset amount buttons', () => {
render(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={() => {}}
provider={mockProvider}
/>
</TestApp>
);
expect(screen.getByText('$5')).toBeInTheDocument();
expect(screen.getByText('$10')).toBeInTheDocument();
expect(screen.getByText('$25')).toBeInTheDocument();
expect(screen.getByText('$50')).toBeInTheDocument();
expect(screen.getByText('$100')).toBeInTheDocument();
});
it('calls onDialogStateChange callback when dialog state changes', () => {
const mockCallback = vi.fn();
const { rerender } = render(
<TestApp>
<CreditsDialog
open={false}
onOpenChange={mockCallback}
provider={mockProvider}
/>
</TestApp>
);
// Simulate opening the dialog
rerender(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={mockCallback}
provider={mockProvider}
/>
</TestApp>
);
expect(screen.getByText('Credits')).toBeInTheDocument();
});
});
+600
View File
@@ -0,0 +1,600 @@
import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import QRCode from 'qrcode';
import { CreditCard, Zap, ExternalLink, RefreshCw, Check, X, Clock, AlertCircle, Copy, RotateCcw, ArrowLeft } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Skeleton } from '@/components/ui/skeleton';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useToast } from '@/hooks/useToast';
import { createAIClient } from '@/lib/ai-client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { AIProvider } from '@/contexts/AISettingsContext';
interface CreditsDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
provider: AIProvider;
}
interface Payment {
object: 'payment';
id: string;
status: 'pending' | 'completed' | 'failed' | 'expired';
amount: number;
fee: number;
total: number;
method: 'stripe' | 'lightning';
description: string;
url: string;
created_at: number;
completed_at?: number;
expires_at: number;
}
interface PaymentsResponse {
object: 'list';
data: Payment[];
has_more: boolean;
url: string;
}
interface AddCreditsRequest {
amount: number;
method: 'stripe' | 'lightning';
redirect_url?: string;
}
const PRESET_AMOUNTS = [5, 10, 25, 50, 100];
interface LightningPaymentProps {
invoice: string;
amount: number;
onClose: () => void;
}
function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) {
const [qrDataUrl, setQrDataUrl] = useState<string>('');
const [isWebLNAvailable, setIsWebLNAvailable] = useState(false);
const [isPayingWithWebLN, setIsPayingWithWebLN] = useState(false);
const [showCopiedTooltip, setShowCopiedTooltip] = useState(false);
const { toast } = useToast();
useEffect(() => {
// Generate QR code
QRCode.toDataURL(invoice, {
width: 256,
margin: 2,
color: {
dark: '#000000',
light: '#ffffff',
},
})
.then(setQrDataUrl)
.catch(console.error);
// Check for WebLN availability
setIsWebLNAvailable(typeof window !== 'undefined' && 'webln' in window);
}, [invoice]);
const handleWebLNPay = async () => {
if (!window.webln) return;
try {
setIsPayingWithWebLN(true);
await window.webln.enable();
await window.webln.sendPayment(invoice);
toast({
title: 'Payment sent!',
description: 'Your Lightning payment has been sent successfully.',
});
onClose();
} catch (error) {
console.error('WebLN payment failed:', error);
toast({
title: 'Payment failed',
description: error instanceof Error ? error.message : 'Failed to send Lightning payment',
variant: 'destructive',
});
} finally {
setIsPayingWithWebLN(false);
}
};
const handleCopyInvoice = () => {
navigator.clipboard.writeText(invoice);
setShowCopiedTooltip(true);
setTimeout(() => setShowCopiedTooltip(false), 2000);
};
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(amount);
};
return (
<div className="space-y-4">
<div className="text-center">
<h3 className="text-lg font-semibold mb-2">Lightning Payment</h3>
<p className="text-sm text-muted-foreground">
Pay {formatCurrency(amount)} with Lightning Network
</p>
</div>
{/* QR Code */}
<div className="flex justify-center">
{qrDataUrl ? (
<div className="p-4 bg-white rounded-lg border">
<img src={qrDataUrl} alt="Lightning Invoice QR Code" className="w-48 h-48" />
</div>
) : (
<div className="w-48 h-48 bg-muted rounded-lg flex items-center justify-center">
<RefreshCw className="h-6 w-6 animate-spin" />
</div>
)}
</div>
{/* Payment Buttons */}
<div className="space-y-2">
{isWebLNAvailable && (
<Button
onClick={handleWebLNPay}
disabled={isPayingWithWebLN}
className="w-full"
size="lg"
>
{isPayingWithWebLN && <RefreshCw className="h-4 w-4 mr-2 animate-spin" />}
<Zap className="h-4 w-4 mr-2" />
Pay with WebLN
</Button>
)}
<div className="relative">
<Button
variant="outline"
onClick={handleCopyInvoice}
className="w-full"
size="lg"
>
<Copy className="h-4 w-4 mr-2" />
Copy Invoice
</Button>
{showCopiedTooltip && (
<div className="absolute -top-10 left-1/2 transform -translate-x-1/2 bg-foreground text-background text-xs px-2 py-1 rounded shadow-lg z-10 animate-in fade-in-0 duration-200">
Copied!
<div className="absolute top-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent border-t-foreground"></div>
</div>
)}
</div>
</div>
</div>
);
}
export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogProps) {
const { user } = useCurrentUser();
const { toast } = useToast();
const queryClient = useQueryClient();
const [amount, setAmount] = useState<number>(10);
const [paymentMethod, setPaymentMethod] = useState<'stripe' | 'lightning'>('stripe');
const [lightningInvoice, setLightningInvoice] = useState<string | null>(null);
const [refreshingPayments, setRefreshingPayments] = useState<Set<string>>(new Set());
// Query for payment history
const { data: payments, isLoading: isLoadingPayments } = useQuery({
queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
queryFn: async (): Promise<Payment[]> => {
const ai = createAIClient(provider, user);
const data = await ai.get('/credits/payments?limit=50') as PaymentsResponse;
return data.data;
},
enabled: open,
retry: false,
refetchOnWindowFocus: false,
});
// Mutation for adding credits
const addCreditsMutation = useMutation({
mutationFn: async (request: AddCreditsRequest): Promise<Payment> => {
const ai = createAIClient(provider, user);
return await ai.post('/credits/add', {
body: request,
}) as Payment;
},
onSuccess: (payment) => {
if (payment.method === 'stripe') {
// Open Stripe checkout in new window
window.open(payment.url, '_blank');
toast({
title: 'Payment initiated',
description: 'Stripe checkout opened in a new window.',
});
} else if (payment.method === 'lightning') {
// Show Lightning payment interface
setLightningInvoice(payment.url);
}
// Refresh payments list
queryClient.invalidateQueries({
queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
});
// Refresh credits balance
queryClient.invalidateQueries({
queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
});
},
onError: (error: Error) => {
const errorMessage = error?.message || 'Failed to initiate payment';
toast({
title: 'Payment failed',
description: errorMessage,
variant: 'destructive',
});
},
});
// Mutation for checking payment status
const checkPaymentMutation = useMutation({
mutationFn: async (paymentId: string): Promise<Payment> => {
const ai = createAIClient(provider, user);
return await ai.get(`/credits/payments/${paymentId}`) as Payment;
},
onMutate: async (paymentId: string) => {
// Add this payment to the refreshing set
setRefreshingPayments(prev => new Set(prev).add(paymentId));
},
onSuccess: (updatedPayment) => {
// Remove from refreshing set
setRefreshingPayments(prev => {
const newSet = new Set(prev);
newSet.delete(updatedPayment.id);
return newSet;
});
// Update the specific payment in the cache instead of refetching
queryClient.setQueryData<Payment[]>(
['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
(oldPayments) => {
if (!oldPayments) return oldPayments;
return oldPayments.map(payment =>
payment.id === updatedPayment.id ? updatedPayment : payment
);
}
);
// If payment completed, refresh credits balance
if (updatedPayment.status === 'completed') {
queryClient.invalidateQueries({
queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
});
toast({
title: 'Payment completed!',
description: `${formatCurrency(updatedPayment.amount)} has been added to your account.`,
});
} else if (updatedPayment.status === 'failed') {
toast({
title: 'Payment failed',
description: 'The payment has failed. Please try again.',
variant: 'destructive',
});
} else if (updatedPayment.status === 'expired') {
toast({
title: 'Payment expired',
description: 'The payment has expired. Please create a new payment.',
variant: 'destructive',
});
}
},
onError: (error: Error, paymentId: string) => {
// Remove from refreshing set on error
setRefreshingPayments(prev => {
const newSet = new Set(prev);
newSet.delete(paymentId);
return newSet;
});
const errorMessage = error?.message || 'Failed to check payment status';
toast({
title: 'Refresh failed',
description: errorMessage,
variant: 'destructive',
});
},
});
const handleAddCredits = () => {
if (amount <= 0) {
toast({
title: 'Invalid amount',
description: 'Please enter a valid amount.',
variant: 'destructive',
});
return;
}
const request: AddCreditsRequest = {
amount,
method: paymentMethod,
};
if (paymentMethod === 'stripe') {
request.redirect_url = window.location.origin + '/settings/ai';
}
addCreditsMutation.mutate(request);
};
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(amount);
};
const formatDate = (timestamp: number) => {
const date = new Date(timestamp * 1000);
const now = new Date();
const diffDays = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60 * 24));
if (diffDays === 0) {
return new Intl.DateTimeFormat('en-US', {
hour: '2-digit',
minute: '2-digit',
}).format(date);
} else if (diffDays === 1) {
return 'Yesterday';
} else if (diffDays < 7) {
return new Intl.DateTimeFormat('en-US', {
weekday: 'short',
}).format(date);
} else {
return new Intl.DateTimeFormat('en-US', {
month: 'short',
day: 'numeric',
}).format(date);
}
};
const getStatusIcon = (status: Payment['status']) => {
switch (status) {
case 'completed':
return <Check className="h-4 w-4 text-green-600" />;
case 'failed':
return <X className="h-4 w-4 text-red-600" />;
case 'expired':
return <AlertCircle className="h-4 w-4 text-orange-600" />;
case 'pending':
default:
return <Clock className="h-4 w-4 text-yellow-600" />;
}
};
const getStatusVariant = (status: Payment['status']): "default" | "secondary" | "destructive" | "outline" => {
switch (status) {
case 'completed':
return 'default';
case 'failed':
return 'destructive';
case 'expired':
return 'secondary';
case 'pending':
default:
return 'outline';
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent onOpenAutoFocus={(e) => e.preventDefault()} className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-full max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none">
<DialogHeader className="flex-shrink-0">
<DialogTitle className="flex items-center gap-2 text-lg">
{lightningInvoice ? (
<>
<button
onClick={() => setLightningInvoice(null)}
className="flex items-center gap-2 hover:opacity-70 transition-opacity"
>
<ArrowLeft className="h-5 w-5" />
Back
</button>
</>
) : (
<>
<CreditCard className="h-5 w-5" />
Credits
</>
)}
</DialogTitle>
</DialogHeader>
{/* Lightning Payment Interface */}
{lightningInvoice ? (
<div className="flex-1 overflow-y-auto px-1 -mx-1">
<LightningPayment
invoice={lightningInvoice}
amount={amount}
onClose={() => setLightningInvoice(null)}
/>
</div>
) : (
<div className="flex-1 flex flex-col min-h-0">
{/* Add Credits Form - Fixed size section */}
<div className="flex-shrink-0 space-y-4 px-1 -mx-1">
<div className="space-y-3">
<Label htmlFor="amount" className="text-sm font-medium">Amount (USD)</Label>
<div className="space-y-3">
<Input
id="amount"
type="number"
step="0.01"
value={amount}
onChange={(e) => setAmount(Number(e.target.value))}
placeholder="Enter amount"
className="text-center text-lg font-medium"
/>
<div className="grid grid-cols-5 gap-2">
{PRESET_AMOUNTS.map((preset) => (
<Button
key={preset}
variant={amount === preset ? "default" : "outline"}
size="sm"
onClick={() => setAmount(preset)}
className="text-xs"
>
${preset}
</Button>
))}
</div>
</div>
</div>
<div className="space-y-3">
<Label htmlFor="payment-method" className="text-sm font-medium">Payment Method</Label>
<Select value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="stripe">
<div className="flex items-center gap-2">
<CreditCard className="h-4 w-4" />
Credit Card
</div>
</SelectItem>
<SelectItem value="lightning">
<div className="flex items-center gap-2">
<Zap className="h-4 w-4" />
Lightning
</div>
</SelectItem>
</SelectContent>
</Select>
</div>
<Button
onClick={handleAddCredits}
disabled={amount <= 0 || addCreditsMutation.isPending}
className="w-full h-12 text-base font-medium"
size="lg"
>
{addCreditsMutation.isPending && <RefreshCw className="h-4 w-4 mr-2 animate-spin" />}
{paymentMethod === 'stripe' ? 'Pay with Card' : 'Generate Invoice'}
{amount > 0 && ` - ${formatCurrency(amount)}`}
</Button>
</div>
<div className="flex-shrink-0 px-1 -mx-1 py-4">
<Separator />
</div>
{/* Transaction History - Flexible section */}
<div className="flex-1 min-h-0 flex flex-col px-1 -mx-1">
<div className="flex-shrink-0 mb-4">
<h3 className="text-base font-semibold">Recent Transactions</h3>
</div>
<div className="flex-1 min-h-0 overflow-y-auto">
{isLoadingPayments ? (
<div className="p-3 border rounded-lg space-y-2">
<div className="flex items-center gap-2">
<Skeleton className="h-4 w-4 rounded" />
<Skeleton className="h-4 w-24" />
<Skeleton className="h-4 w-16 ml-auto" />
</div>
<Skeleton className="h-3 w-32" />
</div>
) : !payments || payments.length === 0 ? (
<div className="flex-1 flex items-center justify-center">
<div className="text-center text-muted-foreground">
<CreditCard className="h-10 w-10 mx-auto mb-3 opacity-50" />
<p className="text-sm">No transactions yet</p>
<p className="text-xs">Your payment history will appear here</p>
</div>
</div>
) : (
<div className="space-y-2 pb-2">
{payments.map((payment) => (
<div
key={payment.id}
className="p-3 border rounded-lg space-y-2 hover:bg-muted/30 transition-colors"
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 min-w-0 flex-1">
{getStatusIcon(payment.status)}
<span className="text-sm font-medium truncate">
{payment.method === 'stripe' ? 'Credit Card' : 'Lightning'}
</span>
<Badge variant={getStatusVariant(payment.status)} className="text-xs flex-shrink-0">
{payment.status}
</Badge>
</div>
<div className="text-right flex-shrink-0">
<p className="text-sm font-medium">{formatCurrency(payment.amount)}</p>
{payment.fee > 0 && (
<p className="text-xs text-muted-foreground">
+{formatCurrency(payment.fee)}
</p>
)}
</div>
</div>
<div className="flex items-center justify-between text-xs text-muted-foreground">
<span>{formatDate(payment.created_at)}</span>
{payment.status === 'pending' && (
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => checkPaymentMutation.mutate(payment.id)}
disabled={refreshingPayments.has(payment.id)}
className="h-6 px-2 text-xs"
title="Refresh payment status"
>
<RotateCcw className={`h-3 w-3 ${refreshingPayments.has(payment.id) ? 'animate-spin' : ''}`} />
</Button>
{payment.url && (
<Button
variant="ghost"
size="sm"
onClick={() => {
if (payment.method === 'lightning') {
setLightningInvoice(payment.url);
} else {
window.open(payment.url, '_blank');
}
}}
className="h-6 px-2 text-xs"
>
<ExternalLink className="h-3 w-3 mr-1" />
{payment.method === 'lightning' ? 'Pay' : 'Pay'}
</Button>
)}
</div>
)}
</div>
</div>
))}
</div>
)}
</div>
</div>
</div>
)}
</DialogContent>
</Dialog>
);
}
+182
View File
@@ -0,0 +1,182 @@
import { useState, useEffect } from 'react';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useToast } from '@/hooks/useToast';
import { useAppContext } from '@/hooks/useAppContext';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useMutation } from '@tanstack/react-query';
import { deployProject } from '@/lib/deploy';
import { useFS } from '@/hooks/useFS';
import {
CloudUpload,
Loader2,
} from 'lucide-react';
interface DeployDialogProps {
projectId: string;
projectName: string;
open: boolean;
onOpenChange: (open: boolean) => void;
onFirstInteraction?: () => void;
}
export function DeployDialog({
projectId,
projectName,
open,
onOpenChange,
onFirstInteraction
}: DeployDialogProps) {
const { config } = useAppContext();
const { user } = useCurrentUser();
const { fs } = useFS();
const { toast } = useToast();
// State for the deploy URL input
const [deployUrl, setDeployUrl] = useState('');
// Initialize deploy URL when dialog opens
useEffect(() => {
if (open) {
setDeployUrl(`${projectId}.${config.deployServer}`);
}
}, [open, projectId, config.deployServer]);
const deployMutation = useMutation({
mutationFn: async () => {
if (!user) {
throw new Error("You must be logged into Nostr to deploy a project");
}
// Parse the deploy URL to extract hostname and server
const hostname = deployUrl.trim();
const parts = hostname.split('.');
if (parts.length < 2) {
throw new Error("Invalid deploy URL format. Please use format: subdomain.domain.com");
}
// Extract the deploy server (everything after the first dot)
const deployServer = parts.slice(1).join('.');
return await deployProject({
fs,
projectId, // Keep the original projectId for file path
deployServer,
projectPath: `/projects/${projectId}`,
signer: user.signer,
customHostname: hostname, // Pass the custom hostname
});
},
onSuccess: (result) => {
toast({
title: "Deployment successful!",
description: `Your project is now live at ${result.hostname}`,
});
// Open the deployed site in a new tab
window.open(result.url, '_blank');
// Close the dialog
onOpenChange(false);
},
onError: (error) => {
toast({
title: "Deployment failed",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
},
});
const handleDeploy = () => {
if (onFirstInteraction) {
onFirstInteraction();
}
deployMutation.mutate();
};
const handleUrlChange = (value: string) => {
// Remove protocol if user enters it
const cleanValue = value.replace(/^https?:\/\//, '');
setDeployUrl(cleanValue);
};
const isValidUrl = () => {
const trimmed = deployUrl.trim();
return trimmed.length > 0 && trimmed.includes('.') && !trimmed.startsWith('.') && !trimmed.endsWith('.');
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<CloudUpload className="h-5 w-5" />
Deploy "{projectName}"
</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="deploy-url">Deploy URL</Label>
<div className="relative">
<span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground">
https://
</span>
<Input
id="deploy-url"
value={deployUrl}
onChange={(e) => handleUrlChange(e.target.value)}
placeholder={`${projectId}.${config.deployServer}`}
className="pl-16"
disabled={deployMutation.isPending}
/>
</div>
<p className="text-xs text-muted-foreground">
Your project will be deployed to this URL. You can customize the subdomain.
</p>
</div>
{!user && (
<div className="p-3 bg-muted rounded-lg">
<p className="text-sm text-muted-foreground">
You must be logged into Nostr to deploy projects.
</p>
</div>
)}
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={deployMutation.isPending}
>
Cancel
</Button>
<Button
onClick={handleDeploy}
disabled={!user || !isValidUrl() || deployMutation.isPending}
className="gap-2"
>
{deployMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<CloudUpload className="h-4 w-4" />
)}
{deployMutation.isPending ? 'Deploying...' : 'Deploy'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+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>
);
}
+193
View File
@@ -0,0 +1,193 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { GitDialog } from './GitDialog';
// Mock the hooks
const mockRefetch = vi.fn();
const mockUseGitStatus = vi.fn();
const baseGitStatus = {
isGitRepo: true,
currentBranch: 'main',
hasUncommittedChanges: false,
changedFiles: [],
totalCommits: 5,
remotes: [{ name: 'origin', url: 'https://github.com/example/repo.git' }],
latestCommit: {
oid: 'abc123def456',
message: 'Initial commit',
author: {
name: 'Test User',
email: '[email protected]',
timestamp: Date.now() / 1000,
},
},
ahead: 0,
behind: 0,
};
vi.mock('@/hooks/useGitStatus', () => ({
useGitStatus: () => mockUseGitStatus(),
}));
vi.mock('@/hooks/useFS', () => ({
useFS: vi.fn(() => ({
fs: {},
})),
}));
vi.mock('@/hooks/useToast', () => ({
useToast: vi.fn(() => ({
toast: vi.fn(),
})),
}));
const mockUseGitSettings = vi.fn();
vi.mock('@/hooks/useGitSettings', () => ({
useGitSettings: () => mockUseGitSettings(),
}));
describe('GitDialog', () => {
beforeEach(() => {
mockUseGitStatus.mockReturnValue({
data: baseGitStatus,
refetch: mockRefetch,
});
mockUseGitSettings.mockReturnValue({
settings: {
credentials: {
'https://github.com': {
username: 'git',
password: 'github-token',
},
},
},
});
});
it('renders git dialog without repository information section', () => {
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
expect(screen.getByText('Repository')).toBeInTheDocument();
expect(screen.queryByText('Repository Information')).not.toBeInTheDocument();
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
});
it('shows sync status', () => {
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
expect(screen.getByText('Sync Status')).toBeInTheDocument();
expect(screen.getByText('Up to date')).toBeInTheDocument();
expect(screen.getByText('Pull')).toBeInTheDocument();
expect(screen.getByText('Push')).toBeInTheDocument();
});
it('shows clean working directory when no changes', () => {
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
expect(screen.getByText('Working directory is clean')).toBeInTheDocument();
expect(screen.getByText('No uncommitted changes')).toBeInTheDocument();
});
it('enables push button when there are commits ahead', () => {
// Mock git status with commits ahead
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
ahead: 2,
},
refetch: mockRefetch,
});
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
const pushButton = screen.getByText('Push');
expect(pushButton).toBeInTheDocument();
expect(pushButton.closest('button')).not.toBeDisabled();
});
it('disables push button when no commits ahead', () => {
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
const pushButton = screen.getByText('Push');
expect(pushButton).toBeInTheDocument();
expect(pushButton.closest('button')).toBeDisabled();
});
it('does not show credentials warning when credentials are configured', () => {
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
// Should not show warning when credentials are configured
expect(screen.queryByText(/No credentials configured/)).not.toBeInTheDocument();
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
});
it('shows credentials warning when no credentials are configured', () => {
// Mock git settings with no credentials and mock git status with an https remote
mockUseGitSettings.mockReturnValue({
settings: {
credentials: {},
},
});
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
remotes: [{ name: 'origin', url: 'https://github.com/example/repo.git' }],
},
refetch: mockRefetch,
});
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
// Should show warning when credentials are missing
expect(screen.getByText(/You are not logged into github.com/)).toBeInTheDocument();
expect(screen.getByText('log in')).toBeInTheDocument();
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
});
});
+805
View File
@@ -0,0 +1,805 @@
import { useState, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
GitBranch,
Upload,
Download,
Loader2,
CheckCircle,
AlertCircle,
Clock,
FileIcon,
Plus,
Minus,
Edit,
AlertTriangle,
Zap,
Save,
} from 'lucide-react';
import { useGitStatus } from '@/hooks/useGitStatus';
import { useGitSettings } from '@/hooks/useGitSettings';
import { useGit } from '@/hooks/useGit';
import { useToast } from '@/hooks/useToast';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostr } from '@nostrify/react';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { cn } from '@/lib/utils';
import { findCredentialsForRepo } from '@/lib/gitCredentials';
import { nip19 } from 'nostr-tools';
const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev"];
interface GitDialogProps {
projectId: string;
children?: React.ReactNode;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
export function GitDialog({ projectId, children, open, onOpenChange }: GitDialogProps) {
const [isPushing, setIsPushing] = useState(false);
const [isPulling, setIsPulling] = useState(false);
const [isPushingToNostr, setIsPushingToNostr] = useState(false);
const [originUrl, setOriginUrl] = useState('');
const [isSavingOrigin, setIsSavingOrigin] = useState(false);
const [searchParams, setSearchParams] = useSearchParams();
const navigate = useNavigate();
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
const { settings } = useGitSettings();
const { git } = useGit();
const { toast } = useToast();
const { user } = useCurrentUser();
const { nostr } = useNostr();
const { mutateAsync: publishEvent } = useNostrPublish();
const projectPath = `/projects/${projectId}`;
// Initialize origin URL from git status
useEffect(() => {
if (gitStatus?.remotes) {
const originRemote = gitStatus.remotes.find(remote => remote.name === 'origin');
setOriginUrl(originRemote?.url || '');
}
}, [gitStatus?.remotes]);
const handleSaveOrigin = async () => {
if (!gitStatus?.isGitRepo) {
toast({
title: "Cannot configure origin",
description: "Not a git repository",
variant: "destructive",
});
return;
}
setIsSavingOrigin(true);
try {
// Remove existing origin if it exists
try {
await git.deleteRemote({
dir: projectPath,
remote: 'origin',
});
} catch {
// Ignore if origin doesn't exist
}
// Add new origin if URL is provided
if (originUrl.trim()) {
await git.addRemote({
dir: projectPath,
remote: 'origin',
url: originUrl.trim(),
});
toast({
title: "Origin configured",
description: `Origin remote set to ${originUrl.trim()}`,
});
} else {
toast({
title: "Origin removed",
description: "Origin remote has been removed",
});
}
// Refresh git status after changing origin
await refetchGitStatus();
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
toast({
title: "Failed to configure origin",
description: errorMessage,
variant: "destructive",
});
} finally {
setIsSavingOrigin(false);
}
};
const handlePushToNostr = async () => {
if (!user) {
toast({
title: "Cannot push to Nostr",
description: "You must be logged in to push to Nostr",
variant: "destructive",
});
return;
}
if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) {
toast({
title: "Cannot push to Nostr",
description: "Not a git repository or no current branch",
variant: "destructive",
});
return;
}
setIsPushingToNostr(true);
try {
// Check if repo announcement already exists
const existingRepoEvents = await nostr.query([{
kinds: [30617],
authors: [user.pubkey],
'#d': [projectId],
limit: 1,
}], { signal: AbortSignal.timeout(5000) });
if (existingRepoEvents.length > 0) {
throw new Error(`Repository announcement already exists for project "${projectId}". Cannot create duplicate.`);
}
// Create repo announcement event (NIP-34 kind 30617)
const cloneUrls = GRASP_SERVERS.map(server =>
`https://${server}/${nip19.npubEncode(user.pubkey)}/${projectId}.git`
);
const relayUrls = GRASP_SERVERS.map(server => `wss://${server}`);
await publishEvent({
kind: 30617,
content: "",
tags: [
["d", projectId],
["clone", ...cloneUrls],
["relays", ...relayUrls],
],
});
// Get current repository state
const refTags: string[][] = [];
// First check if we have any commits at all
try {
const log = await git.log({ dir: projectPath, depth: 1 });
if (log.length === 0) {
throw new Error('Repository has no commits. Please make at least one commit before publishing to Nostr.');
}
console.log(`Repository has ${log.length} commit(s), latest: ${log[0].oid}`);
} catch (error) {
if (error instanceof Error && error.message.includes('no commits')) {
throw error; // Re-throw our custom error
}
throw new Error('Repository has no commits. Please make at least one commit before publishing to Nostr.');
}
try {
// Get all refs using listRefs
const refs = await git.listRefs({ dir: projectPath });
console.log('Found refs:', refs);
for (const ref of refs) {
try {
const commitId = await git.resolveRef({
dir: projectPath,
ref,
});
if (ref.startsWith('refs/heads/') || ref.startsWith('refs/tags/')) {
refTags.push([ref, commitId]);
}
} catch (error) {
console.warn(`Failed to resolve ref ${ref}:`, error);
}
}
} catch (error) {
console.warn('Failed to list refs, trying alternative approach:', error);
}
// If no refs found, try to get the current branch directly
if (refTags.length === 0) {
try {
const currentBranch = await git.currentBranch({ dir: projectPath });
if (currentBranch) {
const currentCommit = await git.resolveRef({
dir: projectPath,
ref: 'HEAD',
});
refTags.push([`refs/heads/${currentBranch}`, currentCommit]);
console.log(`Added current branch: refs/heads/${currentBranch} -> ${currentCommit}`);
} else {
// Try to get HEAD directly even if no current branch
try {
const headCommit = await git.resolveRef({
dir: projectPath,
ref: 'HEAD',
});
refTags.push(['refs/heads/main', headCommit]); // Assume main branch
console.log(`Added assumed main branch: refs/heads/main -> ${headCommit}`);
} catch (headError) {
console.warn('Failed to resolve HEAD directly:', headError);
}
}
} catch (error) {
console.warn('Failed to get current branch:', error);
}
}
if (refTags.length === 0) {
throw new Error('Could not determine repository state. The repository might not have any commits or branches.');
}
// Get HEAD reference
let headRef: string | undefined;
try {
const currentBranch = await git.currentBranch({ dir: projectPath });
if (currentBranch) {
headRef = `ref: refs/heads/${currentBranch}`;
console.log(`HEAD points to: ${headRef}`);
} else {
// HEAD is detached, use the commit ID directly
const headValue = await git.resolveRef({
dir: projectPath,
ref: 'HEAD',
});
if (headValue) {
headRef = headValue;
console.log(`HEAD is detached at: ${headRef}`);
}
}
} catch (error) {
console.warn('Failed to resolve HEAD:', error);
}
// Create repo state event (NIP-34 kind 30618)
await publishEvent({
kind: 30618,
content: "",
tags: [
["d", projectId],
...refTags,
...(headRef ? [["HEAD", headRef]] : []),
],
});
// Set origin remote to Nostr URL
const nostrUrl = `nostr://${nip19.npubEncode(user.pubkey)}/git.shakespeare.diy/${projectId}`;
try {
// Remove existing origin if it exists
await git.deleteRemote({
dir: projectPath,
remote: 'origin',
});
} catch {
// Ignore if origin doesn't exist
}
await git.addRemote({
dir: projectPath,
remote: 'origin',
url: nostrUrl,
});
// Set nostr.repo config
await git.setConfig({
dir: projectPath,
path: 'nostr.repo',
value: nip19.naddrEncode({
kind: 30617,
pubkey: user.pubkey,
identifier: projectId,
}),
});
toast({
title: "Repository published to Nostr",
description: "Waiting for GRASP servers to update...",
});
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
toast({
title: "Push to Nostr failed",
description: errorMessage,
variant: "destructive",
duration: Infinity,
});
} finally {
setIsPushingToNostr(false);
}
};
const handlePush = async () => {
if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) {
toast({
title: "Cannot push",
description: "Not a git repository or no current branch",
variant: "destructive",
});
return;
}
if (gitStatus.remotes.length === 0) {
toast({
title: "Cannot push",
description: "No remote repositories configured",
variant: "destructive",
});
return;
}
if (gitStatus.ahead === 0) {
toast({
title: "Nothing to push",
description: "No commits ahead of remote. Commit your changes first.",
variant: "destructive",
});
return;
}
setIsPushing(true);
try {
const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin')
await git.push({
dir: projectPath,
remote: remote.name,
ref: gitStatus.currentBranch,
onAuth: (url) => findCredentialsForRepo(url, settings.credentials),
signer: user?.signer, // For signing if pushing to Nostr
});
toast({
title: "Push successful",
description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`,
});
// Refresh git status after push
await refetchGitStatus();
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
toast({
title: "Push failed",
description: errorMessage,
variant: "destructive",
duration: Infinity,
});
} finally {
setIsPushing(false);
}
};
const handlePull = async () => {
if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) {
toast({
title: "Cannot pull",
description: "Not a git repository or no current branch",
variant: "destructive",
});
return;
}
if (gitStatus.remotes.length === 0) {
toast({
title: "Cannot pull",
description: "No remote repositories configured",
variant: "destructive",
});
return;
}
setIsPulling(true);
try {
const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin')
// Get the current HEAD commit before pulling
const beforeCommit = await git.resolveRef({
dir: projectPath,
ref: 'HEAD',
});
await git.pull({
dir: projectPath,
ref: gitStatus.currentBranch,
singleBranch: true,
author: {
name: 'shakespeare.diy',
email: '[email protected]',
},
onAuth: (url) => findCredentialsForRepo(url, settings.credentials),
});
// Get the current HEAD commit after pulling
const afterCommit = await git.resolveRef({
dir: projectPath,
ref: 'HEAD',
});
// Check if the repository actually changed
const repoChanged = beforeCommit !== afterCommit;
toast({
title: "Pull successful",
description: repoChanged
? `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}`
: `Already up to date with ${remote.name}/${gitStatus.currentBranch}`,
});
// Refresh git status after pull
await refetchGitStatus();
// Only trigger build if the repository actually changed
if (repoChanged) {
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.set('build', '');
setSearchParams(newSearchParams);
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
toast({
title: "Pull failed",
description: errorMessage,
variant: "destructive",
duration: Infinity,
});
} finally {
setIsPulling(false);
}
};
const getFileStatusIcon = (status: string) => {
switch (status) {
case 'added':
return <Plus className="h-3 w-3 text-green-500" />;
case 'deleted':
return <Minus className="h-3 w-3 text-red-500" />;
case 'modified':
return <Edit className="h-3 w-3 text-blue-500" />;
case 'staged':
return <CheckCircle className="h-3 w-3 text-green-600" />;
case 'untracked':
return <FileIcon className="h-3 w-3 text-gray-500" />;
default:
return <FileIcon className="h-3 w-3" />;
}
};
const getFileStatusColor = (status: string) => {
switch (status) {
case 'added':
return 'bg-green-100 text-green-800 border-green-200';
case 'deleted':
return 'bg-red-100 text-red-800 border-red-200';
case 'modified':
return 'bg-blue-100 text-blue-800 border-blue-200';
case 'staged':
return 'bg-green-100 text-green-800 border-green-200';
case 'untracked':
return 'bg-gray-100 text-gray-800 border-gray-200';
default:
return 'bg-gray-100 text-gray-800 border-gray-200';
}
};
const getSyncStatus = () => {
if (!gitStatus?.isGitRepo) {
return { status: 'not-repo', text: 'Not a Git repository', icon: AlertCircle, color: 'text-gray-500' };
}
if (gitStatus.remotes.length === 0) {
return { status: 'no-remote', text: 'No remote configured', icon: AlertCircle, color: 'text-yellow-600' };
}
if (gitStatus.ahead > 0 && gitStatus.behind > 0) {
return { status: 'diverged', text: `${gitStatus.ahead} ahead, ${gitStatus.behind} behind`, icon: AlertCircle, color: 'text-red-600' };
}
if (gitStatus.ahead > 0) {
return { status: 'ahead', text: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} ahead`, icon: Upload, color: 'text-blue-600' };
}
// Show uncommitted changes but with different styling since they can't be pushed directly
if (gitStatus.hasUncommittedChanges) {
return { status: 'uncommitted', text: `${gitStatus.changedFiles.length} uncommitted change${gitStatus.changedFiles.length !== 1 ? 's' : ''}`, icon: Clock, color: 'text-yellow-600' };
}
if (gitStatus.behind > 0) {
return { status: 'behind', text: `${gitStatus.behind} commit${gitStatus.behind !== 1 ? 's' : ''} behind`, icon: Download, color: 'text-orange-600' };
}
return { status: 'synced', text: 'Up to date', icon: CheckCircle, color: 'text-green-600' };
};
const syncStatus = getSyncStatus();
return (
<Dialog open={open} onOpenChange={onOpenChange}>
{children && <DialogTrigger asChild>{children}</DialogTrigger>}
<DialogContent className="max-w-2xl max-h-[80vh]" onOpenAutoFocus={(e) => e.preventDefault()}>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<GitBranch className="h-5 w-5" />
Repository
</DialogTitle>
</DialogHeader>
{/* URL Configuration */}
{gitStatus?.isGitRepo && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm">Git URL</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="flex gap-2">
<div className="flex-1">
<Label htmlFor="origin-url" className="sr-only">
URL
</Label>
<Input
id="origin-url"
placeholder="https://github.com/username/repository.git"
value={originUrl}
onChange={(e) => setOriginUrl(e.target.value)}
disabled={isSavingOrigin}
/>
</div>
<Button
onClick={handleSaveOrigin}
disabled={isSavingOrigin}
variant="outline"
size="sm"
className="h-10 shrink-0"
>
{isSavingOrigin ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Save className="h-4 w-4 mr-2" />
)}
{isSavingOrigin ? 'Saving...' : 'Save'}
</Button>
</div>
{/* Credentials Warning */}
{gitStatus.remotes.length > 0 && (
(() => {
const remoteWithoutCredentials = gitStatus.remotes.find((remote) => !findCredentialsForRepo(remote.url, settings.credentials));
if (!remoteWithoutCredentials) return null;
let protocol = '';
let hostname = 'the remote host';
try {
const url = new URL(remoteWithoutCredentials.url);
protocol = url.protocol;
hostname = url.hostname;
} catch {
// Invalid URL
return (
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50">
<AlertTriangle className="h-4 w-4" />
<AlertDescription className="text-sm">
Invalid URL format. Enter an https URL.
</AlertDescription>
</Alert>
);
}
// Check for unsupported protocols
if (protocol !== 'https:' && protocol !== 'nostr:') {
return (
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50">
<AlertTriangle className="h-4 w-4" />
<AlertDescription className="text-sm">
The {protocol.replace(':', '')} URL type is not supported. Enter an https URL.
</AlertDescription>
</Alert>
);
}
// For nostr protocol, only show warning if user is not logged in
if (protocol === 'nostr:' && !user) {
return (
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50">
<AlertTriangle className="h-4 w-4" />
<AlertDescription className="text-sm">
You are not logged into Nostr. Push & pull might not work unless you{' '}
<button
onClick={() => navigate('/settings/nostr')}
className="underline hover:no-underline font-medium text-amber-700 dark:text-amber-300"
>
log in
</button>.
</AlertDescription>
</Alert>
);
}
// For https protocol, show warning if no credentials
if (protocol === 'https:') {
return (
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50">
<AlertTriangle className="h-4 w-4" />
<AlertDescription className="text-sm">
You are not logged into {hostname}. Push & pull might not work unless you{' '}
<button
onClick={() => navigate('/settings/git')}
className="underline hover:no-underline font-medium text-amber-700 dark:text-amber-300"
>
log in
</button>.
</AlertDescription>
</Alert>
);
}
return null;
})()
)}
</CardContent>
</Card>
)}
<ScrollArea className="max-h-[60vh]">
<div className="space-y-4">
{/* Sync Status */}
{gitStatus?.isGitRepo && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm">Sync Status</CardTitle>
</CardHeader>
<CardContent>
<div className="flex items-center gap-2 mb-4">
<syncStatus.icon className={cn("h-4 w-4", syncStatus.color)} />
<span className={cn("text-sm font-medium", syncStatus.color)}>
{syncStatus.text}
</span>
</div>
{gitStatus.remotes.length > 0 && (
<div className="flex gap-2">
<Button
onClick={handlePull}
disabled={isPulling || isPushing || isPushingToNostr}
variant="outline"
size="sm"
className="flex-1"
>
{isPulling ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Download className="h-4 w-4 mr-2" />
)}
{isPulling ? 'Pulling...' : 'Pull'}
</Button>
<Button
onClick={handlePush}
disabled={isPushing || isPulling || isPushingToNostr || gitStatus.ahead === 0}
variant="outline"
size="sm"
className="flex-1"
>
{isPushing ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Upload className="h-4 w-4 mr-2" />
)}
{isPushing ? 'Pushing...' : 'Push'}
</Button>
</div>
)}
{/* Push to Nostr button when no remote is configured and user is logged in */}
{gitStatus.remotes.length === 0 && user && (
<div className="flex gap-2">
<Button
onClick={handlePushToNostr}
disabled={isPushingToNostr || isPushing || isPulling}
variant="outline"
size="sm"
className="flex-1"
>
{isPushingToNostr ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Zap className="h-4 w-4 mr-2" />
)}
{isPushingToNostr ? 'Publishing to Nostr...' : 'Push to Nostr'}
</Button>
</div>
)}
</CardContent>
</Card>
)}
{/* Working Directory Changes */}
{gitStatus?.isGitRepo && gitStatus.changedFiles.length > 0 && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm">Working Directory Changes</CardTitle>
<CardDescription>
{gitStatus.changedFiles.length} file{gitStatus.changedFiles.length !== 1 ? 's' : ''} with changes
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2">
{gitStatus.changedFiles.map((file, index) => (
<div
key={index}
className="flex items-center gap-2 p-2 rounded-md border bg-muted/20"
>
{getFileStatusIcon(file.status)}
<span className="font-mono text-sm flex-1 truncate">
{file.filepath}
</span>
<Badge
variant="outline"
className={cn("text-xs", getFileStatusColor(file.status))}
>
{file.status}
</Badge>
</div>
))}
</div>
</CardContent>
</Card>
)}
{/* Clean Working Directory */}
{gitStatus?.isGitRepo && gitStatus.changedFiles.length === 0 && (
<Card>
<CardContent className="py-6">
<div className="text-center text-muted-foreground">
<CheckCircle className="h-8 w-8 mx-auto mb-2 text-green-500" />
<p>Working directory is clean</p>
<p className="text-xs">No uncommitted changes</p>
</div>
</CardContent>
</Card>
)}
</div>
</ScrollArea>
</DialogContent>
</Dialog>
);
}
+244
View File
@@ -0,0 +1,244 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { ReactNode } from 'react';
import { GitSettingsProvider } from './GitSettingsProvider';
import { useGitSettings } from '@/hooks/useGitSettings';
import type { GitCredential } from '@/contexts/GitSettingsContext';
import { TestApp } from '@/test/TestApp';
// Mock the config utils
vi.mock('@/lib/configUtils', () => ({
readGitSettings: vi.fn(),
writeGitSettings: vi.fn(),
}));
// Test component that uses the hook
function TestComponent() {
const { settings, updateSettings, addCredential, removeCredential, updateCredential, isConfigured } = useGitSettings();
const handleAdd = () => {
const credential: GitCredential = {
username: 'git',
password: 'test-token',
};
addCredential('https://github.com', credential);
};
const handleUpdate = () => {
updateCredential('https://github.com', { password: 'updated-token' });
};
const handleRemove = () => {
removeCredential('https://github.com');
};
const handleUpdateCorsProxy = () => {
updateSettings({ corsProxy: 'https://custom-cors.example.com' });
};
return (
<div>
<div data-testid="configured">{isConfigured ? 'configured' : 'not-configured'}</div>
<div data-testid="count">{Object.keys(settings.credentials).length}</div>
<div data-testid="cors-proxy">{settings.corsProxy}</div>
<button onClick={handleAdd}>Add GitHub</button>
<button onClick={handleUpdate}>Update GitHub</button>
<button onClick={handleRemove}>Remove GitHub</button>
<button onClick={handleUpdateCorsProxy}>Update CORS Proxy</button>
{settings.credentials['https://github.com'] && (
<div data-testid="github-creds">
{settings.credentials['https://github.com'].username}:
{settings.credentials['https://github.com'].password}
</div>
)}
</div>
);
}
function TestWrapper({ children }: { children: ReactNode }) {
return (
<TestApp>
<GitSettingsProvider>
{children}
</GitSettingsProvider>
</TestApp>
);
}
describe('GitSettingsProvider', () => {
beforeEach(async () => {
vi.clearAllMocks();
localStorage.clear();
// Mock the read function to return default settings
const { readGitSettings } = await import('@/lib/configUtils');
vi.mocked(readGitSettings).mockResolvedValue({
credentials: {},
corsProxy: 'https://cors.isomorphic-git.org',
});
});
it('provides initial empty state', async () => {
render(
<TestWrapper>
<TestComponent />
</TestWrapper>
);
await waitFor(() => {
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
expect(screen.getByTestId('count')).toHaveTextContent('0');
});
});
it('can add credentials', async () => {
render(
<TestWrapper>
<TestComponent />
</TestWrapper>
);
await waitFor(() => {
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
});
fireEvent.click(screen.getByText('Add GitHub'));
expect(screen.getByTestId('configured')).toHaveTextContent('configured');
expect(screen.getByTestId('count')).toHaveTextContent('1');
expect(screen.getByTestId('github-creds')).toHaveTextContent('git:test-token');
});
it('can update credentials', async () => {
render(
<TestWrapper>
<TestComponent />
</TestWrapper>
);
await waitFor(() => {
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
});
// First add a credential
fireEvent.click(screen.getByText('Add GitHub'));
expect(screen.getByTestId('github-creds')).toHaveTextContent('git:test-token');
// Then update it
fireEvent.click(screen.getByText('Update GitHub'));
expect(screen.getByTestId('github-creds')).toHaveTextContent('git:updated-token');
});
it('can remove credentials', async () => {
render(
<TestWrapper>
<TestComponent />
</TestWrapper>
);
await waitFor(() => {
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
});
// First add a credential
fireEvent.click(screen.getByText('Add GitHub'));
expect(screen.getByTestId('configured')).toHaveTextContent('configured');
expect(screen.getByTestId('count')).toHaveTextContent('1');
// Then remove it
fireEvent.click(screen.getByText('Remove GitHub'));
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
expect(screen.getByTestId('count')).toHaveTextContent('0');
});
it('persists settings to VFS', async () => {
const { writeGitSettings } = await import('@/lib/configUtils');
render(
<TestWrapper>
<TestComponent />
</TestWrapper>
);
await waitFor(() => {
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
});
fireEvent.click(screen.getByText('Add GitHub'));
// Check that settings were saved to VFS
await waitFor(() => {
expect(writeGitSettings).toHaveBeenCalledWith(
expect.anything(), // fs instance
expect.objectContaining({
credentials: {
'https://github.com': {
username: 'git',
password: 'test-token',
}
},
corsProxy: 'https://proxy.shakespeare.diy/?url={href}'
})
);
});
});
it('loads settings from VFS', async () => {
const settings = {
credentials: {
'https://gitlab.com': {
username: 'git',
password: 'gitlab-token',
},
},
corsProxy: 'https://custom-cors.example.com',
};
const { readGitSettings } = await import('@/lib/configUtils');
vi.mocked(readGitSettings).mockResolvedValue(settings);
render(
<TestWrapper>
<TestComponent />
</TestWrapper>
);
await waitFor(() => {
expect(screen.getByTestId('configured')).toHaveTextContent('configured');
expect(screen.getByTestId('count')).toHaveTextContent('1');
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://custom-cors.example.com');
});
});
it('provides default CORS proxy', async () => {
render(
<TestWrapper>
<TestComponent />
</TestWrapper>
);
await waitFor(() => {
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://proxy.shakespeare.diy/?url={href}');
});
});
it('can update CORS proxy', async () => {
render(
<TestWrapper>
<TestComponent />
</TestWrapper>
);
await waitFor(() => {
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://proxy.shakespeare.diy/?url={href}');
});
fireEvent.click(screen.getByText('Update CORS Proxy'));
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://custom-cors.example.com');
});
});
+109
View File
@@ -0,0 +1,109 @@
import { ReactNode, useState, useEffect } from 'react';
import { GitSettingsContext, type GitSettings, type GitCredential, type GitSettingsContextType } from '@/contexts/GitSettingsContext';
import { useFS } from '@/hooks/useFS';
import { readGitSettings, writeGitSettings } from '@/lib/configUtils';
interface GitSettingsProviderProps {
children: ReactNode;
}
const DEFAULT_SETTINGS: GitSettings = {
credentials: {},
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
};
export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
const { fs } = useFS();
const [settings, setSettings] = useState<GitSettings>(DEFAULT_SETTINGS);
const [isInitialized, setIsInitialized] = useState(false);
// Initialize settings from VFS on mount
useEffect(() => {
const initializeSettings = async () => {
try {
const settings = await readGitSettings(fs);
// Migrate old CORS proxy format
if (settings.corsProxy === 'https://cors.isomorphic-git.org') {
settings.corsProxy = DEFAULT_SETTINGS.corsProxy;
}
setSettings(settings);
} catch (error) {
console.error('Failed to initialize Git settings:', error);
setSettings(DEFAULT_SETTINGS);
} finally {
setIsInitialized(true);
}
};
initializeSettings();
}, [fs]);
// Save settings to VFS whenever they change (but not during initialization)
useEffect(() => {
if (!isInitialized) return;
const saveSettings = async () => {
try {
await writeGitSettings(fs, settings);
} catch (error) {
console.error('Failed to save Git settings:', error);
}
};
saveSettings();
}, [fs, settings, isInitialized]);
const updateSettings = (newSettings: Partial<GitSettings>) => {
setSettings(prev => ({ ...prev, ...newSettings }));
};
const addCredential = (origin: string, credential: GitCredential) => {
setSettings(prev => ({
...prev,
credentials: {
...prev.credentials,
[origin]: credential,
},
}));
};
const removeCredential = (origin: string) => {
setSettings(prev => {
const { [origin]: removed, ...rest } = prev.credentials;
return {
...prev,
credentials: rest,
};
});
};
const updateCredential = (origin: string, credential: Partial<GitCredential>) => {
setSettings(prev => ({
...prev,
credentials: {
...prev.credentials,
[origin]: {
...prev.credentials[origin],
...credential,
},
},
}));
};
const isConfigured = Object.entries(settings.credentials).length > 0;
const contextValue: GitSettingsContextType = {
settings,
updateSettings,
addCredential,
removeCredential,
updateCredential,
isConfigured,
};
return (
<GitSettingsContext.Provider value={contextValue}>
{children}
</GitSettingsContext.Provider>
);
}
@@ -0,0 +1,90 @@
import { describe, it, expect, vi } from 'vitest';
import { render } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { GitStatusIndicator } from './GitStatusIndicator';
// Mock the useGitStatus hook
vi.mock('@/hooks/useGitStatus', () => ({
useGitStatus: vi.fn(),
}));
import { useGitStatus } from '@/hooks/useGitStatus';
describe('GitStatusIndicator', () => {
it('should not render when not in a git repo', () => {
vi.mocked(useGitStatus).mockReturnValue({
data: {
hasUncommittedChanges: false,
changedFiles: [],
isGitRepo: false,
},
} as unknown as ReturnType<typeof useGitStatus>);
const { container } = render(
<TestApp>
<GitStatusIndicator projectId="test-project" />
</TestApp>
);
expect(container.firstChild).toBeNull();
});
it('should not render when no uncommitted changes', () => {
vi.mocked(useGitStatus).mockReturnValue({
data: {
hasUncommittedChanges: false,
changedFiles: [],
isGitRepo: true,
},
} as unknown as ReturnType<typeof useGitStatus>);
const { container } = render(
<TestApp>
<GitStatusIndicator projectId="test-project" />
</TestApp>
);
expect(container.firstChild).toBeNull();
});
it('should render yellow dot when there are uncommitted changes', () => {
vi.mocked(useGitStatus).mockReturnValue({
data: {
hasUncommittedChanges: true,
changedFiles: ['file1.txt', 'file2.txt'],
isGitRepo: true,
},
} as unknown as ReturnType<typeof useGitStatus>);
const { container } = render(
<TestApp>
<GitStatusIndicator projectId="test-project" />
</TestApp>
);
const indicator = container.firstChild as HTMLElement;
expect(indicator).toBeTruthy();
expect(indicator.className).toContain('bg-yellow-500');
expect(indicator.className).toContain('rounded-full');
expect(indicator.title).toBe('2 uncommitted changes');
});
it('should handle singular file count in tooltip', () => {
vi.mocked(useGitStatus).mockReturnValue({
data: {
hasUncommittedChanges: true,
changedFiles: ['file1.txt'],
isGitRepo: true,
},
} as unknown as ReturnType<typeof useGitStatus>);
const { container } = render(
<TestApp>
<GitStatusIndicator projectId="test-project" />
</TestApp>
);
const indicator = container.firstChild as HTMLElement;
expect(indicator.title).toBe('1 uncommitted change');
});
});
+27
View File
@@ -0,0 +1,27 @@
import { useGitStatus } from '@/hooks/useGitStatus';
import { cn } from '@/lib/utils';
interface GitStatusIndicatorProps {
projectId: string | null;
className?: string;
}
export function GitStatusIndicator({ projectId, className }: GitStatusIndicatorProps) {
const { data: gitStatus } = useGitStatus(projectId);
// Only show the indicator if we're in a git repo and have uncommitted changes
if (!gitStatus?.isGitRepo || !gitStatus?.hasUncommittedChanges) {
return null;
}
return (
<div
className={cn(
"w-2 h-2 bg-yellow-500 rounded-full animate-pulse",
"shadow-sm shadow-yellow-500/50",
className
)}
title={`${gitStatus.changedFiles.length} uncommitted change${gitStatus.changedFiles.length !== 1 ? 's' : ''}`}
/>
);
}
-18
View File
@@ -1,18 +0,0 @@
import { ReactNode } from 'react';
import { JSRuntimeContext, type JSRuntimeContextType } from '@/contexts/JSRuntimeContext';
import type { JSRuntime } from '@/lib/JSRuntime';
interface JSRuntimeProviderProps {
children: ReactNode;
runtime: JSRuntime;
}
export function JSRuntimeProvider({ children, runtime }: JSRuntimeProviderProps) {
const contextValue: JSRuntimeContextType = { runtime };
return (
<JSRuntimeContext.Provider value={contextValue}>
{children}
</JSRuntimeContext.Provider>
);
}
+52
View File
@@ -0,0 +1,52 @@
import { describe, it, expect } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { LanguagePicker } from './LanguagePicker';
describe('LanguagePicker', () => {
it('renders language picker with default English selection', () => {
render(
<TestApp>
<LanguagePicker />
</TestApp>
);
// Should show the trigger button
expect(screen.getByRole('combobox')).toBeInTheDocument();
});
it('shows language options when opened', async () => {
render(
<TestApp>
<LanguagePicker />
</TestApp>
);
// Click to open the dropdown
const trigger = screen.getByRole('combobox');
fireEvent.click(trigger);
// Should show all language options (using getAllByText since there might be duplicates)
expect(screen.getAllByText('System').length).toBeGreaterThan(0);
expect(screen.getAllByText('English').length).toBeGreaterThan(0);
expect(screen.getAllByText('Portuguese').length).toBeGreaterThan(0);
expect(screen.getAllByText('Chinese').length).toBeGreaterThan(0);
});
it('displays flag emojis for languages', async () => {
render(
<TestApp>
<LanguagePicker />
</TestApp>
);
// Click to open the dropdown
const trigger = screen.getByRole('combobox');
fireEvent.click(trigger);
// Should show flag emojis (using getAllByText since there might be duplicates)
expect(screen.getAllByText('🇺🇸').length).toBeGreaterThan(0);
expect(screen.getAllByText('🇧🇷').length).toBeGreaterThan(0);
expect(screen.getAllByText('🇨🇳').length).toBeGreaterThan(0);
});
});
+71
View File
@@ -0,0 +1,71 @@
import { useTranslation } from 'react-i18next';
import { Languages } from 'lucide-react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useAppContext } from '@/hooks/useAppContext';
interface LanguagePickerProps {
className?: string;
}
export function LanguagePicker({ className }: LanguagePickerProps) {
const { t } = useTranslation();
const { config, updateConfig } = useAppContext();
const handleLanguageChange = (language: string) => {
updateConfig((prev) => ({ ...prev, language: language === 'system' ? undefined : language }));
};
return (
<Select value={config.language ?? 'system'} onValueChange={handleLanguageChange}>
<SelectTrigger className={className}>
<div className="flex items-center gap-2">
<SelectValue />
</div>
</SelectTrigger>
<SelectContent>
<SelectItem value="system">
<div className="flex items-center gap-2">
<Languages className="h-4 w-4" />
{t('systemLanguage')}
</div>
</SelectItem>
<SelectItem value="en">
<div className="flex items-center gap-2">
<span className="text-lg">🇺🇸</span>
{t('english')}
</div>
</SelectItem>
<SelectItem value="pt">
<div className="flex items-center gap-2">
<span className="text-lg">🇧🇷</span>
{t('portuguese')}
</div>
</SelectItem>
<SelectItem value="zh">
<div className="flex items-center gap-2">
<span className="text-lg">🇨🇳</span>
{t('chinese')}
</div>
</SelectItem>
<SelectItem value="ha">
<div className="flex items-center gap-2">
<span className="text-lg">🇳🇬</span>
{t('hausa')}
</div>
</SelectItem>
<SelectItem value="yo">
<div className="flex items-center gap-2">
<span className="text-lg">🇳🇬</span>
{t('yoruba')}
</div>
</SelectItem>
<SelectItem value="ig">
<div className="flex items-center gap-2">
<span className="text-lg">🇳🇬</span>
{t('igbo')}
</div>
</SelectItem>
</SelectContent>
</Select>
);
}
+89
View File
@@ -0,0 +1,89 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import type { AIProvider } from '@/contexts/AISettingsContext';
// Mock QRCode
vi.mock('qrcode', () => ({
default: {
toDataURL: vi.fn().mockResolvedValue('data:image/png;base64,mock-qr-code'),
},
}));
// Mock WebLN
const mockWebLN = {
enable: vi.fn().mockResolvedValue(undefined),
sendPayment: vi.fn().mockResolvedValue({ preimage: 'mock-preimage' }),
};
// We need to import the component after mocking
const { CreditsDialog } = await import('./CreditsDialog');
const mockProvider: AIProvider = {
id: 'test-provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
nostr: false,
};
describe('Lightning Payment', () => {
beforeEach(() => {
vi.clearAllMocks();
// Reset WebLN mock
Object.defineProperty(window, 'webln', {
value: undefined,
writable: true,
});
});
it('shows QR code for Lightning payment', async () => {
render(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={() => {}}
provider={mockProvider}
/>
</TestApp>
);
// Should show the normal form initially
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
});
it('shows WebLN button when available', async () => {
// Mock WebLN availability
Object.defineProperty(window, 'webln', {
value: mockWebLN,
writable: true,
});
render(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={() => {}}
provider={mockProvider}
/>
</TestApp>
);
// Should show the normal form initially
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
});
it('displays copy invoice button', async () => {
render(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={() => {}}
provider={mockProvider}
/>
</TestApp>
);
// Should show the normal form initially
expect(screen.getByText('Payment Method')).toBeInTheDocument();
});
});
+240
View File
@@ -0,0 +1,240 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { ModelSelector } from './ModelSelector';
// Mock the hooks
vi.mock('@/hooks/useAISettings', () => ({
useAISettings: vi.fn(),
}));
vi.mock('@/hooks/useProviderModels', () => ({
useProviderModels: vi.fn(),
}));
vi.mock('react-router-dom', async (importOriginal) => {
const actual = await importOriginal() as Record<string, unknown>;
return {
...actual,
useNavigate: () => vi.fn(),
};
});
import { useAISettings } from '@/hooks/useAISettings';
import { useProviderModels } from '@/hooks/useProviderModels';
const mockUseAISettings = vi.mocked(useAISettings);
const mockUseProviderModels = vi.mocked(useProviderModels);
describe('ModelSelector', () => {
const mockOnChange = vi.fn();
const mockAddRecentlyUsedModel = vi.fn();
beforeEach(() => {
vi.clearAllMocks();
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels: [] },
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
});
mockUseProviderModels.mockReturnValue({
models: [],
isLoading: false,
error: null,
refetch: vi.fn(),
});
});
it('hides recently used section when less than 5 models and all recently used are available', async () => {
// Setup: 3 available models, 2 recently used models that are both available
const availableModels = [
{ fullId: 'provider1/model1', provider: 'provider1', id: 'model1' },
{ fullId: 'provider1/model2', provider: 'provider1', id: 'model2' },
{ fullId: 'provider2/model3', provider: 'provider2', id: 'model3' },
];
const recentlyUsedModels = ['provider1/model1', 'provider1/model2'];
mockUseProviderModels.mockReturnValue({
models: availableModels,
isLoading: false,
error: null,
refetch: vi.fn(),
});
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels },
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="" onChange={mockOnChange} />
</TestApp>
);
// Open the dropdown
const trigger = screen.getByRole('combobox');
fireEvent.click(trigger);
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('provider1')).toBeInTheDocument();
});
// Recently used section should NOT be visible
expect(screen.queryByText('Recently Used')).not.toBeInTheDocument();
});
it('shows recently used section when less than 5 models but some recently used are not available', async () => {
// Setup: 3 available models, 2 recently used models where 1 is not available
const availableModels = [
{ fullId: 'provider1/model1', provider: 'provider1', id: 'model1' },
{ fullId: 'provider1/model2', provider: 'provider1', id: 'model2' },
{ fullId: 'provider2/model3', provider: 'provider2', id: 'model3' },
];
const recentlyUsedModels = ['provider1/model1', 'provider3/model4']; // model4 not in available
mockUseProviderModels.mockReturnValue({
models: availableModels,
isLoading: false,
error: null,
refetch: vi.fn(),
});
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels },
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="" onChange={mockOnChange} />
</TestApp>
);
// Open the dropdown
const trigger = screen.getByRole('combobox');
fireEvent.click(trigger);
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('provider1')).toBeInTheDocument();
});
// Recently used section SHOULD be visible
expect(screen.getByText('Recently Used')).toBeInTheDocument();
});
it('shows recently used section when 5 or more models are available', async () => {
// Setup: 5 available models, 2 recently used models that are both available
const availableModels = [
{ fullId: 'provider1/model1', provider: 'provider1', id: 'model1' },
{ fullId: 'provider1/model2', provider: 'provider1', id: 'model2' },
{ fullId: 'provider2/model3', provider: 'provider2', id: 'model3' },
{ fullId: 'provider2/model4', provider: 'provider2', id: 'model4' },
{ fullId: 'provider3/model5', provider: 'provider3', id: 'model5' },
];
const recentlyUsedModels = ['provider1/model1', 'provider1/model2'];
mockUseProviderModels.mockReturnValue({
models: availableModels,
isLoading: false,
error: null,
refetch: vi.fn(),
});
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels },
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="" onChange={mockOnChange} />
</TestApp>
);
// Open the dropdown
const trigger = screen.getByRole('combobox');
fireEvent.click(trigger);
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('provider1')).toBeInTheDocument();
});
// Recently used section SHOULD be visible
expect(screen.getByText('Recently Used')).toBeInTheDocument();
});
it('hides recently used section when no recently used models exist', async () => {
const availableModels = [
{ fullId: 'provider1/model1', provider: 'provider1', id: 'model1' },
{ fullId: 'provider1/model2', provider: 'provider1', id: 'model2' },
];
mockUseProviderModels.mockReturnValue({
models: availableModels,
isLoading: false,
error: null,
refetch: vi.fn(),
});
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels: [] }, // No recently used models
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="" onChange={mockOnChange} />
</TestApp>
);
// Open the dropdown
const trigger = screen.getByRole('combobox');
fireEvent.click(trigger);
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('provider1')).toBeInTheDocument();
});
// Recently used section should NOT be visible
expect(screen.queryByText('Recently Used')).not.toBeInTheDocument();
});
});
+293
View File
@@ -0,0 +1,293 @@
import { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from '@/components/ui/command';
import { Skeleton } from '@/components/ui/skeleton';
import { useAISettings } from '@/hooks/useAISettings';
import { useProviderModels } from '@/hooks/useProviderModels';
import { cn } from '@/lib/utils';
interface ModelSelectorProps {
value: string;
onChange: (value: string) => void;
className?: string;
disabled?: boolean;
placeholder?: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
export function ModelSelector({
value,
onChange,
className,
disabled = false,
placeholder,
open: controlledOpen,
onOpenChange: setControlledOpen,
}: ModelSelectorProps) {
const { t } = useTranslation();
const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
// Use controlled state if provided, otherwise use local state
const open = controlledOpen !== undefined ? controlledOpen : uncontrolledOpen;
const setOpen = setControlledOpen || setUncontrolledOpen;
const [isCustomInput, setIsCustomInput] = useState(false);
const [customValue, setCustomValue] = useState('');
const { settings, addRecentlyUsedModel, isConfigured } = useAISettings();
const { models, isLoading, error, refetch } = useProviderModels();
const navigate = useNavigate();
const defaultPlaceholder = t('selectOrEnterModel');
const recentlyUsedModels = useMemo(() => settings.recentlyUsedModels || [], [settings.recentlyUsedModels]);
// Group models by provider
const modelsByProvider = useMemo(() => {
const groups: Record<string, typeof models> = {};
for (const model of models) {
if (!groups[model.provider]) {
groups[model.provider] = [];
}
groups[model.provider].push(model);
}
return groups;
}, [models]);
// Determine if we should show the "Recently Used" section
const shouldShowRecentlyUsed = useMemo(() => {
// If no recently used models, don't show the section
if (recentlyUsedModels.length === 0) {
return false;
}
// If there are 5 or more total provider models, always show recently used
if (models.length >= 5) {
return true;
}
// If less than 5 total provider models, check if all recently used models
// are contained within the available provider models
const availableModelIds = new Set(models.map(model => model.fullId));
const allRecentlyUsedAreAvailable = recentlyUsedModels.every(model =>
availableModelIds.has(model)
);
// Hide recently used section if all recently used models are already available
return !allRecentlyUsedAreAvailable;
}, [recentlyUsedModels, models]);
// Don't auto-initialize with recently used models
// Let the parent component handle initialization
const handleSelect = (selectedValue: string) => {
if (selectedValue === '__custom__') {
setIsCustomInput(true);
setCustomValue(value);
setOpen(false);
return;
}
if (selectedValue === '__manage_providers__') {
navigate('/settings/ai');
setOpen(false);
return;
}
onChange(selectedValue);
addRecentlyUsedModel(selectedValue);
setOpen(false);
};
const handleCustomSubmit = () => {
if (customValue.trim()) {
onChange(customValue.trim());
addRecentlyUsedModel(customValue.trim());
setIsCustomInput(false);
setCustomValue('');
}
};
const handleCustomKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
e.preventDefault();
handleCustomSubmit();
} else if (e.key === 'Escape') {
setIsCustomInput(false);
setCustomValue('');
}
};
if (isCustomInput) {
return (
<div className={cn("flex items-center gap-1", className)}>
<Input
value={customValue}
onChange={(e) => setCustomValue(e.target.value)}
onKeyDown={handleCustomKeyDown}
onBlur={handleCustomSubmit}
placeholder="provider/model (e.g., openrouter/anthropic/claude-sonnet-4)"
className="h-8 text-xs"
autoFocus
/>
<Button
size="sm"
variant="ghost"
className="h-8 w-8 p-0"
onClick={handleCustomSubmit}
>
<Check className="h-3 w-3" />
</Button>
</div>
);
}
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
role="combobox"
aria-expanded={open}
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",
className
)}
disabled={disabled}
>
<span className="w-full truncate">
{value || placeholder || defaultPlaceholder}
</span>
<ChevronDown className="size-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-96 p-0" align="end">
<Command>
{(isConfigured && models.length >= 5) && (
<CommandInput placeholder={t('searchModels')} className="h-9" />
)}
<CommandList className="max-h-[300px]">
<CommandEmpty>
<div className="py-6 text-center text-sm text-muted-foreground">
<p>{t('noModelsFound')}</p>
<p className="mt-2 text-xs">{t('tryCustomModel')}</p>
</div>
</CommandEmpty>
{shouldShowRecentlyUsed && (
<CommandGroup heading={t('recentlyUsed')}>
{recentlyUsedModels.map((model) => (
<CommandItem
key={model}
value={model}
onSelect={() => handleSelect(model)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate">{model}</span>
</CommandItem>
))}
</CommandGroup>
)}
{shouldShowRecentlyUsed && <CommandSeparator />}
{/* Loading state */}
{isLoading && (
<CommandGroup heading={t('loading')}>
<div className="px-2 py-1.5">
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4 w-1/2" />
</div>
</div>
</CommandGroup>
)}
{/* Error state */}
{error && !isLoading && (
<CommandGroup heading={t('errorLoadingModels')}>
<div className="px-2 py-1.5 text-sm text-muted-foreground">
<div className="flex items-start gap-2">
<AlertCircle className="h-4 w-4 text-destructive flex-shrink-0 mt-0.5" />
<div className="space-y-2">
<p className="text-destructive">{error}</p>
<Button
variant="outline"
size="sm"
onClick={refetch}
className="h-7 text-xs"
>
<RefreshCw className="h-3 w-3 mr-1" />
{t('retry')}
</Button>
</div>
</div>
</div>
</CommandGroup>
)}
{/* Provider models */}
{!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => (
<div key={provider}>
<CommandSeparator />
<CommandGroup heading={provider}>
{providerModels.map((model) => (
<CommandItem
key={model.fullId}
value={model.fullId}
onSelect={() => handleSelect(model.fullId)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model.fullId ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate">{model.fullId}</span>
</CommandItem>
))}
</CommandGroup>
</div>
))}
{/* Custom model option and manage providers - moved to bottom */}
<CommandSeparator />
<CommandGroup>
{isConfigured && (
<CommandItem
value="__custom_model_option__"
onSelect={() => handleSelect('__custom__')}
className="cursor-pointer"
>
<Edit3 className="mr-2 h-4 w-4" />
{t('enterCustomModel')}
</CommandItem>
)}
<CommandItem
value="__manage_providers_option__"
onSelect={() => handleSelect('__manage_providers__')}
className="cursor-pointer"
>
<Settings className="mr-2 h-4 w-4" />
{t('manageProviders')}
</CommandItem>
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}
+31 -3
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useRef } from 'react';
import { NostrEvent, NPool, NRelay1 } from '@nostrify/nostrify';
import { NostrEvent, NostrFilter, NPool, NRelay1 } from '@nostrify/nostrify';
import { NostrContext } from '@nostrify/react';
import { useQueryClient } from '@tanstack/react-query';
import { useAppContext } from '@/hooks/useAppContext';
@@ -8,6 +8,18 @@ interface NostrProviderProps {
children: React.ReactNode;
}
const GIT_KINDS = [
30617, // NIP-34 Repository Announcement
30618, // NIP-34 Commit Announcement
1617, // NIP-34 Patch
1621, // NIP-34 Issue
];
const GIT_RELAYS = [
'wss://git.shakespeare.diy/',
'wss://relay.ngit.dev/',
];
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
const { children } = props;
const { config, presetRelays } = useAppContext();
@@ -33,12 +45,28 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
return new NRelay1(url);
},
reqRouter(filters) {
return new Map([[relayUrl.current, filters]]);
const routes = new Map<string, NostrFilter[]>();
routes.set(relayUrl.current, filters);
if (filters.every((f) => f.kinds?.every((k) => GIT_KINDS.includes(k)))) {
// If all filters are git-related, route to all git relays
for (const url of GIT_RELAYS) {
routes.set(url, filters);
}
}
return routes;
},
eventRouter(_event: NostrEvent) {
eventRouter(event: NostrEvent) {
// Publish to the selected relay
const allRelays = new Set<string>([relayUrl.current]);
// If it's a git-related event, also publish to the git relays
if (GIT_KINDS.includes(event.kind)) {
for (const url of GIT_RELAYS) {
allRelays.add(url);
}
}
// Also publish to the preset relays, capped to 5
for (const { url } of (presetRelays ?? [])) {
allRelays.add(url);
@@ -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>
);
}
+59
View File
@@ -0,0 +1,59 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { OnboardingDialog } from './OnboardingDialog';
import { TestApp } from '@/test/TestApp';
// Mock the hooks
vi.mock('@/hooks/useAISettings', () => ({
useAISettings: () => ({
settings: { providers: [], recentlyUsedModels: [] },
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
updateSettings: vi.fn(),
isConfigured: false,
}),
}));
vi.mock('@/hooks/useCurrentUser', () => ({
useCurrentUser: () => ({ user: null }),
}));
vi.mock('@/hooks/useLoginActions', () => ({
useLoginActions: () => ({ nsec: vi.fn() }),
}));
vi.mock('@/hooks/useProviderModels', () => ({
useProviderModels: () => ({
models: [],
isLoading: false,
error: null,
refetch: vi.fn(),
}),
}));
describe('OnboardingDialog', () => {
it('renders welcome step when open', () => {
render(
<TestApp>
<OnboardingDialog open={true} onOpenChange={vi.fn()} />
</TestApp>
);
expect(screen.getByText('Welcome to Shakespeare!')).toBeInTheDocument(); // Only in dialog title now
expect(screen.getByText(/Your AI-powered development assistant/)).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Get Started/i })).toBeInTheDocument();
});
it('does not render when closed', () => {
render(
<TestApp>
<OnboardingDialog open={false} onOpenChange={vi.fn()} />
</TestApp>
);
expect(screen.queryByText('Welcome to Shakespeare!')).not.toBeInTheDocument();
});
});
+633
View File
@@ -0,0 +1,633 @@
import { Decimal } from 'decimal.js';
import { useState, useEffect, useRef } from 'react';
import { generateSecretKey } from 'nostr-tools';
import { nip19 } from 'nostr-tools';
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, ExternalLink } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Checkbox } from '@/components/ui/checkbox';
import { PasswordInput } from '@/components/ui/password-input';
import { useAISettings } from '@/hooks/useAISettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useLoginActions } from '@/hooks/useLoginActions';
import { useProviderModels } from '@/hooks/useProviderModels';
import { CreditsDialog } from '@/components/CreditsDialog';
import { 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 {
open: boolean;
onOpenChange: (open: boolean) => void;
}
type OnboardingStep = 'welcome' | 'open-source' | 'provider-selection' | 'model-selection' | 'conclusion';
export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) {
const [step, setStep] = useState<OnboardingStep>('welcome');
const [selectedProvider, setSelectedProvider] = useState<PresetProvider | null>(null);
const [providerApiKey, setProviderApiKey] = useState<string>('');
const [selectedModel, setSelectedModel] = useState<string>('');
const [isSettingUp, setIsSettingUp] = 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 { user } = useCurrentUser();
const login = useLoginActions();
const { models, isLoading: isLoadingModels } = useProviderModels();
// Filter models to only show selected provider models
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;
setIsSettingUp(true);
try {
// If user is not logged in and provider uses Nostr auth, generate and login with secret key
if (!user && selectedProvider.nostr) {
const secretKey = generateSecretKey();
const nsec = nip19.nsecEncode(secretKey);
login.nsec(nsec);
}
// Add selected provider to their config
const providerConfig = {
id: selectedProvider.id,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
apiKey: requiresApiKey ? providerApiKey.trim() : undefined,
};
setProvider(providerConfig);
// Move to model selection
setStep('model-selection');
} catch (error) {
console.error('Failed to set up user:', error);
} finally {
setIsSettingUp(false);
}
};
const handleModelSelect = (modelFullId: string) => {
setSelectedModel(modelFullId);
};
const handleContinue = () => {
if (!selectedModel) return;
// Add model to recently used
addRecentlyUsedModel(selectedModel);
// Find the selected model to check if it's free
const model = providerModels.find(m => m.fullId === selectedModel);
const isFreeModel = !model?.pricing || (
model.pricing.prompt.equals(0) && model.pricing.completion.equals(0)
);
if (isFreeModel) {
// Free model, go straight to conclusion
setStep('conclusion');
} else {
// Paid model, show credits dialog
setShowCreditsDialog(true);
}
};
const handleCreditsDialogClose = () => {
setShowCreditsDialog(false);
setStep('conclusion');
};
const handleFinish = () => {
onOpenChange(false);
};
const formatPrice = (price: Decimal | undefined) => {
if (!price) return 'unknown';
if (price.equals(0)) return 'Free';
// Convert from per-token to per-1M tokens and format with $ prefix
const pricePerMillion = price.times(1_000_000);
return '$' + pricePerMillion.toFixed(2).toString().replace(/\.00$/, '') + '/M tokens';
};
// Reset state when dialog opens/closes
useEffect(() => {
if (open) {
setStep('welcome');
setSelectedProvider(null);
setProviderApiKey('');
setSelectedModel('');
setIsSettingUp(false);
setShowCreditsDialog(false);
setAgreedToTerms(false);
setAgreedToProviderTerms(false);
}
}, [open]);
// Scroll to top when step changes
useEffect(() => {
if (scrollableContentRef.current) {
scrollableContentRef.current.scrollTop = 0;
}
}, [step]);
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl h-[100dvh] sm:h-auto sm:max-h-[90vh] flex flex-col">
<DialogHeader className="flex-shrink-0">
<DialogTitle className="flex items-center gap-2">
{step === 'open-source' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('welcome')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</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">
{step === 'model-selection' && 'Choose Your AI Model'}
</span>
</DialogTitle>
</DialogHeader>
<div ref={scrollableContentRef} className="flex-1 overflow-y-auto min-h-0">
{step === 'welcome' && (
<div className="text-center space-y-6 py-4">
<div className="mb-4">
<ShakespeareLogo className="w-16 h-16 mx-auto" />
</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Welcome to Shakespeare!
</h2>
<p className="text-lg text-muted-foreground max-w-md mx-auto">
Your AI-powered development assistant for building custom Nostr applications.
Simply describe what you want to build, and AI will help you create it.
</p>
</div>
<div className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 max-w-lg mx-auto">
<div className="text-center space-y-2">
<div className="text-2xl">💡</div>
<p className="text-sm text-muted-foreground">AI-Powered Development</p>
</div>
<div className="text-center space-y-2">
<div className="text-2xl">⚡</div>
<p className="text-sm text-muted-foreground">Nostr Integration</p>
</div>
<div className="text-center space-y-2">
<div className="text-2xl">🚀</div>
<p className="text-sm text-muted-foreground">Instant Preview</p>
</div>
</div>
<Button
onClick={handleGetStarted}
disabled={isSettingUp}
size="lg"
className="gap-2"
>
{isSettingUp ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white" />
Setting up...
</>
) : (
<>
<Sparkles className="h-4 w-4" />
Get Started
</>
)}
</Button>
</div>
</div>
)}
{step === 'open-source' && (
<div className="space-y-6 py-4">
<div className="text-center space-y-4">
<h2 className="text-2xl font-bold">Shakespeare is Open Source software that runs entirely in your web&nbsp;browser</h2>
</div>
<div className="grid gap-1 max-w-md mx-auto">
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
<p className="text-sm">Your browser connects directly to third-party AI providers of your choice</p>
</div>
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
<p className="text-sm">Your files are stored on your device in your browser</p>
</div>
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
<p className="text-sm">Be careful not to delete your browser data or you may lose project files</p>
</div>
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
<p className="text-sm">You are responsible for taking backups or syncing to git</p>
</div>
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
<p className="text-sm">Quality of output depends on quality of input and models used, and is not guaranteed</p>
</div>
</div>
<div className="space-y-3 max-w-md mx-auto">
<p className="text-xs text-muted-foreground max-w-xl mx-auto">
Shakespeare is not a cloud service. It's Open Source software that runs in your web browser.
You agree to the Terms of Service of AI providers you interact with.
Shakespeare is provided "as is" without warranty of any kind.
</p>
<div className="flex items-center justify-center gap-2">
<Checkbox
id="agree-terms"
checked={agreedToTerms}
onCheckedChange={(checked) => setAgreedToTerms(checked === true)}
/>
<label
htmlFor="agree-terms"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
>
I agree
</label>
</div>
</div>
<div className="flex justify-center">
<Button
onClick={handleContinueFromOpenSource}
disabled={!agreedToTerms}
className="gap-2 rounded-full w-full max-w-md"
>
Continue
<ArrowRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
{step === 'provider-selection' && (
<div className="space-y-6 py-4">
<div className="text-center space-y-4">
<h2 className="text-2xl font-bold">Choose your AI provider</h2>
<p className="text-muted-foreground max-w-md mx-auto">
Select an AI provider to power your development assistant. You can add more providers later in settings.
</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 p-1 gap-3 max-w-4xl mx-auto">
{AI_PROVIDER_PRESETS.map((provider) => {
const isSelected = selectedProvider?.id === provider.id;
const isShakespeare = provider.id === 'shakespeare';
return (
<Card
key={provider.id}
className={cn('cursor-pointer transition-all hover:shadow-md', {
'ring-2 ring-primary': isSelected,
})}
onClick={() => handleProviderSelect(provider)}
>
<div className="flex items-center justify-between p-3">
<div className="flex-1">
<CardTitle className={cn('text-lg font-semibold', {
'bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent': isShakespeare,
})}>
{provider.name}
</CardTitle>
</div>
<div className="flex items-center gap-2">
<OnboardingCreditsBadge provider={provider} />
{isSelected && (
<div className="h-5 w-5 rounded-full bg-primary flex items-center justify-center">
<Check className="h-3 w-3 text-primary-foreground" />
</div>
)}
</div>
</div>
</Card>
);
})}
</div>
{/* API Key Input Section */}
{selectedProvider && selectedProvider.apiKeysURL && !selectedProvider.nostr && (
<div className="space-y-3 max-w-md mx-auto">
<div className="text-center">
<h3 className="text-lg font-semibold">
{selectedProvider.id === 'routstr' ? 'Enter Cashu Token' : 'Enter API Key'}
</h3>
<p className="text-sm text-muted-foreground">
{selectedProvider.id === 'routstr' ? (
<>{selectedProvider.name} requires a Cashu token</>
) : (
<>
{selectedProvider.name} requires an {selectedProvider.apiKeysURL ? (
<a className="text-foreground underline" href={selectedProvider.apiKeysURL} target="_blank">
API key
<ExternalLink className="inline-block h-4 w-4 ml-1" />
</a>
) : (
<>API key</>
)}
</>
)}
</p>
</div>
<PasswordInput
placeholder={selectedProvider.id === 'routstr' ? 'Enter a Cashu Token' : 'Enter your API key'}
value={providerApiKey}
onChange={(e) => setProviderApiKey(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && providerApiKey.trim()) {
handleContinueFromProviderSelection();
}
}}
/>
</div>
)}
{/* Terms of Service Agreement */}
{selectedProvider && (
<div className="space-y-3 max-w-md mx-auto">
<div className="flex items-center justify-center gap-2">
<Checkbox
id="agree-provider-terms"
checked={agreedToProviderTerms}
onCheckedChange={(checked) => setAgreedToProviderTerms(checked === true)}
/>
<label
htmlFor="agree-provider-terms"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
>
I agree to {selectedProvider.name}'s{' '}
{selectedProvider.tosURL ? (
<a
href={selectedProvider.tosURL}
target="_blank"
rel="noopener noreferrer"
className="text-primary underline hover:no-underline"
onClick={(e) => e.stopPropagation()}
>
Terms of Service
</a>
) : (
'Terms of Service'
)}
</label>
</div>
</div>
)}
<div className="flex justify-center">
<Button
onClick={handleContinueFromProviderSelection}
disabled={
!selectedProvider ||
isSettingUp ||
!agreedToProviderTerms ||
!!(selectedProvider?.apiKeysURL && !selectedProvider?.nostr && !providerApiKey.trim())
}
className="gap-2 rounded-full w-full max-w-md"
>
{isSettingUp ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white" />
Setting up...
</>
) : (
<>
Continue
<ArrowRight className="h-4 w-4" />
</>
)}
</Button>
</div>
</div>
)}
{step === 'model-selection' && (
<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">
{isLoadingModels ? (
<>
{Array.from({ length: 3 }).map((_, i) => (
<Card key={i} className="p-4">
<div className="space-y-3">
<div className="flex items-center justify-between">
<Skeleton className="h-5 w-32" />
<Skeleton className="h-5 w-16" />
</div>
<Skeleton className="h-4 w-full" />
<div className="flex gap-2">
<Skeleton className="h-6 w-20" />
<Skeleton className="h-6 w-24" />
</div>
</div>
</Card>
))}
</>
) : providerModels.length === 0 ? (
<Card className="p-6 text-center">
<div className="space-y-2">
<Bot className="h-8 w-8 mx-auto text-muted-foreground" />
<p className="text-muted-foreground">
No models available. Please check your connection and try again.
</p>
</div>
</Card>
) : (
providerModels.map((model) => {
const isSelected = selectedModel === model.fullId;
const isFree = model.pricing?.prompt.equals(0) && model.pricing?.completion.equals(0);
const isPremium = !!model.pricing && !isFree;
const modelName = model.name || model.id;
return (
<Card
key={model.fullId}
className={`cursor-pointer transition-all hover:shadow-md ${
isSelected ? 'ring-2 ring-primary' : ''
}`}
onClick={() => handleModelSelect(model.fullId)}
>
<CardHeader>
<div className="flex items-center justify-between">
<div className="flex-1">
<CardTitle className={cn('text-xl font-semibold', {
'bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent': isPremium,
})}>
{modelName}
</CardTitle>
{model.description && (
<p className="text-sm text-muted-foreground mt-1">
{model.description.length > 70
? model.description.slice(0, 70) + '...'
: model.description}
</p>
)}
</div>
<div className="flex items-center gap-2">
{isFree && (
<Badge variant="secondary" className="text-xs">
Free
</Badge>
)}
{isPremium && (
<Badge className="text-xs bg-primary text-white border-0">
Premium
</Badge>
)}
{isSelected && (
<div className="h-5 w-5 rounded-full bg-primary flex items-center justify-center">
<Check className="h-3 w-3 text-primary-foreground" />
</div>
)}
</div>
</div>
</CardHeader>
{(model.pricing || model.contextLength) && (
<CardContent className="pt-0">
<div className="flex items-end justify-end gap-4 text-xs text-muted-foreground">
{model.pricing && (
<div className="text-right">
<div>Input: {formatPrice(model.pricing.prompt)}</div>
<div>Output: {formatPrice(model.pricing.completion)}</div>
</div>
)}
{model.contextLength && (
<span>Context: {model.contextLength.toLocaleString()} tokens</span>
)}
</div>
</CardContent>
)}
</Card>
);
})
)}
</div>
</div>
<div className="flex justify-end gap-2 pt-4 flex-shrink-0">
<Button
onClick={handleContinue}
disabled={!selectedModel}
className="gap-2"
>
Continue
<ArrowRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
{step === 'conclusion' && (
<div className="text-center space-y-6 py-8">
<div className="text-5xl mb-4">🎉</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold">Now you're ready to build!</h2>
<p className="text-lg text-muted-foreground max-w-md mx-auto">
Your AI assistant is configured and ready to help.
Just enter your prompt to start building amazing Nostr applications.
</p>
</div>
<Button onClick={handleFinish} size="lg" className="gap-2">
<Sparkles className="h-4 w-4" />
Start Building
</Button>
</div>
)}
</div>
</DialogContent>
</Dialog>
{/* Credits Dialog */}
{showCreditsDialog && selectedModel && selectedProvider && (
<CreditsDialog
open={showCreditsDialog}
onOpenChange={(open) => {
if (!open) {
handleCreditsDialogClose();
}
}}
provider={{
id: selectedProvider.id,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
}}
/>
)}
</>
);
}
+320
View File
@@ -0,0 +1,320 @@
import { useState, useEffect } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { type Project } from '@/lib/ProjectsManager';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useToast } from '@/hooks/useToast';
import { useFS } from '@/hooks/useFS';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useNavigate } from 'react-router-dom';
import {
Calendar,
Folder,
Download,
Loader2,
Trash2,
Save,
} from 'lucide-react';
import JSZip from 'jszip';
import { Separator } from './ui/separator';
interface ProjectDetailsDialogProps {
project: Project;
open: boolean;
onOpenChange: (open: boolean) => void;
onProjectDeleted?: () => void;
}
export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDeleted }: ProjectDetailsDialogProps) {
const [isExporting, setIsExporting] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const [isRenaming, setIsRenaming] = useState(false);
const [newProjectName, setNewProjectName] = useState(project.id);
const { toast } = useToast();
const { fs } = useFS();
const projectsManager = useProjectsManager();
const navigate = useNavigate();
const queryClient = useQueryClient();
// Reset state when project changes
useEffect(() => {
setNewProjectName(project.id);
setIsRenaming(false);
}, [project.id]);
const formatDistanceToNow = (date: Date) => {
const now = new Date();
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
if (diffInSeconds < 60) return 'just now';
if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)} minutes ago`;
if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)} hours ago`;
if (diffInSeconds < 2592000) return `${Math.floor(diffInSeconds / 86400)} days ago`;
if (diffInSeconds < 31536000) return `${Math.floor(diffInSeconds / 2592000)} months ago`;
return `${Math.floor(diffInSeconds / 31536000)} years ago`;
};
const handleSaveProject = async () => {
if (!newProjectName.trim() || newProjectName === project.id) {
setNewProjectName(project.id);
return;
}
setIsRenaming(true);
try {
await projectsManager.renameProject(project.id, newProjectName);
// Invalidate the projects query to update the sidebar
await queryClient.invalidateQueries({ queryKey: ['projects'] });
toast({
title: "Project renamed",
description: `Project renamed from "${project.id}" to "${newProjectName}".`,
});
// Close the dialog first
onOpenChange(false);
// Navigate to the new URL
navigate(`/project/${newProjectName}`);
} catch (error) {
toast({
title: "Failed to rename project",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
setNewProjectName(project.id); // Reset to original name
} finally {
setIsRenaming(false);
}
};
const handleDeleteProject = async () => {
setIsDeleting(true);
try {
await projectsManager.deleteProject(project.id);
// Invalidate the projects query to update the sidebar
await queryClient.invalidateQueries({ queryKey: ['projects'] });
toast({
title: "Project deleted",
description: `"${project.name}" has been permanently deleted.`,
});
// Close the dialog first
onOpenChange(false);
// Navigate back to home and notify parent
navigate('/');
if (onProjectDeleted) {
onProjectDeleted();
}
} catch (error) {
toast({
title: "Failed to delete project",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
} finally {
setIsDeleting(false);
}
};
const handleExportProject = async () => {
setIsExporting(true);
try {
const zip = new JSZip();
const projectPath = `/projects/${project.id}`;
// Recursive function to add files and directories to zip from a specific project
const addFolderToZip = async (dirPath: string, zipFolder: JSZip) => {
try {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
if (entry.isDirectory()) {
// Create folder in zip and recursively add its contents
const folder = zipFolder.folder(entry.name);
if (folder) {
await addFolderToZip(fullPath, folder);
}
} else if (entry.isFile()) {
// Add file to zip
try {
const fileContent = await fs.readFile(fullPath);
zipFolder.file(entry.name, fileContent);
} catch (error) {
console.warn(`Failed to read file ${fullPath}:`, error);
}
}
}
} catch (error) {
console.warn(`Failed to read directory ${dirPath}:`, error);
}
};
// Start from the project directory
await addFolderToZip(projectPath, zip);
// Generate zip file
const content = await zip.generateAsync({ type: 'blob' });
// Create download link
const url = URL.createObjectURL(content);
const link = document.createElement('a');
link.href = url;
link.download = `${project.id}.zip`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
toast({
title: "Project exported successfully",
description: `"${project.name}" has been downloaded as a zip file.`,
});
} catch (error) {
console.error('Failed to export project:', error);
toast({
title: "Failed to export project",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
} finally {
setIsExporting(false);
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md" onOpenAutoFocus={(e) => e.preventDefault()}>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Folder className="h-5 w-5" />
{project.name}
</DialogTitle>
</DialogHeader>
<div className="space-y-4">
{/* Last Modified */}
<div className="flex items-center gap-2 text-sm">
<Calendar className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Last Modified:</span>
<span>{formatDistanceToNow(project.lastModified)}</span>
</div>
{/* Project Name */}
<div className="space-y-2">
<Label htmlFor="project-name">Project Name</Label>
<div className="flex items-center gap-2">
<Input
id="project-name"
value={newProjectName}
onChange={(e) => setNewProjectName(e.target.value)}
disabled={isRenaming}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleSaveProject();
} else if (e.key === 'Escape') {
setNewProjectName(project.id);
}
}}
className="flex-1"
placeholder="Enter project name"
/>
<Button
size="sm"
onClick={handleSaveProject}
disabled={isRenaming || !newProjectName.trim() || newProjectName === project.id}
className="h-10"
>
{isRenaming ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Save className="h-4 w-4" />
)}
</Button>
</div>
</div>
<Separator />
{/* Export Project Button */}
<Button
onClick={handleExportProject}
disabled={isExporting || isDeleting || isRenaming}
className="w-full gap-2"
variant="outline"
>
{isExporting ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Download className="h-4 w-4" />
)}
{isExporting ? 'Exporting...' : 'Export Project'}
</Button>
{/* Delete Project Button */}
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
variant="destructive"
className="w-full gap-2"
disabled={isExporting || isDeleting || isRenaming}
>
<Trash2 className="h-4 w-4" />
Delete Project
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Project</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete "{project.name}"? This action cannot be undone and will permanently delete all project data including files.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleDeleteProject}
disabled={isDeleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isDeleting ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Deleting...
</>
) : (
'Delete Project'
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</DialogContent>
</Dialog>
);
}
+145
View File
@@ -0,0 +1,145 @@
import { render, screen, fireEvent } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { ProjectSidebar } from './ProjectSidebar';
import { useProjects } from '@/hooks/useProjects';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { TestApp } from '@/test/TestApp';
// Mock the hooks
vi.mock('@/hooks/useProjects');
vi.mock('@/hooks/useLocalStorage');
vi.mock('@/hooks/useProjectSessionStatus', () => ({
useProjectSessionStatus: () => ({ hasRunningSessions: false })
}));
vi.mock('react-router-dom', async (importOriginal) => {
const actual = await importOriginal() as Record<string, unknown>;
return {
...actual,
useNavigate: () => vi.fn()
};
});
vi.mock('@tanstack/react-query', async (importOriginal) => {
const actual = await importOriginal() as Record<string, unknown>;
return {
...actual,
useQueryClient: () => ({
invalidateQueries: vi.fn(),
resetQueries: vi.fn()
})
};
});
// Mock window.open for help button test
const mockWindowOpen = vi.fn();
Object.defineProperty(window, 'open', {
value: mockWindowOpen,
writable: true
});
const mockUseProjects = vi.mocked(useProjects);
const mockUseLocalStorage = vi.mocked(useLocalStorage);
describe('ProjectSidebar', () => {
beforeEach(() => {
mockUseProjects.mockReturnValue({
data: [],
isLoading: false,
error: null
} as unknown as ReturnType<typeof useProjects>);
mockUseLocalStorage.mockReturnValue([[], vi.fn()]);
});
it('renders sidebar header with logo', () => {
render(
<TestApp>
<ProjectSidebar
selectedProject={null}
onSelectProject={vi.fn()}
/>
</TestApp>
);
expect(screen.getByAltText('Shakespeare')).toBeInTheDocument();
expect(screen.getByText('Shakespeare')).toBeInTheDocument();
});
it('shows collapse button when onToggleSidebar is provided', () => {
const mockToggle = vi.fn();
render(
<TestApp>
<ProjectSidebar
selectedProject={null}
onSelectProject={vi.fn()}
onToggleSidebar={mockToggle}
/>
</TestApp>
);
const collapseButton = screen.getByLabelText('Collapse sidebar');
expect(collapseButton).toBeInTheDocument();
fireEvent.click(collapseButton);
expect(mockToggle).toHaveBeenCalledTimes(1);
});
it('does not show collapse button when onToggleSidebar is not provided', () => {
render(
<TestApp>
<ProjectSidebar
selectedProject={null}
onSelectProject={vi.fn()}
/>
</TestApp>
);
expect(screen.queryByLabelText('Collapse sidebar')).not.toBeInTheDocument();
});
it('renders settings and help buttons at the bottom', () => {
render(
<TestApp>
<ProjectSidebar
selectedProject={null}
onSelectProject={vi.fn()}
/>
</TestApp>
);
expect(screen.getByText('Settings')).toBeInTheDocument();
expect(screen.getByLabelText('Help')).toBeInTheDocument();
});
it('shows new project button', () => {
render(
<TestApp>
<ProjectSidebar
selectedProject={null}
onSelectProject={vi.fn()}
/>
</TestApp>
);
expect(screen.getByText('New Project')).toBeInTheDocument();
});
it('opens help documentation when help button is clicked', () => {
render(
<TestApp>
<ProjectSidebar
selectedProject={null}
onSelectProject={vi.fn()}
/>
</TestApp>
);
const helpButton = screen.getByLabelText('Help');
fireEvent.click(helpButton);
expect(mockWindowOpen).toHaveBeenCalledWith(
'https://soapbox.pub/shakespeare-resources/',
'_blank'
);
});
});
+189 -422
View File
@@ -1,351 +1,198 @@
import React, { useState } from 'react';
import React, { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Plus, Loader2, Info, MoreVertical, Trash2, Eye, Star, Bug, Folder, Download } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Label } from '@/components/ui/label';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
import { LoginArea } from '@/components/auth/LoginArea';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useProjects } from '@/hooks/useProjects';
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useToast } from '@/hooks/useToast';
import { useFS } from '@/hooks/useFS';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { Project } from '@/lib/ProjectsManager';
import { cn } from '@/lib/utils';
import JSZip from 'jszip';
import git from 'isomorphic-git';
import { useQueryClient } from '@tanstack/react-query';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
interface ProjectItemProps {
project: Project;
isSelected: boolean;
onSelect: (project: Project) => void;
isFavorite?: boolean;
}
const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect, isFavorite }) => {
const navigate = useNavigate();
const { hasRunningSessions } = useProjectSessionStatus(project.id);
const handleClick = () => {
onSelect(project);
navigate(`/project/${project.id}`);
};
return (
<div
className={cn(
"group relative rounded-lg transition-all duration-200 hover:bg-gradient-to-r hover:from-primary/10 hover:to-accent/10",
isSelected && "bg-gradient-to-r from-primary/15 to-accent/15 shadow-sm"
)}
>
<div className="w-full px-3 py-2 text-left text-sidebar-foreground">
<button
onClick={handleClick}
className="absolute inset-0"
/>
<div className="flex items-center gap-3">
<div className="flex-shrink-0">
{hasRunningSessions ? (
<Loader2 className="h-4 w-4 animate-spin text-blue-600 dark:text-blue-400" />
) : (
<Folder className="h-4 w-4 text-primary" />
)}
</div>
<div className="flex justify-between gap-2 flex-1 min-w-0">
<div className="min-w-0 flex-1 flex items-center">
<h3 className="font-medium text-sm truncate">
{project.name}
</h3>
</div>
{/* Star indicator - only shown when favorited */}
{isFavorite && (
<div className="flex-shrink-0 relative -mr-1 pointer-events-none">
<div className="flex items-center justify-center">
<Star className="h-4 w-4 text-yellow-500 fill-current" />
</div>
</div>
)}
</div>
</div>
</div>
</div>
);
};
ProjectItem.displayName = 'ProjectItem';
interface ProjectSidebarProps {
selectedProject: Project | null;
onSelectProject: (project: Project | null) => void;
className?: string;
onToggleSidebar?: () => void;
onClose?: () => void;
}
export function ProjectSidebar({
selectedProject,
onSelectProject,
className
className,
onToggleSidebar,
onClose
}: ProjectSidebarProps) {
const [projects, setProjects] = useState<Project[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isDeleting, setIsDeleting] = useState(false);
const [isExporting, setIsExporting] = useState(false);
const [favorites, setFavorites] = useLocalStorage<string[]>('project-favorites', []);
const projectsManager = useProjectsManager();
const { t } = useTranslation();
const queryClient = useQueryClient();
const { data: projects = [], isLoading, error } = useProjects();
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
const isMobile = useIsMobile();
const navigate = useNavigate();
const { toast } = useToast();
const { fs } = useFS();
// Load projects on mount
React.useEffect(() => {
const loadProjects = async () => {
try {
await projectsManager.init();
const projectList = await projectsManager.getProjects();
setProjects(projectList);
} catch (error) {
console.error('Failed to load projects:', error);
} finally {
setIsLoading(false);
}
};
loadProjects();
}, [projectsManager]);
// Custom navigate function that closes sidebar on mobile
const navigateAndClose = (path: string) => {
navigate(path);
if (isMobile && onClose) {
onClose();
}
};
const handleNewProject = () => {
onSelectProject(null);
navigate('/');
navigateAndClose('/');
};
const handleDeleteProject = async (project: Project) => {
setIsDeleting(true);
try {
await projectsManager.deleteProject(project.id);
// Remove from local state
setProjects(prev => prev.filter(p => p.id !== project.id));
// If the deleted project was selected, deselect it
if (selectedProject?.id === project.id) {
onSelectProject(null);
navigate('/');
}
toast({
title: "Project deleted",
description: `"${project.name}" has been permanently deleted.`,
});
} catch (error) {
toast({
title: "Failed to delete project",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
} finally {
setIsDeleting(false);
const handleToggleSidebar = () => {
if (onToggleSidebar) {
onToggleSidebar();
} else if (onClose && isMobile) {
onClose();
}
};
const handleToggleFavorite = (project: Project) => {
const wasFavorite = favorites.includes(project.id);
const newFavorites = wasFavorite
? favorites.filter(id => id !== project.id)
: [...favorites, project.id];
setFavorites(newFavorites);
toast({
title: wasFavorite ? "Project Unfavorited" : "Project Favorited",
description: `"${project.name}" has been ${wasFavorite ? 'removed from' : 'added to'} your favorites.`,
});
};
useEffect(() => {
queryClient.invalidateQueries({ queryKey: ['projects'] });
}, [favorites, queryClient]);
const isFavorite = (projectId: string) => favorites.includes(projectId);
const exportFilesAsZip = async (projectName: string) => {
const zip = new JSZip();
// Recursive function to add files and directories to zip
const addToZip = async (dirPath: string, zipFolder: JSZip) => {
try {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = dirPath === '/' ? `/${entry.name}` : `${dirPath}/${entry.name}`;
if (entry.isDirectory()) {
// Create folder in zip and recursively add its contents
const folder = zipFolder.folder(entry.name);
if (folder) {
await addToZip(fullPath, folder);
}
} else if (entry.isFile()) {
// Add file to zip
try {
const fileContent = await fs.readFile(fullPath);
zipFolder.file(entry.name, fileContent);
} catch (error) {
console.warn(`Failed to read file ${fullPath}:`, error);
}
}
}
} catch (error) {
console.warn(`Failed to read directory ${dirPath}:`, error);
}
};
// Start from root directory
await addToZip('/', zip);
// Generate zip file
const content = await zip.generateAsync({ type: 'blob' });
// Create download link
const url = URL.createObjectURL(content);
const link = document.createElement('a');
link.href = url;
// Generate filename with date
const now = new Date();
const dateStr = now.toISOString().split('T')[0]; // YYYY-MM-DD format
link.download = `${projectName}-${dateStr}.zip`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
};
const handleExportFiles = async () => {
setIsExporting(true);
try {
const projectName = selectedProject?.name || 'shakespeare';
await exportFilesAsZip(projectName);
toast({
title: "Files exported successfully",
description: "Your project files have been downloaded as a zip file.",
});
} catch (error) {
console.error('Failed to export files:', error);
toast({
title: "Failed to export files",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
} finally {
setIsExporting(false);
}
};
const handleExportProject = async (project: Project) => {
setIsExporting(true);
try {
const zip = new JSZip();
const projectPath = `/projects/${project.id}`;
// Recursive function to add files and directories to zip from a specific project
const addProjectToZip = async (dirPath: string, zipFolder: JSZip) => {
try {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
if (entry.isDirectory()) {
// Create folder in zip and recursively add its contents
const folder = zipFolder.folder(entry.name);
if (folder) {
await addProjectToZip(fullPath, folder);
}
} else if (entry.isFile()) {
// Add file to zip
try {
const fileContent = await fs.readFile(fullPath);
zipFolder.file(entry.name, fileContent);
} catch (error) {
console.warn(`Failed to read file ${fullPath}:`, error);
}
}
}
} catch (error) {
console.warn(`Failed to read directory ${dirPath}:`, error);
}
};
// Start from the project directory
await addProjectToZip(projectPath, zip);
// Generate zip file
const content = await zip.generateAsync({ type: 'blob' });
// Create download link
const url = URL.createObjectURL(content);
const link = document.createElement('a');
link.href = url;
// Generate filename with commit hash
let filename = `${project.name}.zip`;
try {
// Get the current commit hash
const commits = await git.log({
fs,
dir: projectPath,
depth: 1,
});
if (commits.length > 0) {
const commitHash = commits[0].oid.substring(0, 7); // Truncate to 7 characters
filename = `${project.name}-${commitHash}.zip`;
}
} catch (error) {
console.warn('Failed to get commit hash, using project name only:', error);
}
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
toast({
title: "Project exported successfully",
description: `"${project.name}" has been downloaded as a zip file.`,
});
} catch (error) {
console.error('Failed to export project:', error);
toast({
title: "Failed to export project",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
} finally {
setIsExporting(false);
}
};
// Sort projects: favorites first, then by lastModified (newest first)
const sortedProjects = projects.sort((a, b) => {
const aIsFavorite = isFavorite(a.id);
const bIsFavorite = isFavorite(b.id);
if (aIsFavorite && !bIsFavorite) return -1;
if (!aIsFavorite && bIsFavorite) return 1;
return b.lastModified.getTime() - a.lastModified.getTime();
});
if (error) {
console.error('Failed to load projects:', error);
}
return (
<div className={cn("flex flex-col h-full bg-gradient-to-b from-sidebar to-sidebar/95", className)}>
{/* Header with Logo */}
<div className="p-4 border-b border-sidebar-border bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10">
<button
onClick={() => navigate('/')}
className="flex items-center gap-3 hover:opacity-80 transition-opacity w-full text-left"
>
<span className="text-2xl">🎭</span>
<h1 className="text-xl font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Shakespeare
</h1>
</button>
</div>
{/* Info Section */}
<div className="p-4 border-b border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5">
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs font-medium text-primary/80 uppercase tracking-wide">
Projects
</Label>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm" className="h-4 w-4 p-0 hover:bg-primary/10">
<MoreVertical className="h-3 w-3 text-primary/60 hover:text-primary" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem
onClick={handleExportFiles}
disabled={isExporting}
className="flex items-center gap-2 w-full"
>
<Download className="h-4 w-4" />
{isExporting ? 'Exporting...' : 'Export Files'}
</DropdownMenuItem>
<DropdownMenuItem asChild>
<a href="https://soapbox.pub/mkstack" target="_blank" rel="noopener noreferrer" className="flex items-center gap-2 w-full">
<Info className="h-4 w-4" />
About MKStack
</a>
</DropdownMenuItem>
<DropdownMenuItem asChild>
<a href="https://github.com/soapbox-pub/mkstack/issues" target="_blank" rel="noopener noreferrer" className="flex items-center gap-2 w-full">
<Bug className="h-4 w-4" />
Report an Issue
</a>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
<div className="flex px-4 h-12 border-b border-sidebar-border bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10">
<div className="flex items-center justify-between w-full">
<button
onClick={() => navigateAndClose('/')}
className="flex items-center gap-3 hover:opacity-80 transition-opacity text-left"
>
<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">
Shakespeare
</h1>
</button>
{(onToggleSidebar || (onClose && isMobile)) && (
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
onClick={handleToggleSidebar}
aria-label={(onClose && isMobile) ? t('closeSidebar') : t('collapseSidebar')}
>
{(onClose && isMobile) ? (
<X className="h-4 w-4 text-primary/60 hover:text-primary" />
) : (
<Columns2 className="h-4 w-4 text-primary/60 hover:text-primary" />
)}
</Button>
</div>
)}
</div>
</div>
<div className="flex-1 overflow-y-auto">
<div className="p-2">
<div className="mb-2">
<Button
size="sm"
className="w-full bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90"
onClick={handleNewProject}
>
<Plus className="h-4 w-4 mr-2" />
New Project
</Button>
<div className="relative rounded-md bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90 transition-all duration-200">
<div className="flex">
<button
onClick={handleNewProject}
className="flex-1 flex items-center justify-center px-3 py-2 text-sm font-medium text-primary-foreground rounded-l-md hover:bg-white/10 transition-colors"
>
<Plus className="h-4 w-4 mr-2" />
{t('newProject')}
</button>
<div className="w-px bg-white/20" />
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="px-2 py-2 text-primary-foreground hover:bg-white/10 rounded-r-md transition-colors">
<ChevronDown className="h-4 w-4" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem
onClick={() => navigateAndClose('/clone')}
className="flex items-center gap-2 w-full"
>
<GitBranch className="h-4 w-4" />
{t('importRepository')}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
</div>
{isLoading ? (
@@ -362,130 +209,50 @@ export function ProjectSidebar({
) : projects.length === 0 ? (
<div className="text-center p-6 text-muted-foreground">
<Folder className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">No projects yet</p>
<p className="text-xs">Create your first project to get started</p>
<p className="text-sm">{t('noProjectsYet')}</p>
<p className="text-xs">{t('createFirstProject')}</p>
</div>
) : (
<div className="space-y-1">
{sortedProjects.map((project) => (
<div
key={project.id}
className={cn(
"group relative rounded-lg transition-all duration-200 hover:bg-gradient-to-r hover:from-primary/10 hover:to-accent/10",
selectedProject?.id === project.id && "bg-gradient-to-r from-primary/15 to-accent/15 shadow-sm"
)}
>
<button
onClick={() => {
onSelectProject(project);
navigate(`/project/${project.id}`);
}}
className="w-full p-3 text-left text-sidebar-foreground"
>
<div className="flex items-center gap-3">
<div className="flex items-start justify-between gap-2 flex-1 min-w-0">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 mb-1">
<h3 className="font-medium text-sm truncate">
{project.name}
</h3>
<div className="flex items-center gap-1 ml-auto">
{isFavorite(project.id) && (
<Star className="h-3 w-3 text-yellow-500 fill-current" />
)}
</div>
</div>
</div>
{/* Dropdown Menu */}
<div className="flex-shrink-0 -mt-1 -mr-1">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 hover:bg-primary/20"
onClick={(e) => e.stopPropagation()}
>
<MoreVertical className="h-3 w-3" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem
onClick={() => handleToggleFavorite(project)}
>
<Star className={cn(
"h-4 w-4 mr-2",
isFavorite(project.id) ? "text-yellow-500 fill-current" : "text-muted-foreground"
)} />
{isFavorite(project.id) ? "Unfavorite" : "Favorite"}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => navigate(`/project/${project.id}`)}
>
<Eye className="h-4 w-4 mr-2" />
Open Project
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleExportProject(project)}
disabled={isExporting}
>
<Download className="h-4 w-4 mr-2" />
{isExporting ? 'Exporting...' : 'Export Project'}
</DropdownMenuItem>
<AlertDialog>
<AlertDialogTrigger asChild>
<DropdownMenuItem
className="text-destructive focus:text-destructive cursor-pointer"
onSelect={(e) => e.preventDefault()}
>
<Trash2 className="h-4 w-4 mr-2" />
Delete Project
</DropdownMenuItem>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Project</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete "{project.name}"? This action cannot be undone and will permanently delete all project data including files.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => handleDeleteProject(project)}
disabled={isDeleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isDeleting ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Deleting...
</>
) : (
'Delete Project'
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
</div>
</button>
</div>
))}
{projects.map((project) => (
<ProjectItem
key={project.id}
project={project}
isSelected={selectedProject?.id === project.id}
onSelect={onSelectProject}
isFavorite={favorites.includes(project.id)}
/>
))}
</div>
)}
</div>
</div>
{/* Account Selector at Bottom */}
<div className="p-4 border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto">
<LoginArea className="w-full" />
{/* Settings and Help at Bottom */}
<div className="p-2 border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto">
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="sm"
className="flex-1 h-9 justify-start gap-2 text-sidebar-foreground dark:hover:text-sidebar-primary hover:bg-primary/10 dark:hover:bg-sidebar-accent/30 transition-all duration-200"
onClick={() => navigateAndClose('/settings')}
>
<Settings className="h-4 w-4 transition-colors duration-200" />
{t('settings')}
</Button>
<Button
variant="ghost"
size="sm"
className="h-9 w-9 p-0 text-sidebar-foreground dark:hover:text-sidebar-primary hover:bg-primary/10 dark:hover:bg-sidebar-accent/30 transition-all duration-200"
onClick={() => window.open('https://soapbox.pub/shakespeare-resources/', '_blank')}
aria-label={t('help')}
>
<HelpCircle className="h-4 w-4 transition-colors duration-200" />
</Button>
</div>
</div>
</div>
);
}
+177
View File
@@ -0,0 +1,177 @@
import OpenAI from 'openai';
import { useNavigate } from 'react-router-dom';
import { X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { QuillySVG } from '@/components/ui/QuillySVG';
import { useAISettings } from '@/hooks/useAISettings';
import { parseProviderModel } from '@/lib/parseProviderModel';
import { useAICredits } from '@/hooks/useAICredits';
import { CreditsDialog } from './CreditsDialog';
import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool';
import { useState } from 'react';
export interface QuillyProps {
error: Error;
onDismiss: () => void;
onNewChat: () => void;
onOpenModelSelector: () => void;
onRequestConsoleErrorHelp?: (error: ProjectPreviewConsoleError) => void;
providerModel: string;
}
interface ErrorBody {
message: string;
action?: {
label: string;
onClick: () => void;
};
}
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
const navigate = useNavigate();
const { settings } = useAISettings();
// Handle empty provider model gracefully
let provider;
try {
provider = parseProviderModel(providerModel, settings.providers).provider;
} catch {
// If no valid provider model, use a default or undefined
provider = undefined;
}
const credits = useAICredits(provider || { id: '', name: '', apiKey: '', nostr: false });
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
const renderBody = (error: Error): ErrorBody => {
// Handle Project Preview Console Errors
if (error instanceof ProjectPreviewConsoleError) {
return {
message: 'I noticed some console errors in your project preview. Would you like me to take a look and help fix them?',
action: {
label: 'Help fix errors',
onClick: () => {
onRequestConsoleErrorHelp?.(error);
onDismiss();
},
},
};
}
// Handle OpenAI API errors with specific error codes
if (error instanceof OpenAI.APIError) {
switch (error.code) {
case 'invalid_api_key':
case 'invalid_request_error':
return {
message: 'Authentication error: Please check your API key in AI settings.',
action: {
label: 'Check API key',
onClick: () => navigate('/settings/ai'),
}
};
case 'insufficient_quota': {
if (credits.data) {
return {
message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`,
action: {
label: 'Add credits',
onClick: () => setShowCreditsDialog(true),
}
};
} else {
return {
message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.',
action: {
label: 'Check AI settings',
onClick: () => navigate('/settings/ai'),
}
};
}
}
case 'rate_limit_exceeded':
return {
message: 'Rate limit exceeded. Please wait a moment before trying again.',
};
case 'model_not_found':
return {
message: 'The selected AI model is not available. Please choose a different model.',
action: {
label: 'Choose model',
onClick: onOpenModelSelector,
},
};
case 'context_length_exceeded':
return {
message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.',
action: {
label: 'New chat',
onClick: onNewChat,
},
};
case 'server_error':
case 'service_unavailable':
return {
message: 'The AI service is temporarily unavailable. Please try again in a moment.',
};
default:
return {
message: `AI service error: ${error.message}`,
};
}
}
// Default fallback
return {
message: error.message
? `AI service error: ${error.message}`
: 'Sorry, I encountered an unexpected error. Please try again.',
};
};
const { message, action } = renderBody(error);
return (
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
<div className="flex items-start gap-2">
<QuillySVG className="h-20 px-2 flex-shrink-0" fillColor="hsl(var(--primary))" />
<div className="flex-1 min-w-0">
<div className="space-y-1">
<h4 className="font-semibold text-primary">
Pardon the interruption
</h4>
<p className="text-sm text-muted-foreground">
{message}
{' '}
{action && (
<button className="text-primary underline" onClick={action.onClick}>
{action.label}
</button>
)}
</p>
</div>
</div>
<Button
variant="ghost"
size="sm"
onClick={onDismiss}
className="h-5 w-5 p-0 hover:text-foreground/70 hover:bg-transparent flex-shrink-0"
>
<X className="h-4 w-4" />
</Button>
</div>
<CreditsDialog
open={showCreditsDialog}
onOpenChange={setShowCreditsDialog}
provider={provider}
/>
</div>
);
}
+43
View File
@@ -0,0 +1,43 @@
import { ReactNode, useMemo, useEffect } from 'react';
import { SessionManagerContext } from '@/contexts/SessionManagerContext';
import { SessionManager } from '@/lib/SessionManager';
import { useFS } from '@/hooks/useFS';
import { useAISettings } from '@/hooks/useAISettings';
import { useProviderModels } from '@/hooks/useProviderModels';
import { useCurrentUser } from '@/hooks/useCurrentUser';
interface SessionManagerProviderProps {
children: ReactNode;
}
/**
* Provider that creates and manages the global session manager instance
*/
export function SessionManagerProvider({ children }: SessionManagerProviderProps) {
const { fs } = useFS();
const { settings } = useAISettings();
const { models } = useProviderModels();
const { user, metadata } = useCurrentUser();
const sessionManager = useMemo(() => {
const getProviderModels = () => models;
const getCurrentUser = () => ({ user, metadata });
return new SessionManager(fs, settings, getProviderModels, getCurrentUser);
}, [fs, settings, models, user, metadata]);
// Cleanup on unmount
useEffect(() => {
return () => {
// Fire and forget cleanup - we don't need to await in useEffect cleanup
sessionManager.cleanup().catch(error => {
console.warn('Failed to cleanup session manager:', error);
});
};
}, [sessionManager]);
return (
<SessionManagerContext.Provider value={sessionManager}>
{children}
</SessionManagerContext.Provider>
);
}
+79
View File
@@ -0,0 +1,79 @@
import { useEffect, useRef } from 'react';
import { useSessionManager } from '@/hooks/useSessionManager';
import { useToast } from '@/hooks/useToast';
import { useNavigate, useLocation } from 'react-router-dom';
/**
* Global component that monitors AI sessions and shows notifications
* when sessions complete in the background
*/
export function SessionMonitor() {
const sessionManager = useSessionManager();
const { toast } = useToast();
const navigate = useNavigate();
const location = useLocation();
const previousLoadingStates = useRef<Map<string, boolean>>(new Map());
useEffect(() => {
const handleLoadingChanged = (projectId: string, isLoading: boolean) => {
const wasLoading = previousLoadingStates.current.get(projectId);
previousLoadingStates.current.set(projectId, isLoading);
// If session just finished loading (was loading, now not loading)
if (wasLoading && !isLoading) {
const session = sessionManager.getSession(projectId);
if (!session) return;
// Check if user is currently viewing this project
const currentProjectId = location.pathname.split('/')[2]; // /project/{projectId}
const isCurrentProject = session.projectId === currentProjectId;
// Only show notification if user is not currently viewing this project
if (!isCurrentProject) {
toast({
title: "AI Session Complete",
description: `Finished working on ${session.projectId}`,
action: (
<button
onClick={() => navigate(`/project/${session.projectId}`)}
className="inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus-visible:ring-destructive"
>
View
</button>
)
});
}
}
};
const handleSessionCreated = (projectId: string) => {
const session = sessionManager.getSession(projectId);
if (session) {
previousLoadingStates.current.set(projectId, session.isLoading);
}
};
const handleSessionDeleted = (projectId: string) => {
previousLoadingStates.current.delete(projectId);
};
// Initialize with current sessions
sessionManager.getAllSessions().forEach(session => {
previousLoadingStates.current.set(session.projectId, session.isLoading);
});
// Subscribe to events
sessionManager.on('loadingChanged', handleLoadingChanged);
sessionManager.on('sessionCreated', handleSessionCreated);
sessionManager.on('sessionDeleted', handleSessionDeleted);
return () => {
sessionManager.off('loadingChanged', handleLoadingChanged);
sessionManager.off('sessionCreated', handleSessionCreated);
sessionManager.off('sessionDeleted', handleSessionDeleted);
};
}, [sessionManager, toast, navigate, location.pathname]);
// This component doesn't render anything
return null;
}
+245
View File
@@ -0,0 +1,245 @@
import { useState, useEffect } from 'react';
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react';
import { ProjectSidebar } from '@/components/ProjectSidebar';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useIsMobile } from '@/hooks/useIsMobile';
import { type Project } from '@/lib/ProjectsManager';
import { useCallback } from 'react';
import { cn } from '@/lib/utils';
interface SettingsItem {
id: string;
title: string;
description: string;
icon: React.ComponentType<{ className?: string }>;
href: string;
}
// Define settings items as a function to get fresh translations
const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [
{
id: 'preferences',
title: t('preferences'),
description: t('preferencesDescription'),
icon: Settings2,
href: '/settings/preferences',
},
{
id: 'ai',
title: t('aiSettings'),
description: t('aiSettingsDescription'),
icon: Bot,
href: '/settings/ai',
},
{
id: 'git',
title: t('gitSettings'),
description: t('gitSettingsDescription'),
icon: GitBranch,
href: '/settings/git',
},
{
id: 'nostr',
title: t('nostrSettings'),
description: t('nostrSettingsDescription'),
icon: Wifi,
href: '/settings/nostr',
},
{
id: 'data',
title: t('dataSettings'),
description: t('dataSettingsDescription'),
icon: Database,
href: '/settings/data',
},
{
id: 'about',
title: t('aboutShakespeare'),
description: t('aboutShakespeareDescription'),
icon: Info,
href: '/settings/about',
},
];
export function SettingsLayout() {
const { t } = useTranslation();
const navigate = useNavigate();
const location = useLocation();
const isMobile = useIsMobile();
const projectsManager = useProjectsManager();
const [_projects, setProjects] = useState<Project[]>([]);
const [isSidebarVisible, setIsSidebarVisible] = useState(!isMobile);
const [hasSetInitialState, setHasSetInitialState] = useState(false);
const loadProjects = useCallback(async () => {
try {
await projectsManager.init();
const projectList = await projectsManager.getProjects();
setProjects(projectList);
// Set initial sidebar state based on projects and device type
if (!hasSetInitialState && !isMobile) {
// On desktop, show sidebar if there are projects
setIsSidebarVisible(true);
setHasSetInitialState(true);
} else if (!hasSetInitialState && isMobile) {
// On mobile, always start hidden
setIsSidebarVisible(false);
setHasSetInitialState(true);
}
} catch (error) {
console.error('Failed to load projects:', error);
if (!hasSetInitialState) {
setHasSetInitialState(true);
}
}
}, [projectsManager, hasSetInitialState, isMobile]);
useEffect(() => {
loadProjects();
}, [loadProjects]);
const handleProjectSelect = (project: Project | null) => {
if (project) {
setIsSidebarVisible(false); // Collapse sidebar on mobile navigation
navigate(`/project/${project.id}`);
} else {
navigate('/');
}
};
// Get current settings page
const settingsItems = getSettingsItems(t);
const currentPath = location.pathname;
const currentSettingsId = settingsItems.find(item => item.href === currentPath)?.id;
if (isMobile) {
return (
<div className="min-h-dvh bg-background">
{/* Mobile Header */}
<header className="h-12 border-b bg-background px-4 py-3 flex items-center justify-between">
<div className="flex items-center space-x-2">
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
aria-label={t('toggleSidebar')}
>
<Menu className="h-4 w-4" />
</Button>
<h1 className="text-lg font-semibold">{t('settings')}</h1>
</div>
</header>
{/* Mobile Sidebar Overlay */}
{isSidebarVisible && (
<div className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm">
<div
className="absolute inset-0"
onClick={() => setIsSidebarVisible(false)}
/>
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
<ProjectSidebar
selectedProject={null}
onSelectProject={(project) => {
setIsSidebarVisible(false);
handleProjectSelect(project);
}}
onClose={() => setIsSidebarVisible(false)}
/>
</div>
</div>
)}
<Outlet />
</div>
);
}
// Desktop 3-column layout
return (
<div className="h-screen flex bg-background overflow-hidden">
{/* Left Column - Projects Sidebar (optionally hidden) */}
{isSidebarVisible && (
<div className="w-80 border-r bg-sidebar flex-shrink-0">
<ProjectSidebar
selectedProject={null}
onSelectProject={handleProjectSelect}
className="h-full"
onToggleSidebar={() => setIsSidebarVisible(false)}
/>
</div>
)}
{/* Middle Column - Settings Navigation */}
<div className="w-96 border-r bg-background flex flex-col flex-shrink-0">
{/* Header with toggle button */}
<div className="h-12 px-4 py-2 border-b flex-shrink-0">
<div className="flex items-center gap-3">
{!isSidebarVisible && (
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(true)}
className="h-8 w-8 p-0"
aria-label={t('openSidebar')}
>
<Menu className="h-4 w-4" />
</Button>
)}
<h1 className="text-xl font-bold flex items-center gap-2">
{t('settings')}
</h1>
</div>
</div>
{/* Settings Navigation - Scrollable */}
<ScrollArea className="flex-1">
<div className="p-4">
<div className="space-y-2">
{settingsItems.map((item) => {
const Icon = item.icon;
const isActive = currentSettingsId === item.id;
return (
<button
key={item.id}
onClick={() => navigate(item.href)}
className={cn('w-full text-left p-3 rounded-lg transition-colors border border-transparent', {
'bg-primary/10 border border-primary/20': isActive,
'hover:bg-muted/50': !isActive,
})}
>
<div className="flex items-start gap-3">
<Icon className={`h-5 w-5 mt-0.5 ${isActive ? 'text-primary' : 'text-muted-foreground'}`} />
<div className="flex-1 min-w-0">
<div className={`font-medium ${isActive ? 'text-primary' : 'text-foreground'}`}>
{item.title}
</div>
<div className="text-sm text-muted-foreground mt-0.5">
{item.description}
</div>
</div>
</div>
</button>
);
})}
</div>
</div>
</ScrollArea>
</div>
{/* Right Column - Settings Content - Scrollable */}
<ScrollArea className="flex-1 bg-background">
<div className="max-w-4xl">
<Outlet />
</div>
</ScrollArea>
</div>
);
}
File diff suppressed because it is too large. Load diff
+36 -6
View File
@@ -1,21 +1,26 @@
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Save, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useGitStatus } from '@/hooks/useGitStatus';
interface FileEditorProps {
filePath: string;
content: string;
onSave: (content: string) => void;
isLoading: boolean;
projectId?: string;
}
export function FileEditor({ filePath, content, onSave, isLoading }: FileEditorProps) {
export function FileEditor({ filePath, content, onSave, isLoading, projectId }: FileEditorProps) {
const { t } = useTranslation();
const [editedContent, setEditedContent] = useState(content);
const [isSaving, setIsSaving] = useState(false);
const [hasChanges, setHasChanges] = useState(false);
const { data: gitStatus } = useGitStatus(projectId || null);
useEffect(() => {
setEditedContent(content);
@@ -64,14 +69,39 @@ export function FileEditor({ filePath, content, onSave, isLoading }: FileEditorP
return 'font-mono text-sm';
};
// Helper function to get git status for the current file
const getFileGitStatus = (filePath: string) => {
if (!gitStatus?.changedFiles) return null;
const fileChange = gitStatus.changedFiles.find(change => change.filepath === filePath);
return fileChange?.status || null;
};
// Helper function to get styling classes based on git status
const getGitStatusClasses = (status: string | null) => {
switch (status) {
case 'added':
case 'untracked':
return 'text-green-600 dark:text-green-400';
case 'modified':
case 'staged':
return 'text-yellow-600 dark:text-yellow-400';
default:
return '';
}
};
// Get git status for the current file
const currentFileGitStatus = getFileGitStatus(filePath);
const gitStatusClasses = getGitStatusClasses(currentFileGitStatus);
return (
<div className="h-full flex flex-col">
<CardHeader className="border-b py-2 sm:py-3">
<div className="flex items-center justify-between">
<CardTitle className="text-sm sm:text-base truncate flex-1 mr-2">{filePath}</CardTitle>
<CardTitle className={cn("text-sm sm:text-base truncate flex-1 mr-2", gitStatusClasses)}>{filePath}</CardTitle>
<div className="flex items-center space-x-1 sm:space-x-2">
{hasChanges && (
<span className="text-xs sm:text-sm text-muted-foreground hidden sm:inline">Unsaved changes</span>
<span className="text-xs sm:text-sm text-muted-foreground hidden sm:inline">{t('unsavedChanges')}</span>
)}
<Button
onClick={handleSave}
@@ -82,19 +112,19 @@ export function FileEditor({ filePath, content, onSave, isLoading }: FileEditorP
{isSaving ? (
<>
<Loader2 className="mr-1 sm:mr-2 h-4 w-4 animate-spin" />
<span className="hidden sm:inline">Saving...</span>
<span className="hidden sm:inline">{t('saving')}</span>
</>
) : (
<>
<Save className="sm:mr-2 h-4 w-4" />
<span className="hidden sm:inline">Save</span>
<span className="hidden sm:inline">{t('save')}</span>
</>
)}
</Button>
</div>
</div>
<div className="text-xs text-muted-foreground mt-1">
Language: {getLanguageFromPath(filePath)}
{t('languageLabel')}: {getLanguageFromPath(filePath)}
</div>
</CardHeader>
+165 -11
View File
@@ -1,8 +1,12 @@
import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useFS } from '@/hooks/useFS';
import { ChevronRight, ChevronDown, File, Folder } from 'lucide-react';
import { useGitStatus } from '@/hooks/useGitStatus';
import { ChevronRight, ChevronDown, File, Folder, Search } from 'lucide-react';
import { cn } from '@/lib/utils';
import { createGitignoreFilter, normalizePathForGitignore } from '@/lib/gitignore';
import { Input } from '@/components/ui/input';
interface FileTreeProps {
projectId: string;
@@ -19,10 +23,65 @@ interface FileNode {
}
export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProps) {
const { t } = useTranslation();
const [tree, setTree] = useState<FileNode[]>([]);
const [filteredTree, setFilteredTree] = useState<FileNode[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [gitignoreFilter, setGitignoreFilter] = useState<{
isIgnored: (path: string) => boolean;
shouldShow: (path: string) => boolean;
} | null>(null);
const [searchTerm, setSearchTerm] = useState('');
const [isSearching, setIsSearching] = useState(false);
const { fs } = useFS();
const projectsManager = useProjectsManager();
const { data: gitStatus } = useGitStatus(projectId);
// Helper function to get git status for a file
const getFileGitStatus = (filePath: string) => {
if (!gitStatus?.changedFiles) return null;
const fileChange = gitStatus.changedFiles.find(change => change.filepath === filePath);
return fileChange?.status || null;
};
// Helper function to get git status for a directory
const getDirectoryGitStatus = (dirPath: string, _children: FileNode[]): 'modified' | 'added' | null => {
if (!gitStatus?.changedFiles) return null;
// Check if any files in this directory or subdirectories have changes
const hasChanges = gitStatus.changedFiles.some(change =>
change.filepath.startsWith(dirPath + '/') ||
(dirPath === '' && !change.filepath.includes('/'))
);
if (!hasChanges) return null;
// Check if all changes are new files (added/untracked)
const relevantChanges = gitStatus.changedFiles.filter(change =>
change.filepath.startsWith(dirPath + '/') ||
(dirPath === '' && !change.filepath.includes('/'))
);
const allAdded = relevantChanges.every(change =>
change.status === 'added' || change.status === 'untracked'
);
return allAdded ? 'added' : 'modified';
};
// Helper function to get styling classes based on git status
const getGitStatusClasses = (status: string | null) => {
switch (status) {
case 'added':
case 'untracked':
return 'text-green-600 dark:text-green-400';
case 'modified':
case 'staged':
return 'text-yellow-600 dark:text-yellow-400';
default:
return '';
}
};
const buildFileTree = useCallback(async (projectId: string, dirPath: string): Promise<FileNode[]> => {
const items = await projectsManager.listFiles(projectId, dirPath);
@@ -67,14 +126,20 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
const loadFileTree = useCallback(async () => {
setIsLoading(true);
try {
// Load gitignore filter
const projectPath = `${projectsManager['dir']}/${projectId}`;
const filter = await createGitignoreFilter(fs, projectPath);
setGitignoreFilter(filter);
const structure = await buildFileTree(projectId, '');
setTree(structure);
setFilteredTree(structure);
} catch (_error) {
console.error('Failed to load file tree:', _error);
} finally {
setIsLoading(false);
}
}, [projectId, buildFileTree]);
}, [projectId, buildFileTree, fs, projectsManager]);
useEffect(() => {
loadFileTree();
@@ -93,7 +158,9 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
});
};
// Update both the original tree and filtered tree
setTree(prev => toggleNode(prev));
setFilteredTree(prev => toggleNode(prev));
};
const handleFileClick = (filePath: string, type: 'file' | 'directory') => {
@@ -104,9 +171,76 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
}
};
// Search functions
const searchInFiles = useCallback(async (nodes: FileNode[], term: string): Promise<FileNode[]> => {
if (!term.trim()) return nodes;
const results: FileNode[] = [];
const searchTermLower = term.toLowerCase();
for (const node of nodes) {
if (node.type === 'file') {
const fileNameMatch = node.name.toLowerCase().includes(searchTermLower);
if (fileNameMatch) {
results.push(node);
}
} else if (node.type === 'directory' && node.children) {
const childResults = await searchInFiles(node.children, term);
if (childResults.length > 0) {
// Create a filtered directory node with matching children
results.push({
...node,
children: childResults,
isOpen: true, // Auto-expand directories with matches
});
}
}
}
return results }, []);
// Perform search when search term changes
useEffect(() => {
const performSearch = async () => {
if (!searchTerm.trim()) {
setFilteredTree(tree);
return;
}
setIsSearching(true);
try {
const results = await searchInFiles(tree, searchTerm);
setFilteredTree(results);
} catch (error) {
console.error('Search failed:', error);
setFilteredTree([]);
} finally {
setIsSearching(false);
}
};
performSearch();
}, [searchTerm, tree, searchInFiles]);
const renderNode = (node: FileNode, depth: number = 0) => {
const isSelected = selectedFile === node.path;
// Get git status for this node
const gitFileStatus = node.type === 'file' ? getFileGitStatus(node.path) : null;
const gitDirStatus = node.type === 'directory' ? getDirectoryGitStatus(node.path, node.children || []) : null;
const gitStatus = gitFileStatus || gitDirStatus;
// Check if this file/directory is gitignored
const normalizedPath = normalizePathForGitignore(node.path);
const isGitignored = gitignoreFilter?.isIgnored(normalizedPath) ?? false;
// Get styling classes for git status
const gitStatusClasses = getGitStatusClasses(gitStatus);
// Apply muted styling for gitignored files
const gitignoreClasses = isGitignored ? 'text-muted-foreground' : '';
return (
<div key={node.path}>
<div
@@ -121,19 +255,19 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
{node.type === 'directory' ? (
<>
{node.isOpen ? (
<ChevronDown className="h-4 w-4 flex-shrink-0" />
<ChevronDown className={cn("h-4 w-4 flex-shrink-0", gitignoreClasses)} />
) : (
<ChevronRight className="h-4 w-4 flex-shrink-0" />
<ChevronRight className={cn("h-4 w-4 flex-shrink-0", gitignoreClasses)} />
)}
<Folder className="h-4 w-4 text-blue-500 flex-shrink-0" />
<Folder className={cn("h-4 w-4 text-blue-500 flex-shrink-0", gitignoreClasses)} />
</>
) : (
<>
<div className="w-4" /> {/* Spacer for alignment */}
<File className="h-4 w-4 text-gray-500 flex-shrink-0" />
<File className={cn("h-4 w-4 text-gray-500 flex-shrink-0", gitignoreClasses)} />
</>
)}
<span className="text-sm truncate">{node.name}</span>
<span className={cn("text-sm whitespace-nowrap", gitStatusClasses, gitignoreClasses)}>{node.name}</span>
</div>
{node.type === 'directory' && node.isOpen && node.children && (
@@ -159,12 +293,32 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
return (
<div className="p-2">
{tree.length === 0 ? (
<div className="text-center text-sm text-muted-foreground py-8">
No files found
{/* Search Section */}
<div className="mb-3">
<div className="relative">
<Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
placeholder={t('searchFiles')}
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-8"
/>
</div>
</div>
{/* File Tree */}
{isSearching ? (
<div className="space-y-2">
{[...Array(3)].map((_, i) => (
<div key={i} className="h-6 bg-muted rounded animate-pulse"></div>
))}
</div>
) : filteredTree.length === 0 ? (
<div className="text-center text-sm text-muted-foreground py-4">
{searchTerm ? t('noFilesFoundSearch') : t('noFilesFound')}
</div>
) : (
tree.map(node => renderNode(node))
filteredTree.map(node => renderNode(node))
)}
</div>
);
+593 -113
View File
@@ -1,18 +1,45 @@
import { encodeBase64 } from '@std/encoding/base64';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useFS } from '@/hooks/useFS';
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/tools/ReadConsoleMessagesTool';
import { useBuildProject } from '@/hooks/useBuildProject';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { RefreshCw, FolderOpen, ArrowLeft } 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 { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
import { cn } from '@/lib/utils';
import { FileTree } from './FileTree';
import { FileEditor } from './FileEditor';
import { DeployDialog } from '@/components/DeployDialog';
import { Terminal as TerminalComponent } from '@/components/Terminal';
import { useSearchParams } from 'react-router-dom';
// Get iframe domain from environment variable
const IFRAME_DOMAIN = import.meta.env.VITE_IFRAME_DOMAIN || 'local-shakespeare.dev';
interface PreviewPaneProps {
projectId: string;
activeTab: 'preview' | 'code';
onToggleView?: () => void;
projectName?: string;
onFirstInteraction?: () => void;
isPreviewable?: boolean;
}
interface JSONRPCRequest {
@@ -36,7 +63,7 @@ interface JSONRPCResponse {
statusText: string;
headers: Record<string, string>;
body: string | null;
};
}
error?: {
code: number;
message: string;
@@ -45,17 +72,57 @@ interface JSONRPCResponse {
id: number;
}
export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction, isPreviewable = true }: PreviewPaneProps) {
const { t } = useTranslation();
const [selectedFile, setSelectedFile] = useState<string | null>(null);
const [fileContent, setFileContent] = useState<string>('');
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 [hasBuiltProject, setHasBuiltProject] = useState(false);
const [currentPath, setCurrentPath] = useState('/');
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
const [historyIndex, setHistoryIndex] = useState(0);
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
const iframeRef = useRef<HTMLIFrameElement>(null);
const { fs } = useFS();
const projectsManager = useProjectsManager();
const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId);
const [searchParams, setSearchParams] = useSearchParams();
const [shouldBuild, setShouldBuild] = useState(false);
const handleBuildProject = useCallback(() => {
buildProject(undefined, {
onError: (error) => {
console.error('Build failed:', error);
}
});
}, [buildProject]);
// Handle "build" URL parameter on initial load
useEffect(() => {
if (searchParams.has('build')) {
setShouldBuild(true);
// Remove the build parameter from URL
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.delete('build');
setSearchParams(newSearchParams, { replace: true });
}
}, [searchParams, setSearchParams]);
// Build automatically if "build" parameter was present
useEffect(() => {
if (shouldBuild && isPreviewable && !isBuildLoading) {
setShouldBuild(false);
handleBuildProject();
}
}, [isBuildLoading, isPreviewable, handleBuildProject, shouldBuild]);
const loadFileContent = useCallback(async (filePath: string) => {
setIsLoading(true);
try {
@@ -105,45 +172,147 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
}
}, [projectId, projectsManager]);
const refreshIframe = useCallback(() => {
// Legacy refresh function for build completion events
const refreshIframeLegacy = useCallback(() => {
if (iframeRef.current) {
// Force reload the iframe by updating its src
const currentSrc = iframeRef.current.src;
iframeRef.current.src = '';
iframeRef.current.src = '/';
// Use a small timeout to ensure the src is cleared before setting it back
setTimeout(() => {
if (iframeRef.current) {
iframeRef.current.src = currentSrc;
iframeRef.current.src = `https://${projectId}.${IFRAME_DOMAIN}/`;
}
}, 10);
}
}, []);
}, [projectId]);
const sendResponse = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
console.log(`Sending response to iframe:`, message);
const targetOrigin = `https://${projectId}.local-shakespeare.dev`;
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
}
}, [projectId]);
const sendError = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
const targetOrigin = `https://${projectId}.local-shakespeare.dev`;
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
}
}, [projectId]);
const handleConsoleMessage = useCallback((message: {
jsonrpc: '2.0';
method: 'console';
params: {
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
message: string;
};
}) => {
const { params } = message;
// Normalize level to ensure it's one of our supported types
let normalizedLevel: ConsoleMessage['level'] = 'log';
if (['log', 'warn', 'error', 'info', 'debug'].includes(params.level)) {
normalizedLevel = params.level as ConsoleMessage['level'];
}
// Add to console messages
addConsoleMessage(normalizedLevel, params.message);
// Log to parent console for debugging with appropriate level
console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`);
}, []);
const handleUpdateNavigationState = useCallback((message: {
jsonrpc: '2.0';
method: 'updateNavigationState';
params: {
currentUrl: string;
canGoBack: boolean;
canGoForward: boolean;
};
}) => {
const { params } = message;
try {
// params.currentUrl is now just a semantic path (e.g., "/about", "/contact?param=value#section")
const path = params.currentUrl;
setCurrentPath(path);
// Update navigation history if this is a new navigation
// But only if it's different from current path (avoid duplicates)
if (path !== navigationHistory[historyIndex]) {
const newHistory = navigationHistory.slice(0, historyIndex + 1);
newHistory.push(path);
setNavigationHistory(newHistory);
setHistoryIndex(newHistory.length - 1);
}
} catch (error) {
console.error('Failed to handle navigation state:', params.currentUrl, error);
}
}, [historyIndex, navigationHistory]);
const sendNavigationCommand = useCallback((method: string, params?: Record<string, unknown>) => {
if (iframeRef.current?.contentWindow) {
const message = {
jsonrpc: '2.0',
method,
params: params || {},
id: Date.now()
};
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
}
}, [projectId]);
const navigateIframe = useCallback((url: string) => {
// Send semantic path directly (e.g., "/about", "/contact")
// The iframe's NavigationHandler will handle this as semantic navigation
sendNavigationCommand('navigate', { url });
}, [sendNavigationCommand]);
const refreshIframe = useCallback(() => {
sendNavigationCommand('refresh');
}, [sendNavigationCommand]);
const goBackIframe = useCallback(() => {
if (historyIndex > 0) {
// Move back in history
const newIndex = historyIndex - 1;
const targetPath = navigationHistory[newIndex];
setHistoryIndex(newIndex);
setCurrentPath(targetPath);
// Tell iframe to navigate to this path
sendNavigationCommand('navigate', { url: targetPath });
}
}, [historyIndex, navigationHistory, sendNavigationCommand]);
const goForwardIframe = useCallback(() => {
if (historyIndex < navigationHistory.length - 1) {
// Move forward in history
const newIndex = historyIndex + 1;
const targetPath = navigationHistory[newIndex];
setHistoryIndex(newIndex);
setCurrentPath(targetPath);
// Tell iframe to navigate to this path
sendNavigationCommand('navigate', { url: targetPath });
}
}, [historyIndex, navigationHistory, sendNavigationCommand]);
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
const { params, id } = request;
const { request: fetchRequest } = params;
console.log(`Preview iframe requesting: ${fetchRequest.url}`);
try {
// Parse the URL and validate origin
const url = new URL(fetchRequest.url);
const expectedOrigin = `https://${projectId}.local-shakespeare.dev`;
const expectedOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
if (url.origin !== expectedOrigin) {
console.log(`Invalid origin: ${url.origin}, expected: ${expectedOrigin}`);
@@ -162,10 +331,14 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
const path = url.pathname;
const filePath = path;
// Skip SPA fallback for static assets (files with extensions)
const isStaticAsset = /\.[a-zA-Z0-9]+$/.test(path);
// SPA routing: try to serve the exact file first
try {
const file = await projectsManager.readFile(projectId, 'dist' + filePath);
const bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath);
console.log(`Serving file: ${filePath}`);
sendResponse({
jsonrpc: '2.0',
result: {
@@ -175,20 +348,37 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
'Content-Type': getContentType(filePath),
'Cache-Control': 'no-cache',
},
body: file,
body: encodeBase64(bytes),
},
id
});
return;
} catch {
// File not found, try SPA fallback to index.html
console.log(`File not found: ${filePath}, trying index.html fallback`);
// For static assets, return 404 immediately
if (isStaticAsset) {
sendResponse({
jsonrpc: '2.0',
result: {
status: 404,
statusText: 'Not Found',
headers: {
'Content-Type': 'text/plain',
},
body: encodeBase64(`Static asset not found: ${path}`),
},
id
});
return;
}
}
// SPA fallback: serve index.html for non-file requests
// SPA fallback: serve index.html for non-file requests (SPA routing)
try {
const indexFile = await projectsManager.readFile(projectId, 'dist/index.html');
const bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html');
console.log(`Serving index.html fallback for: ${path}`);
sendResponse({
jsonrpc: '2.0',
result: {
@@ -198,13 +388,12 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
'Content-Type': 'text/html',
'Cache-Control': 'no-cache',
},
body: indexFile,
body: encodeBase64(bytes),
},
id
});
} catch {
// Even index.html doesn't exist
console.log(`No files found, returning 404 for: ${path}`);
sendResponse({
jsonrpc: '2.0',
result: {
@@ -213,7 +402,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
headers: {
'Content-Type': 'text/plain',
},
body: `File not found: ${path}`,
body: encodeBase64(`File not found: ${path}`),
},
id
});
@@ -236,7 +425,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
// Verify origin for security
const expectedOrigin = `https://${projectId}.local-shakespeare.dev`;
const expectedOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
if (event.origin !== expectedOrigin) {
console.log(`Ignoring message from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`);
return;
@@ -246,12 +435,16 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
console.log('Received message from iframe:', message);
if (message.jsonrpc === '2.0' && message.method === 'fetch') {
handleFetch(message);
} else if (message.jsonrpc === '2.0' && message.method === 'console') {
handleConsoleMessage(message);
} else if (message.jsonrpc === '2.0' && message.method === 'updateNavigationState') {
handleUpdateNavigationState(message);
}
};
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, [handleFetch, projectId]);
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId]);
useEffect(() => {
if (selectedFile) {
@@ -259,6 +452,19 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
}
}, [selectedFile, loadFileContent]);
// Reset selected file and navigation history when projectId changes
useEffect(() => {
setSelectedFile(null);
setFileContent('');
setMobileCodeView('explorer');
setDesktopCodeView('files');
// Reset navigation history and state
setCurrentPath('/');
setNavigationHistory(['/']);
setHistoryIndex(0);
}, [projectId]);
useEffect(() => {
checkForBuiltProject();
}, [checkForBuiltProject]);
@@ -270,13 +476,13 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
console.log('Build completed for project, refreshing preview');
// Check for built project and refresh iframe
checkForBuiltProject();
refreshIframe();
refreshIframeLegacy();
}
};
window.addEventListener('buildComplete', handleBuildComplete as EventListener);
return () => window.removeEventListener('buildComplete', handleBuildComplete as EventListener);
}, [projectId, checkForBuiltProject, refreshIframe]);
}, [projectId, checkForBuiltProject, refreshIframeLegacy]);
const handleFileSelect = (filePath: string) => {
setSelectedFile(filePath);
@@ -291,77 +497,288 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
try {
await fs.writeFile(`/projects/${projectId}/${selectedFile}`, content);
setFileContent(content);
// Automatically trigger a rebuild after saving a file
if (isPreviewable) {
console.log('File saved, triggering rebuild...');
handleBuildProject();
}
} catch (error) {
console.error('Failed to save file:', error);
}
};
const ConsoleDropdown = () => {
const [isOpen, setIsOpen] = useState(false);
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
try {
await navigator.clipboard.writeText(msg.message);
setCopiedMessageIndex(index);
setTimeout(() => setCopiedMessageIndex(null), 2000);
} catch (error) {
console.error('Failed to copy message to clipboard:', error);
}
};
const consoleMessages = getConsoleMessages();
const messageCount = consoleMessages.length;
const hasErrors = consoleMessages.some(msg => msg.level === 'error');
return (
<Popover open={isOpen} onOpenChange={setIsOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 relative"
>
<Bug className="h-4 w-4" />
{hasErrors && (
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
)}
</Button>
</PopoverTrigger>
<PopoverContent
align="end"
className="w-[calc(100vw-1rem)] max-w-[480px] max-h-[512px] overflow-hidden shadow-lg border rounded-lg bg-background p-0"
sideOffset={4}
>
{/* Messages */}
<div className="h-[60vh] max-h-[512px] w-full bg-background text-foreground font-mono text-xs relative overflow-y-auto overflow-x-hidden [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]">
<div className="py-2 px-1 space-y-0">
{messageCount === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-center">
<p className="text-sm text-muted-foreground font-medium">No console messages</p>
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
</div>
) : (
consoleMessages.map((msg, index) => (
<div
key={index}
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer"
onClick={(e) => {
e.stopPropagation();
copyMessageToClipboard(msg, index);
}}
>
<div className={cn(
"text-xs font-mono leading-tight whitespace-pre-wrap break-words",
msg.level === 'error' ? "text-destructive" :
msg.level === 'warn' ? "text-warning" :
msg.level === 'info' ? "text-primary" :
"text-muted-foreground"
)}>
{msg.message}
</div>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
copyMessageToClipboard(msg, index);
}}
className="h-3 w-3 p-0 opacity-0 group-hover:opacity-100 transition-all duration-200 absolute right-1 top-1 hover:bg-muted/70 text-muted-foreground hover:text-foreground bg-background/80 rounded border"
>
{copiedMessageIndex === index ? (
<Check className="h-2 w-2 text-success" />
) : (
<Copy className="h-2 w-2" />
)}
</Button>
</div>
))
)}
</div>
</div>
{/* Close button */}
<button
onClick={() => setIsOpen(false)}
className="absolute top-2 right-2 h-8 w-8 p-0 bg-muted/50 hover:bg-muted/70 rounded-md z-10 flex items-center justify-center border"
>
<X className="h-5 w-5 text-muted-foreground" />
</button>
</PopoverContent>
</Popover>
);
};
const Menu = () => {
const isAnyLoading = isBuildLoading;
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
>
<MenuIcon className="h-4 w-4" />
<span className="sr-only">Open menu</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48 sm:w-48">
<DropdownMenuItem
onClick={handleBuildProject}
disabled={isBuildLoading}
className="gap-2"
>
{isBuildLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Play className="h-4 w-4" />
)}
{isBuildLoading ? 'Building...' : 'Build'}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setDeployDialogOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<CloudUpload className="h-4 w-4" />
Deploy
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
};
return (
<div className="h-full">
<Tabs value={activeTab} className="h-full">
<TabsContent value="preview" className="h-full mt-0">
{hasBuiltProject ? (
<div className="h-full w-full flex flex-col">
<div className="flex items-center justify-between p-2 border-b bg-gradient-to-r from-primary/5 to-accent/5">
<span className="text-sm font-medium bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">Project Preview</span>
<Button
variant="ghost"
size="sm"
onClick={refreshIframe}
className="h-8 w-8 p-0 hover:bg-primary/10"
>
<RefreshCw className="h-4 w-4" />
</Button>
</div>
<iframe
ref={iframeRef}
src={`https://${projectId}.local-shakespeare.dev/`}
className="w-full flex-1 border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin"
{isPreviewable && (
<TabsContent value="preview" className="h-full mt-0">
<div className="h-full w-full flex flex-col relative">
{/* Always show browser address bar */}
<div className="h-12 flex items-center w-full">
<BrowserAddressBar
currentPath={currentPath}
onNavigate={hasBuiltProject ? navigateIframe : undefined}
onRefresh={hasBuiltProject ? refreshIframe : undefined}
onBack={hasBuiltProject ? goBackIframe : undefined}
onForward={hasBuiltProject ? goForwardIframe : undefined}
canGoBack={hasBuiltProject && historyIndex > 0}
canGoForward={hasBuiltProject && historyIndex < navigationHistory.length - 1}
extraContent={(
<div className="flex items-center">
{(!isMobile && onToggleView && isPreviewable) && (
<Button
variant="ghost"
size="sm"
onClick={onToggleView}
className="h-8 gap-2"
>
<Code className="h-4 w-4" />
</Button>
)}
<ConsoleDropdown />
<Menu />
</div>
)}
/>
</div>
) : (
<div className="h-full flex items-center justify-center bg-muted">
<div className="text-center">
<h3 className="text-lg font-semibold mb-2">Project Preview</h3>
<p className="text-muted-foreground mb-4">
Build your project to see the preview here
</p>
<div className="bg-background border rounded-lg p-8 max-w-md">
<p className="text-sm text-muted-foreground mb-4">
Run the build command to generate <code className="bg-muted px-1 rounded">dist/index.html</code>
</p>
<Button
variant="outline"
size="sm"
onClick={checkForBuiltProject}
className="gap-2"
>
<RefreshCw className="h-4 w-4" />
Check for Build
</Button>
{/* Content area */}
<div className="flex-1">
{hasBuiltProject ? (
<iframe
ref={iframeRef}
src={`https://${projectId}.${IFRAME_DOMAIN}/`}
className="w-full h-full border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin"
/>
) : (
<div className="h-full flex items-center justify-center bg-muted">
<div className="text-center">
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
<p className="text-muted-foreground mb-4">
{t('buildProjectToSeePreview')}
</p>
<Button
onClick={handleBuildProject}
disabled={isBuildLoading}
variant="outline"
className="gap-2"
>
{isBuildLoading ? (
<>
<Loader2 className="h-5 w-5 animate-spin" />
Building...
</>
) : (
<>
<Play className="h-5 w-5" />
Build Project
</>
)}
</Button>
</div>
</div>
)}
</div>
{/* Build loading overlay */}
{isBuildLoading && (
<div className="absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10">
<div className="bg-background/90 border rounded-lg p-4 shadow-lg flex items-center gap-3">
<Loader2 className="h-5 w-5 animate-spin text-primary" />
<span className="text-sm font-medium">Building project...</span>
</div>
</div>
</div>
)}
)}
</div>
</TabsContent>
)}
<TabsContent value="code" className="h-full mt-0">
{isMobile ? (
<div className="h-full flex flex-col">
<div className="h-full flex flex-col min-h-0">
{mobileCodeView === 'explorer' ? (
<>
<div className="p-3 border-b bg-gradient-to-r from-primary/5 to-accent/5">
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">File Explorer</h3>
</div>
<ScrollArea className="flex-1">
<FileTree
projectId={projectId}
onFileSelect={handleFileSelect}
selectedFile={selectedFile}
/>
<div className="flex-1 relative min-h-0">
<ScrollArea className="h-full">
<ScrollBar orientation="horizontal" />
<div className="min-w-max">
<FileTree
projectId={projectId}
onFileSelect={handleFileSelect}
selectedFile={selectedFile}
/>
</div>
</ScrollArea>
{/* Floating Terminal Button */}
<Button
variant="outline"
size="sm"
onClick={() => setMobileCodeView('terminal')}
className="fixed right-4 bottom-safe-nav z-20 h-12 w-12 p-0 rounded-full shadow-lg bg-background border-2"
>
<Terminal className="h-6 w-6" />
</Button>
</div>
) : mobileCodeView === 'terminal' ? (
<>
<div className="h-12 px-3 flex items-center gap-2 bg-black text-purple-400 flex-shrink-0">
<Button
variant="ghost"
size="sm"
onClick={() => setMobileCodeView('explorer')}
className="p-1 hover:bg-transparent hover:text-white"
>
<ArrowLeft className="h-4 w-4" />
</Button>
<h3 className="font-semibold">
Terminal
</h3>
</div>
<div className="flex-1 min-h-0">
<TerminalComponent projectId={projectId} />
</div>
</>
) : (
<>
@@ -375,8 +792,9 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
<ArrowLeft className="h-4 w-4" />
</Button>
<h3 className="font-semibold flex-1 truncate bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
{selectedFile ? selectedFile.split('/').pop() : 'File Editor'}
{selectedFile ? selectedFile.split('/').pop() : t('fileEditor')}
</h3>
<GitStatusIndicator projectId={projectId} />
</div>
<div className="flex-1">
{selectedFile ? (
@@ -385,13 +803,14 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
content={fileContent}
onSave={handleFileSave}
isLoading={isLoading}
projectId={projectId}
/>
) : (
<div className="h-full flex items-center justify-center">
<div className="text-center">
<FolderOpen className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
<p className="text-muted-foreground">
Select a file from the explorer to edit
{t('selectFileFromExplorer')}
</p>
<Button
variant="outline"
@@ -399,7 +818,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
onClick={() => setMobileCodeView('explorer')}
className="mt-4"
>
Open File Explorer
{t('openFileExplorer')}
</Button>
</div>
</div>
@@ -409,42 +828,103 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
)}
</div>
) : (
<div className="h-full flex">
<div className="w-1/3 border-r">
<div className="p-4 border-b bg-gradient-to-r from-primary/5 to-accent/5">
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">File Explorer</h3>
<div className="h-full flex flex-col">
{/* Code view header with back button */}
{!isMobile && onToggleView && isPreviewable && (
<div className="h-12 px-4 border-b flex items-center bg-gradient-to-r from-muted/20 to-background">
<Button
variant="ghost"
size="sm"
onClick={onToggleView}
className="gap-2 text-muted-foreground hover:text-foreground"
>
<ArrowLeft className="h-4 w-4" />
{t('backToPreview')}
</Button>
<div className="flex-1" />
<Button
variant="ghost"
size="sm"
onClick={() => setDesktopCodeView(desktopCodeView === 'terminal' ? 'files' : 'terminal')}
className="gap-2 text-muted-foreground hover:text-foreground"
>
<Terminal className="h-4 w-4" />
</Button>
</div>
<ScrollArea className="h-[calc(100%-60px)]">
<FileTree
projectId={projectId}
onFileSelect={handleFileSelect}
selectedFile={selectedFile}
/>
</ScrollArea>
</div>
)}
{/* Code view header without back button for non-previewable projects */}
{!isMobile && !isPreviewable && (
<div className="h-12 px-4 border-b flex items-center bg-gradient-to-r from-muted/20 to-background">
<div className="flex-1" />
<Button
variant="ghost"
size="sm"
onClick={() => setDesktopCodeView(desktopCodeView === 'terminal' ? 'files' : 'terminal')}
className="gap-2 text-muted-foreground hover:text-foreground"
>
<Terminal className="h-4 w-4" />
</Button>
<GitStatusIndicator projectId={projectId} />
</div>
)}
<div className="flex-1">
{selectedFile ? (
<FileEditor
filePath={selectedFile}
content={fileContent}
onSave={handleFileSave}
isLoading={isLoading}
/>
) : (
<div className="h-full flex items-center justify-center">
<div className="text-center">
<p className="text-muted-foreground">
Select a file from the explorer to edit
</p>
</div>
<div className="flex-1 flex min-h-0">
{desktopCodeView === 'terminal' ? (
<div className="flex-1">
<TerminalComponent projectId={projectId} />
</div>
) : (
<>
<div className="w-1/3 border-r flex flex-col">
<ScrollArea className="flex-1">
<ScrollBar orientation="horizontal" />
<div className="min-w-max">
<FileTree
projectId={projectId}
onFileSelect={handleFileSelect}
selectedFile={selectedFile}
/>
</div>
</ScrollArea>
</div>
<div className="flex-1">
{selectedFile ? (
<FileEditor
filePath={selectedFile}
content={fileContent}
onSave={handleFileSave}
isLoading={isLoading}
projectId={projectId}
/>
) : (
<div className="h-full flex items-center justify-center">
<div className="text-center">
<p className="text-muted-foreground">
{t('selectFileFromExplorer')}
</p>
</div>
</div>
)}
</div>
</>
)}
</div>
</div>
)}
</TabsContent>
</Tabs>
{/* Deploy Dialog */}
{projectName && (
<DeployDialog
projectId={projectId}
projectName={projectName}
open={deployDialogOpen}
onOpenChange={setDeployDialogOpen}
onFirstInteraction={onFirstInteraction}
/>
)}
</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}
/>
);
}
+70
View File
@@ -0,0 +1,70 @@
import { Button } from '@/components/ui/button';
import { Star } from 'lucide-react';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useToast } from '@/hooks/useToast';
import { useQueryClient } from '@tanstack/react-query';
import { cn } from '@/lib/utils';
interface StarButtonProps {
projectId: string;
projectName: string;
className?: string;
size?: 'sm' | 'default' | 'lg';
variant?: 'ghost' | 'outline' | 'default';
showToast?: boolean;
}
export function StarButton({
projectId,
projectName,
className,
size = 'sm',
variant = 'ghost',
showToast = true
}: StarButtonProps) {
const [favorites, setFavorites] = useLocalStorage<string[]>('project-favorites', []);
const { toast } = useToast();
const queryClient = useQueryClient();
const isFavorite = favorites.includes(projectId);
const handleToggleFavorite = (e: React.MouseEvent) => {
e.stopPropagation(); // Prevent triggering parent click events
const newFavorites = isFavorite
? favorites.filter(id => id !== projectId)
: [...favorites, projectId];
setFavorites(newFavorites);
// Invalidate the projects query to trigger a refetch with new sorting
queryClient.invalidateQueries({ queryKey: ['projects'] });
if (showToast) {
toast({
title: isFavorite ? "Project Unfavorited" : "Project Favorited",
description: `"${projectName}" has been ${isFavorite ? 'removed from' : 'added to'} your favorites.`,
});
}
};
return (
<Button
variant={variant}
size={size}
onClick={handleToggleFavorite}
className={cn(
"h-8 w-8 p-0",
className
)}
aria-label={isFavorite ? "Remove from favorites" : "Add to favorites"}
>
<Star
className={cn(
"h-4 w-4",
isFavorite ? "text-yellow-500 fill-current" : "text-muted-foreground hover:text-yellow-500"
)}
/>
</Button>
);
}
+235
View File
@@ -0,0 +1,235 @@
import { useState, useRef, useEffect, useCallback } from 'react';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { Copy } from 'lucide-react';
import { cn } from '@/lib/utils';
import { ShellTool } from '@/lib/tools/ShellTool';
import { useFS } from '@/hooks/useFS';
import { useGit } from '@/hooks/useGit';
interface TerminalProps {
projectId: string;
className?: string;
}
interface TerminalLine {
id: string;
type: 'input' | 'output' | 'error';
content: string;
timestamp: Date;
}
export function Terminal({ projectId, className }: TerminalProps) {
const [lines, setLines] = useState<TerminalLine[]>([]);
const [currentInput, setCurrentInput] = useState('');
const [isExecuting, setIsExecuting] = useState(false);
const [commandHistory, setCommandHistory] = useState<string[]>([]);
const [historyIndex, setHistoryIndex] = useState(-1);
const inputRef = useRef<HTMLInputElement>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const shellToolRef = useRef<ShellTool | null>(null);
const { fs } = useFS();
const { git } = useGit();
// Initialize ShellTool
useEffect(() => {
shellToolRef.current = new ShellTool(fs, `/projects/${projectId}`, git);
// Add welcome message
setLines([{
id: Date.now().toString(),
type: 'output',
content: `Welcome to Shakespeare Terminal\nType 'help' to see available commands.`,
timestamp: new Date()
}]);
}, [projectId, fs, git]);
// Auto-scroll to bottom when new lines are added or execution state changes
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
}, [lines, isExecuting]);
// Focus input when component mounts
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
// Refocus input after command execution
useEffect(() => {
if (!isExecuting && inputRef.current) {
inputRef.current.focus();
}
}, [isExecuting]);
const addLine = useCallback((type: TerminalLine['type'], content: string) => {
const newLine: TerminalLine = {
id: Date.now().toString() + Math.random(),
type,
content,
timestamp: new Date()
};
setLines(prev => [...prev, newLine]);
}, []);
const executeCommand = useCallback(async (command: string) => {
if (!shellToolRef.current || !command.trim()) return;
// Add command to history
if (command.trim() && !commandHistory.includes(command.trim())) {
setCommandHistory(prev => [...prev, command.trim()]);
}
setHistoryIndex(-1);
// Add input line
addLine('input', command);
setIsExecuting(true);
try {
// Handle special help command
if (command.trim() === 'help') {
const availableCommands = shellToolRef.current.getAvailableCommands();
const helpText = `Available commands:\n\n${availableCommands.map(cmd =>
`${cmd.name.padEnd(12)} - ${cmd.description}`
).join('\n')}\n\nUse 'which <command>' for more details about a specific command.`;
addLine('output', helpText);
} else if (command.trim() === 'clear') {
setLines([]);
} else {
const result = await shellToolRef.current.execute({ command });
// Add output
if (result && result.trim()) {
addLine('output', result);
}
}
} catch (error) {
addLine('error', `Error: ${error instanceof Error ? error.message : 'Unknown error'}`);
} finally {
setIsExecuting(false);
}
}, [addLine, commandHistory]);
const handleSubmit = useCallback((e: React.FormEvent) => {
e.preventDefault();
if (currentInput.trim() && !isExecuting) {
executeCommand(currentInput);
setCurrentInput('');
}
}, [currentInput, isExecuting, executeCommand]);
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
if (e.key === 'ArrowUp') {
e.preventDefault();
if (commandHistory.length > 0) {
const newIndex = historyIndex === -1 ? commandHistory.length - 1 : Math.max(0, historyIndex - 1);
setHistoryIndex(newIndex);
setCurrentInput(commandHistory[newIndex]);
}
} else if (e.key === 'ArrowDown') {
e.preventDefault();
if (historyIndex >= 0) {
const newIndex = historyIndex + 1;
if (newIndex >= commandHistory.length) {
setHistoryIndex(-1);
setCurrentInput('');
} else {
setHistoryIndex(newIndex);
setCurrentInput(commandHistory[newIndex]);
}
}
} else if (e.key === 'Tab') {
e.preventDefault();
// Basic tab completion could be added here
}
}, [commandHistory, historyIndex]);
const copyToClipboard = useCallback(async (content: string) => {
try {
await navigator.clipboard.writeText(content);
} catch (error) {
console.error('Failed to copy to clipboard:', error);
}
}, []);
// Focus input when clicking anywhere in the terminal
const handleTerminalClick = useCallback(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
return (
<div className={cn("h-full flex flex-col bg-black text-slate-300 font-mono text-sm", className)}>
{/* Terminal Content */}
<div className="flex-1 flex flex-col min-h-0" onClick={handleTerminalClick}>
<ScrollArea className="flex-1" ref={scrollRef}>
<div className="p-2 space-y-1">
{lines.map((line) => (
<div
key={line.id}
className={cn(
"group relative",
line.type === 'input' && "text-white",
line.type === 'error' && "text-red-400",
line.type === 'output' && "text-slate-300"
)}
>
<pre className="whitespace-pre-wrap break-words font-mono leading-relaxed">
{line.type === 'input' ? (
<span className="text-purple-400 font-mono whitespace-nowrap">
${' '}
</span>
) : null}
{line.content}
</pre>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
copyToClipboard(line.content);
}}
className="absolute right-0 top-0 h-4 w-4 p-0 opacity-0 group-hover:opacity-100 transition-opacity text-gray-500 hover:text-white hover:bg-gray-700"
>
<Copy className="h-2 w-2" />
</Button>
</div>
))}
{/* Current Command Input - inline with content */}
{!isExecuting && (
<div className="flex items-center gap-2">
<span className="text-purple-400 font-mono whitespace-nowrap">
$
</span>
<form onSubmit={handleSubmit} className="flex-1 relative">
<input
ref={inputRef}
type="text"
value={currentInput}
onChange={(e) => setCurrentInput(e.target.value)}
onKeyDown={handleKeyDown}
disabled={isExecuting}
className="w-full bg-transparent border-none outline-none text-white font-mono placeholder-gray-500 caret-white leading-relaxed"
placeholder=""
autoComplete="off"
spellCheck="false"
autoCapitalize="off"
autoCorrect="off"
/>
</form>
</div>
)}
</div>
</ScrollArea>
</div>
</div>
);
}
+57
View File
@@ -0,0 +1,57 @@
import { ChevronsUpDown, Monitor, Moon, Sun } from "lucide-react";
import { useTranslation } from 'react-i18next';
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useTheme } from "@/hooks/useTheme";
import { type Theme } from "@/contexts/AppContext";
export function ThemePicker() {
const { t } = useTranslation();
const { theme, setTheme } = useTheme();
const themeOptions: { value: Theme; label: string; icon: React.ComponentType<{ className?: string }> }[] = [
{ value: "system", label: t('system'), icon: Monitor },
{ value: "light", label: t('light'), icon: Sun },
{ value: "dark", label: t('dark'), icon: Moon },
];
const currentTheme = themeOptions.find(option => option.value === theme);
const CurrentIcon = currentTheme?.icon || Monitor;
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="w-full justify-between">
<div className="flex items-center gap-2">
<CurrentIcon className="h-4 w-4" />
<span>{currentTheme?.label || t('system')}</span>
</div>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-[180px]">
{themeOptions.map((option) => {
const Icon = option.icon;
return (
<DropdownMenuItem
key={option.value}
onClick={() => setTheme(option.value)}
className="flex items-center gap-2"
>
<Icon className="h-4 w-4" />
<span>{option.label}</span>
{theme === option.value && (
<div className="ml-auto h-2 w-2 rounded-full bg-primary" />
)}
</DropdownMenuItem>
);
})}
</DropdownMenuContent>
</DropdownMenu>
);
}
@@ -0,0 +1,61 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { UserMessage } from './UserMessage';
describe('UserMessage Integration', () => {
it('renders text parts with file attachments correctly', () => {
// Simulate the new text parts structure that ChatPane would create
const content = [
{ type: 'text' as const, text: 'Please analyze this file:' },
{ type: 'text' as const, text: 'Added file: /tmp/data.csv' },
{ type: 'text' as const, text: 'Let me know what you find!' }
];
render(<UserMessage content={content} />);
// Check that regular text is displayed
expect(screen.getByText('Please analyze this file:')).toBeInTheDocument();
expect(screen.getByText('Let me know what you find!')).toBeInTheDocument();
// Check that file attachment is rendered as a badge
expect(screen.getByText('data.csv')).toBeInTheDocument();
// Full path should not be displayed
expect(screen.queryByText('/tmp/data.csv')).not.toBeInTheDocument();
});
it('handles single text part with file attachment', () => {
const content = [
{ type: 'text' as const, text: 'Added file: /tmp/script.js' }
];
render(<UserMessage content={content} />);
expect(screen.getByText('script.js')).toBeInTheDocument();
// Full path should not be displayed
expect(screen.queryByText('/tmp/script.js')).not.toBeInTheDocument();
});
it('handles multiple file attachments in separate parts', () => {
const content = [
{ type: 'text' as const, text: 'Here are my files:' },
{ type: 'text' as const, text: 'Added file: /tmp/config.json' },
{ type: 'text' as const, text: 'Added file: /tmp/styles.css' },
{ type: 'text' as const, text: 'Added file: /tmp/main.js' }
];
render(<UserMessage content={content} />);
expect(screen.getByText('Here are my files:')).toBeInTheDocument();
expect(screen.getByText('config.json')).toBeInTheDocument();
expect(screen.getByText('styles.css')).toBeInTheDocument();
expect(screen.getByText('main.js')).toBeInTheDocument();
});
it('handles empty content gracefully', () => {
const content: Array<{ type: 'text'; text: string }> = [];
const { container } = render(<UserMessage content={content} />);
expect(container.firstChild).toBeNull();
});
});
+110
View File
@@ -0,0 +1,110 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { UserMessage } from './UserMessage';
describe('UserMessage', () => {
it('renders regular text without file attachments', () => {
const content = 'This is a regular message without any file attachments.';
render(<UserMessage content={content} />);
expect(screen.getByText(content)).toBeInTheDocument();
});
it('handles backward compatibility with string content containing file attachments', () => {
const content = 'Here is my file: Added file: /tmp/test.txt';
render(<UserMessage content={content} />);
// When using string content, it should still work but won't separate file attachments
expect(screen.getByText(content)).toBeInTheDocument();
});
it('renders file attachment badges for single file with text parts', () => {
const content = [
{ type: 'text' as const, text: 'Here is my file:' },
{ type: 'text' as const, text: 'Added file: /tmp/test.txt' }
];
render(<UserMessage content={content} />);
expect(screen.getByText('Here is my file:')).toBeInTheDocument();
expect(screen.getByText('test.txt')).toBeInTheDocument();
// Full path should not be displayed
expect(screen.queryByText('/tmp/test.txt')).not.toBeInTheDocument();
});
it('renders multiple file attachments with text parts', () => {
const content = [
{ type: 'text' as const, text: 'Files uploaded:' },
{ type: 'text' as const, text: 'Added file: /tmp/document.pdf' },
{ type: 'text' as const, text: 'Added file: /tmp/image.jpg' },
{ type: 'text' as const, text: 'All done!' }
];
render(<UserMessage content={content} />);
expect(screen.getByText('Files uploaded:')).toBeInTheDocument();
expect(screen.getByText('document.pdf')).toBeInTheDocument();
expect(screen.getByText('image.jpg')).toBeInTheDocument();
expect(screen.getByText('All done!')).toBeInTheDocument();
});
it('renders text files with FileText icon', () => {
const content = [{ type: 'text' as const, text: 'Added file: /tmp/script.js' }];
render(<UserMessage content={content} />);
expect(screen.getByText('script.js')).toBeInTheDocument();
// FileText icon should be rendered (we can't easily test the icon itself, but we can test the component renders)
});
it('handles files without extensions', () => {
const content = [{ type: 'text' as const, text: 'Added file: /tmp/README' }];
render(<UserMessage content={content} />);
expect(screen.getByText('README')).toBeInTheDocument();
// Full path should not be displayed
expect(screen.queryByText('/tmp/README')).not.toBeInTheDocument();
});
it('handles complex filenames with underscores and numbers', () => {
const content = [{ type: 'text' as const, text: 'Added file: /tmp/my_file_1.txt' }];
render(<UserMessage content={content} />);
expect(screen.getByText('my_file_1.txt')).toBeInTheDocument();
// Full path should not be displayed
expect(screen.queryByText('/tmp/my_file_1.txt')).not.toBeInTheDocument();
});
it('preserves whitespace in text content', () => {
const content = [
{ type: 'text' as const, text: 'Line 1\n\nLine 3 with spaces \n\nFinal line' },
{ type: 'text' as const, text: 'Added file: /tmp/test.txt' }
];
const { container } = render(<UserMessage content={content} />);
// Check that the component renders and contains the expected text content
expect(container.textContent).toContain('Line 1');
expect(container.textContent).toContain('Line 3 with spaces');
expect(container.textContent).toContain('Final line');
expect(screen.getByText('test.txt')).toBeInTheDocument();
});
it('handles mixed content with file attachments in the middle', () => {
const content = [
{ type: 'text' as const, text: 'Starting text' },
{ type: 'text' as const, text: 'Added file: /tmp/middle.txt' },
{ type: 'text' as const, text: 'ending text' }
];
render(<UserMessage content={content} />);
expect(screen.getByText('Starting text')).toBeInTheDocument();
expect(screen.getByText('middle.txt')).toBeInTheDocument();
expect(screen.getByText('ending text')).toBeInTheDocument();
});
});
+85
View File
@@ -0,0 +1,85 @@
import { FileText, File } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import type OpenAI from 'openai';
interface UserMessageProps {
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>;
}
/**
* Component to render user messages nicely
* Handles both string content and array content (text parts)
* Detects "Added file: /tmp/<filename>" patterns and renders them as badges
*/
export function UserMessage({ content }: UserMessageProps) {
// Convert content to array format for uniform processing
const contentParts = typeof content === 'string'
? [{ type: 'text' as const, text: content }]
: content.filter(part => part.type === 'text') as Array<{ type: 'text'; text: string }>;
// Regular expression to match "Added file: /tmp/<filename>" patterns
const filePattern = /^Added file: (\/tmp\/[^\s\n]+)$/;
// Process each content part and categorize as text or file
const processedParts: Array<{ type: 'text' | 'file'; content: string; filepath?: string }> = [];
contentParts.forEach(part => {
const text = part.text.trim();
const match = text.match(filePattern);
if (match) {
// This is a file attachment
const filepath = match[1]; // "/tmp/filename.txt"
processedParts.push({ type: 'file', content: text, filepath });
} else if (text) {
// This is regular text content
processedParts.push({ type: 'text', content: text });
}
});
// If no content, return empty
if (processedParts.length === 0) {
return null;
}
const getFileIcon = (filename: string) => {
const extension = filename.split('.').pop()?.toLowerCase();
// Return FileText icon for text-like files, File icon for others
const textExtensions = ['txt', 'md', 'json', 'js', 'ts', 'jsx', 'tsx', 'css', 'html', 'xml', 'yml', 'yaml'];
if (extension && textExtensions.includes(extension)) {
return <FileText className="h-3 w-3" />;
}
return <File className="h-3 w-3" />;
};
const getFileName = (filepath: string) => {
return filepath.split('/').pop() || filepath;
};
return (
<div className="space-y-2">
{processedParts.map((part, index) => {
if (part.type === 'text') {
return (
<div key={index} className="whitespace-pre-wrap">
{part.content}
</div>
);
} else {
const filename = getFileName(part.filepath!);
return (
<div key={index} className="flex items-center gap-2">
<Badge variant="secondary" className="flex items-center gap-1.5 px-2 py-1">
{getFileIcon(filename)}
<span className="text-xs font-medium">{filename}</span>
</Badge>
</div>
);
}
})}
</div>
);
}
+395
View File
@@ -0,0 +1,395 @@
import { useState, forwardRef } from 'react';
import { Wallet, Plus, Trash2, Zap, Globe, WalletMinimal, CheckCircle, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
DrawerClose,
} from '@/components/ui/drawer';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { useNWC } from '@/hooks/useNWCContext';
import { useWallet } from '@/hooks/useWallet';
import { useToast } from '@/hooks/useToast';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { NWCConnection, NWCInfo } from '@/hooks/useNWC';
interface WalletModalProps {
children?: React.ReactNode;
className?: string;
}
// Extracted AddWalletContent to prevent re-renders
const AddWalletContent = forwardRef<HTMLDivElement, {
alias: string;
setAlias: (value: string) => void;
connectionUri: string;
setConnectionUri: (value: string) => void;
}>(({ alias, setAlias, connectionUri, setConnectionUri }, ref) => (
<div className="space-y-4 px-4" ref={ref}>
<div>
<Label htmlFor="alias">Wallet Name (optional)</Label>
<Input
id="alias"
placeholder="My Lightning Wallet"
value={alias}
onChange={(e) => setAlias(e.target.value)}
/>
</div>
<div>
<Label htmlFor="connection-uri">Connection URI</Label>
<Textarea
id="connection-uri"
placeholder="nostr+walletconnect://..."
value={connectionUri}
onChange={(e) => setConnectionUri(e.target.value)}
rows={3}
/>
</div>
</div>
));
AddWalletContent.displayName = 'AddWalletContent';
// Extracted WalletContent to prevent re-renders
const WalletContent = forwardRef<HTMLDivElement, {
hasWebLN: boolean;
isDetecting: boolean;
hasNWC: boolean;
connections: NWCConnection[];
connectionInfo: Record<string, NWCInfo>;
activeConnection: string | null;
handleSetActive: (cs: string) => void;
handleRemoveConnection: (cs: string) => void;
setAddDialogOpen: (open: boolean) => void;
}>(({
hasWebLN,
isDetecting,
hasNWC,
connections,
connectionInfo,
activeConnection,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen
}, ref) => (
<div className="space-y-6 px-4 pb-4" ref={ref}>
{/* Current Status */}
<div className="space-y-3">
<h3 className="font-medium">Current Status</h3>
<div className="grid gap-3">
{/* WebLN */}
<div className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<Globe className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">WebLN</p>
<p className="text-xs text-muted-foreground">Browser extension</p>
</div>
</div>
<div className="flex items-center gap-2">
{hasWebLN && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={hasWebLN ? "default" : "secondary"} className="text-xs">
{isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found"}
</Badge>
</div>
</div>
{/* NWC */}
<div className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">Nostr Wallet Connect</p>
<p className="text-xs text-muted-foreground">
{connections.length > 0
? `${connections.length} wallet${connections.length !== 1 ? 's' : ''} connected`
: "Remote wallet connection"
}
</p>
</div>
</div>
<div className="flex items-center gap-2">
{hasNWC && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={hasNWC ? "default" : "secondary"} className="text-xs">
{hasNWC ? "Ready" : "None"}
</Badge>
</div>
</div>
</div>
</div>
<Separator />
{/* NWC Management */}
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="font-medium">Nostr Wallet Connect</h3>
<Button size="sm" variant="outline" onClick={() => setAddDialogOpen(true)}>
<Plus className="h-4 w-4 mr-1" />
Add
</Button>
</div>
{/* Connected Wallets List */}
{connections.length === 0 ? (
<div className="text-center py-6 text-muted-foreground">
<p className="text-sm">No wallets connected</p>
</div>
) : (
<div className="space-y-2">
{connections.map((connection) => {
const info = connectionInfo[connection.connectionString];
const isActive = activeConnection === connection.connectionString;
return (
<div key={connection.connectionString} className={`flex items-center justify-between p-3 border rounded-lg ${isActive ? 'ring-2 ring-primary' : ''}`}>
<div className="flex items-center gap-3">
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">
{connection.alias || info?.alias || 'Lightning Wallet'}
</p>
<p className="text-xs text-muted-foreground">
NWC Connection
</p>
</div>
</div>
<div className="flex items-center gap-2">
{isActive && <CheckCircle className="h-4 w-4 text-green-600" />}
{!isActive && (
<Button
size="sm"
variant="ghost"
onClick={() => handleSetActive(connection.connectionString)}
>
<Zap className="h-3 w-3" />
</Button>
)}
<Button
size="sm"
variant="ghost"
onClick={() => handleRemoveConnection(connection.connectionString)}
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
</div>
);
})}
</div>
)}
</div>
{/* Help */}
{!hasWebLN && connections.length === 0 && (
<>
<Separator />
<div className="text-center py-4 space-y-2">
<p className="text-sm text-muted-foreground">
Install a WebLN extension or connect a NWC wallet for zaps.
</p>
</div>
</>
)}
</div>
));
WalletContent.displayName = 'WalletContent';
export function WalletModal({ children, className }: WalletModalProps) {
const [open, setOpen] = useState(false);
const [addDialogOpen, setAddDialogOpen] = useState(false);
const [connectionUri, setConnectionUri] = useState('');
const [alias, setAlias] = useState('');
const [isConnecting, setIsConnecting] = useState(false);
const isMobile = useIsMobile();
const {
connections,
activeConnection,
connectionInfo,
addConnection,
removeConnection,
setActiveConnection
} = useNWC();
const { hasWebLN, isDetecting } = useWallet();
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
const { toast } = useToast();
const handleAddConnection = async () => {
if (!connectionUri.trim()) {
toast({
title: 'Connection URI required',
description: 'Please enter a valid NWC connection URI.',
variant: 'destructive',
});
return;
}
setIsConnecting(true);
try {
const success = await addConnection(connectionUri.trim(), alias.trim() || undefined);
if (success) {
setConnectionUri('');
setAlias('');
setAddDialogOpen(false);
}
} finally {
setIsConnecting(false);
}
};
const handleRemoveConnection = (connectionString: string) => {
removeConnection(connectionString);
};
const handleSetActive = (connectionString: string) => {
setActiveConnection(connectionString);
toast({
title: 'Active wallet changed',
description: 'The selected wallet is now active for zaps.',
});
};
const walletContentProps = {
hasWebLN,
isDetecting,
hasNWC,
connections,
connectionInfo,
activeConnection,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen,
};
const addWalletDialog = (
<Dialog open={addDialogOpen} onOpenChange={setAddDialogOpen}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>Connect NWC Wallet</DialogTitle>
<DialogDescription>
Enter your connection string from a compatible wallet.
</DialogDescription>
</DialogHeader>
<AddWalletContent
alias={alias}
setAlias={setAlias}
connectionUri={connectionUri}
setConnectionUri={setConnectionUri}
/>
<DialogFooter className="px-4">
<Button
onClick={handleAddConnection}
disabled={isConnecting || !connectionUri.trim()}
className="w-full"
>
{isConnecting ? 'Connecting...' : 'Connect'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
if (isMobile) {
return (
<>
<Drawer open={open} onOpenChange={setOpen}>
<DrawerTrigger asChild>
{children || (
<Button variant="outline" size="sm" className={className}>
<Wallet className="h-4 w-4 mr-2" />
Wallet Settings
</Button>
)}
</DrawerTrigger>
<DrawerContent className="h-full">
<DrawerHeader className="text-center relative">
<DrawerClose asChild>
<Button variant="ghost" size="sm" className="absolute right-4 top-4">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</Button>
</DrawerClose>
<DrawerTitle className="flex items-center justify-center gap-2 pt-2">
<Wallet className="h-5 w-5" />
Lightning Wallet
</DrawerTitle>
<DrawerDescription>
Connect your lightning wallet to send zaps instantly.
</DrawerDescription>
</DrawerHeader>
<div className="overflow-y-auto">
<WalletContent {...walletContentProps} />
</div>
</DrawerContent>
</Drawer>
{/* Render Add Wallet as a separate Drawer for mobile */}
<Drawer open={addDialogOpen} onOpenChange={setAddDialogOpen}>
<DrawerContent>
<DrawerHeader>
<DrawerTitle>Connect NWC Wallet</DrawerTitle>
<DrawerDescription>
Enter your connection string from a compatible wallet.
</DrawerDescription>
</DrawerHeader>
<AddWalletContent
alias={alias}
setAlias={setAlias}
connectionUri={connectionUri}
setConnectionUri={setConnectionUri}
/>
<div className="p-4">
<Button
onClick={handleAddConnection}
disabled={isConnecting || !connectionUri.trim()}
className="w-full"
>
{isConnecting ? 'Connecting...' : 'Connect'}
</Button>
</div>
</DrawerContent>
</Drawer>
</>
);
}
return (
<>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
{children || (
<Button variant="outline" size="sm" className={className}>
<Wallet className="h-4 w-4 mr-2" />
Wallet Settings
</Button>
)}
</DialogTrigger>
<DialogContent className="sm:max-w-[500px] max-h-[80vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Wallet className="h-5 w-5" />
Lightning Wallet
</DialogTitle>
<DialogDescription>
Connect your lightning wallet to send zaps instantly.
</DialogDescription>
</DialogHeader>
<WalletContent {...walletContentProps} />
</DialogContent>
</Dialog>
{addWalletDialog}
</>
);
}
+58
View File
@@ -0,0 +1,58 @@
import { ZapDialog } from '@/components/ZapDialog';
import { useZaps } from '@/hooks/useZaps';
import { useWallet } from '@/hooks/useWallet';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAuthor } from '@/hooks/useAuthor';
import { Zap } from 'lucide-react';
import type { Event } from 'nostr-tools';
interface ZapButtonProps {
target: Event;
className?: string;
showCount?: boolean;
zapData?: { count: number; totalSats: number; isLoading?: boolean };
}
export function ZapButton({
target,
className = "text-xs ml-1",
showCount = true,
zapData: externalZapData
}: ZapButtonProps) {
const { user } = useCurrentUser();
const { data: author } = useAuthor(target?.pubkey || '');
const { webln, activeNWC } = useWallet();
// Only fetch data if not provided externally
const { totalSats: fetchedTotalSats, isLoading } = useZaps(
externalZapData ? [] : target ?? [], // Empty array prevents fetching if external data provided
webln,
activeNWC
);
// Don't show zap button if user is not logged in, is the author, or author has no lightning address
if (!user || !target || user.pubkey === target.pubkey || (!author?.metadata?.lud16 && !author?.metadata?.lud06)) {
return null;
}
// Use external data if provided, otherwise use fetched data
const totalSats = externalZapData?.totalSats ?? fetchedTotalSats;
const showLoading = externalZapData?.isLoading || isLoading;
return (
<ZapDialog target={target}>
<div className={`flex items-center gap-1 ${className}`}>
<Zap className="h-4 w-4" />
<span className="text-xs">
{showLoading ? (
'...'
) : showCount && totalSats > 0 ? (
`${totalSats.toLocaleString()}`
) : (
'Zap'
)}
</span>
</div>
</ZapDialog>
);
}
+470
View File
@@ -0,0 +1,470 @@
import { useState, useEffect, useRef, forwardRef } from 'react';
import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
DrawerClose,
} from '@/components/ui/drawer';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAuthor } from '@/hooks/useAuthor';
import { useToast } from '@/hooks/useToast';
import { useZaps } from '@/hooks/useZaps';
import { useWallet } from '@/hooks/useWallet';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { Event } from 'nostr-tools';
import QRCode from 'qrcode';
interface ZapDialogProps {
target: Event;
children?: React.ReactNode;
className?: string;
}
const presetAmounts = [
{ amount: 1, icon: Sparkle },
{ amount: 50, icon: Sparkles },
{ amount: 100, icon: Zap },
{ amount: 250, icon: Star },
{ amount: 1000, icon: Rocket },
];
interface ZapContentProps {
invoice: string | null;
amount: number | string;
comment: string;
isZapping: boolean;
qrCodeUrl: string;
copied: boolean;
hasWebLN: boolean;
handleZap: () => void;
handleCopy: () => void;
openInWallet: () => void;
setAmount: (amount: number | string) => void;
setComment: (comment: string) => void;
inputRef: React.RefObject<HTMLInputElement>;
zap: (amount: number, comment: string) => void;
}
// Moved ZapContent outside of ZapDialog to prevent re-renders causing focus loss
const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
invoice,
amount,
comment,
isZapping,
qrCodeUrl,
copied,
hasWebLN,
handleZap,
handleCopy,
openInWallet,
setAmount,
setComment,
inputRef,
zap,
}, ref) => (
<div ref={ref}>
{invoice ? (
<div className="flex flex-col h-full min-h-0">
{/* Payment amount display */}
<div className="text-center pt-4">
<div className="text-2xl font-bold">{amount} sats</div>
</div>
<Separator className="my-4" />
<div className="flex flex-col justify-center min-h-0 flex-1 px-2">
{/* QR Code */}
<div className="flex justify-center">
<Card className="p-3 [@media(max-height:680px)]:max-w-[65vw] max-w-[95vw] mx-auto">
<CardContent className="p-0 flex justify-center">
{qrCodeUrl ? (
<img
src={qrCodeUrl}
alt="Lightning Invoice QR Code"
className="w-full h-auto aspect-square max-w-full object-contain"
/>
) : (
<div className="w-full aspect-square bg-muted animate-pulse rounded" />
)}
</CardContent>
</Card>
</div>
{/* Invoice input */}
<div className="space-y-2 mt-4">
<Label htmlFor="invoice">Lightning Invoice</Label>
<div className="flex gap-2 min-w-0">
<Input
id="invoice"
value={invoice}
readOnly
className="font-mono text-xs min-w-0 flex-1 overflow-hidden text-ellipsis"
onClick={(e) => e.currentTarget.select()}
/>
<Button
variant="outline"
size="icon"
onClick={handleCopy}
className="shrink-0"
>
{copied ? (
<Check className="h-4 w-4 text-green-600" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
</div>
{/* Payment buttons */}
<div className="space-y-3 mt-4">
{hasWebLN && (
<Button
onClick={() => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
zap(finalAmount, comment);
}}
disabled={isZapping}
className="w-full"
size="lg"
>
<Zap className="h-4 w-4 mr-2" />
{isZapping ? "Processing..." : "Pay with WebLN"}
</Button>
)}
<Button
variant="outline"
onClick={openInWallet}
className="w-full"
size="lg"
>
<ExternalLink className="h-4 w-4 mr-2" />
Open in Lightning Wallet
</Button>
<div className="text-xs sm:text-[.65rem] text-muted-foreground text-center">
Scan the QR code or copy the invoice to pay with any Lightning wallet.
</div>
</div>
</div>
</div>
) : (
<>
<div className="grid gap-3 px-4 py-4 w-full overflow-hidden">
<ToggleGroup
type="single"
value={String(amount)}
onValueChange={(value) => {
if (value) {
setAmount(parseInt(value, 10));
}
}}
className="grid grid-cols-5 gap-1 w-full"
>
{presetAmounts.map(({ amount: presetAmount, icon: Icon }) => (
<ToggleGroupItem
key={presetAmount}
value={String(presetAmount)}
className="flex flex-col h-auto min-w-0 text-xs px-1 py-2"
>
<Icon className="h-4 w-4 mb-1" />
<span className="truncate">{presetAmount}</span>
</ToggleGroupItem>
))}
</ToggleGroup>
<div className="flex items-center gap-2">
<div className="h-px flex-1 bg-muted" />
<span className="text-xs text-muted-foreground">OR</span>
<div className="h-px flex-1 bg-muted" />
</div>
<Input
ref={inputRef}
id="custom-amount"
type="number"
placeholder="Custom amount"
value={amount}
onChange={(e) => setAmount(e.target.value)}
className="w-full text-sm"
/>
<Textarea
id="custom-comment"
placeholder="Add a comment (optional)"
value={comment}
onChange={(e) => setComment(e.target.value)}
className="w-full resize-none text-sm"
rows={2}
/>
</div>
<div className="px-4 pb-4">
<Button onClick={handleZap} className="w-full" disabled={isZapping} size="default">
{isZapping ? (
'Creating invoice...'
) : (
<>
<Zap className="h-4 w-4 mr-2" />
Zap {amount} sats
</>
)}
</Button>
</div>
</>
)}
</div>
));
ZapContent.displayName = 'ZapContent';
export function ZapDialog({ target, children, className }: ZapDialogProps) {
const [open, setOpen] = useState(false);
const { user } = useCurrentUser();
const { data: author } = useAuthor(target.pubkey);
const { toast } = useToast();
const { webln, activeNWC, hasWebLN, detectWebLN } = useWallet();
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
const [amount, setAmount] = useState<number | string>(100);
const [comment, setComment] = useState<string>('');
const [copied, setCopied] = useState(false);
const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
const inputRef = useRef<HTMLInputElement>(null);
const isMobile = useIsMobile();
useEffect(() => {
if (target) {
setComment('Zapped with MKStack!');
}
}, [target]);
// Detect WebLN when dialog opens
useEffect(() => {
if (open && !hasWebLN) {
detectWebLN();
}
}, [open, hasWebLN, detectWebLN]);
// Generate QR code
useEffect(() => {
let isCancelled = false;
const generateQR = async () => {
if (!invoice) {
setQrCodeUrl('');
return;
}
try {
const url = await QRCode.toDataURL(invoice.toUpperCase(), {
width: 512,
margin: 2,
color: {
dark: '#000000',
light: '#FFFFFF',
},
});
if (!isCancelled) {
setQrCodeUrl(url);
}
} catch (err) {
if (!isCancelled) {
console.error('Failed to generate QR code:', err);
}
}
};
generateQR();
return () => {
isCancelled = true;
};
}, [invoice]);
const handleCopy = async () => {
if (invoice) {
await navigator.clipboard.writeText(invoice);
setCopied(true);
toast({
title: 'Invoice copied',
description: 'Lightning invoice copied to clipboard',
});
setTimeout(() => setCopied(false), 2000);
}
};
const openInWallet = () => {
if (invoice) {
const lightningUrl = `lightning:${invoice}`;
window.open(lightningUrl, '_blank');
}
};
useEffect(() => {
if (open) {
setAmount(100);
setInvoice(null);
setCopied(false);
setQrCodeUrl('');
} else {
// Clean up state when dialog closes
setAmount(100);
setInvoice(null);
setCopied(false);
setQrCodeUrl('');
}
}, [open, setInvoice]);
const handleZap = () => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
zap(finalAmount, comment);
};
const contentProps = {
invoice,
amount,
comment,
isZapping,
qrCodeUrl,
copied,
hasWebLN,
handleZap,
handleCopy,
openInWallet,
setAmount,
setComment,
inputRef,
zap,
};
if (!user || user.pubkey === target.pubkey || !author?.metadata?.lud06 && !author?.metadata?.lud16) {
return null;
}
if (isMobile) {
// Use drawer for entire mobile flow, make it full-screen when showing invoice
return (
<Drawer
open={open}
onOpenChange={(newOpen) => {
// Reset invoice when closing
if (!newOpen) {
setInvoice(null);
setQrCodeUrl('');
}
setOpen(newOpen);
}}
dismissible={true} // Always allow dismissal via drag
snapPoints={invoice ? [0.5, 0.75, 0.98] : [0.98]}
activeSnapPoint={invoice ? 0.98 : 0.98}
modal={true}
shouldScaleBackground={false}
fadeFromIndex={0}
>
<DrawerTrigger asChild>
<div className={`cursor-pointer ${className || ''}`}>
{children}
</div>
</DrawerTrigger>
<DrawerContent
key={invoice ? 'payment' : 'form'}
className={cn(
"transition-all duration-300",
invoice ? "h-full max-h-screen" : "max-h-[98vh]"
)}
data-testid="zap-modal"
>
<DrawerHeader className="text-center relative">
{/* Back button when showing invoice */}
{invoice && (
<Button
variant="ghost"
size="sm"
onClick={() => {
setInvoice(null);
setQrCodeUrl('');
}}
className="absolute left-4 top-4 flex items-center gap-2"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{/* Close button */}
<DrawerClose asChild>
<Button
variant="ghost"
size="sm"
className="absolute right-4 top-4"
>
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</Button>
</DrawerClose>
<DrawerTitle className="text-lg break-words pt-2">
{invoice ? 'Lightning Payment' : 'Send a Zap'}
</DrawerTitle>
<DrawerDescription className="text-sm break-words text-center">
{invoice ? (
'Pay with Bitcoin Lightning Network'
) : (
'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
)}
</DrawerDescription>
</DrawerHeader>
<div className="flex-1 overflow-y-auto px-4 pb-4">
<ZapContent {...contentProps} />
</div>
</DrawerContent>
</Drawer>
);
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<div className={`cursor-pointer ${className || ''}`}>
{children}
</div>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px] max-h-[95vh] overflow-hidden" data-testid="zap-modal">
<DialogHeader>
<DialogTitle className="text-lg break-words">
{invoice ? 'Lightning Payment' : 'Send a Zap'}
</DialogTitle>
<DialogDescription className="text-sm text-center break-words">
{invoice ? (
'Pay with Bitcoin Lightning Network'
) : (
<>
Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!
</>
)}
</DialogDescription>
</DialogHeader>
<div className="overflow-y-auto">
<ZapContent {...contentProps} />
</div>
</DialogContent>
</Dialog>
);
}
+203
View File
@@ -0,0 +1,203 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { ZipImportDialog } from './ZipImportDialog';
import { TestApp } from '@/test/TestApp';
// Mock the useProjects hook
const mockProjects = [
{ id: 'test-project', name: 'Test Project', path: '/projects/test-project', lastModified: new Date() }
];
vi.mock('@/hooks/useProjects', () => ({
useProjects: () => ({
data: mockProjects,
isLoading: false,
error: null
})
}));
describe('ZipImportDialog', () => {
const mockOnImport = vi.fn();
const defaultProps = {
onImport: mockOnImport,
disabled: false
};
beforeEach(() => {
mockOnImport.mockClear();
vi.clearAllMocks();
});
it('renders dialog trigger button', () => {
render(
<TestApp>
<ZipImportDialog {...defaultProps} />
</TestApp>
);
expect(screen.getByText('Import ZIP')).toBeInTheDocument();
});
it('opens dialog when trigger is clicked', async () => {
render(
<TestApp>
<ZipImportDialog {...defaultProps} />
</TestApp>
);
const triggerButton = screen.getByText('Import ZIP');
fireEvent.click(triggerButton);
await waitFor(() => {
expect(screen.getByText('Import Project from ZIP')).toBeInTheDocument();
});
});
it('processes file selection without displaying project ID', async () => {
render(
<TestApp>
<ZipImportDialog {...defaultProps} />
</TestApp>
);
// Open dialog
const triggerButton = screen.getByText('Import ZIP');
fireEvent.click(triggerButton);
// Create a mock file
const file = new File(['test content'], 'my-project.zip', { type: 'application/zip' });
// Find the hidden file input by ref
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
if (fileInput) {
fireEvent.change(fileInput, { target: { files: [file] } });
}
await waitFor(() => {
// Verify that the file name is displayed (from the file selection area)
expect(screen.getByText('my-project.zip')).toBeInTheDocument();
// Verify that Project ID label is not displayed
expect(screen.queryByText('Project ID')).not.toBeInTheDocument();
});
});
it('shows overwrite warning when project ID already exists', async () => {
render(
<TestApp>
<ZipImportDialog {...defaultProps} />
</TestApp>
);
// Open dialog
const triggerButton = screen.getByText('Import ZIP');
fireEvent.click(triggerButton);
// Create a mock file that will generate an existing project ID
const file = new File(['test content'], 'test-project.zip', { type: 'application/zip' });
// Find the hidden file input by ref
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
if (fileInput) {
fireEvent.change(fileInput, { target: { files: [file] } });
}
await waitFor(() => {
expect(screen.getByText(/A project with this ID already exists/)).toBeInTheDocument();
expect(screen.getByText('Overwrite Project')).toBeInTheDocument();
});
});
it('calls onImport with correct parameters when import button is clicked', async () => {
render(
<TestApp>
<ZipImportDialog {...defaultProps} />
</TestApp>
);
// Open dialog
const triggerButton = screen.getByText('Import ZIP');
fireEvent.click(triggerButton);
// Create a mock file
const file = new File(['test content'], 'new-project.zip', { type: 'application/zip' });
// Find the hidden file input by ref
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
if (fileInput) {
fireEvent.change(fileInput, { target: { files: [file] } });
}
// Wait for file to be processed
await waitFor(() => {
expect(screen.getByText('new-project.zip')).toBeInTheDocument();
});
// Click import button
const importButton = screen.getByText('Import Project');
fireEvent.click(importButton);
await waitFor(() => {
expect(mockOnImport).toHaveBeenCalledWith(file, false, "new-project");
});
});
it('shows overwrite confirmation dialog when overwrite button is clicked', async () => {
render(
<TestApp>
<ZipImportDialog {...defaultProps} />
</TestApp>
);
// Open dialog
const triggerButton = screen.getByText('Import ZIP');
fireEvent.click(triggerButton);
// Create a mock file that will generate an existing project ID
const file = new File(['test content'], 'test-project.zip', { type: 'application/zip' });
// Find the hidden file input by ref
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
if (fileInput) {
fireEvent.change(fileInput, { target: { files: [file] } });
}
// Wait for overwrite button to appear
await waitFor(() => {
expect(screen.getByText('Overwrite Project')).toBeInTheDocument();
});
// Click overwrite button
const overwriteButton = screen.getByText('Overwrite Project');
fireEvent.click(overwriteButton);
// Check for overwrite confirmation dialog
await waitFor(() => {
expect(screen.getByText('Overwrite Existing Project')).toBeInTheDocument();
// Use a more flexible matcher for the text that might be split across elements
const dialogContent = screen.getByText('Overwrite Existing Project').closest('.AlertDialogContent');
if (dialogContent) {
expect(dialogContent.textContent).toContain('A project with the ID "test-project" already exists');
}
}, { timeout: 2000 });
});
it('does not show project ID input field (simplified interface)', async () => {
render(
<TestApp>
<ZipImportDialog {...defaultProps} />
</TestApp>
);
// Open dialog
const triggerButton = screen.getByText('Import ZIP');
fireEvent.click(triggerButton);
// Check that there's no input field for project ID
expect(screen.queryByLabelText('Project ID')).not.toBeInTheDocument();
expect(screen.queryByPlaceholderText('project-name')).not.toBeInTheDocument();
});
});
+397
View File
@@ -0,0 +1,397 @@
import React, { useState, useRef, useCallback, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Progress } from '@/components/ui/progress';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
import { Upload, FileArchive, AlertCircle, FileText, Trash2 } from 'lucide-react';
import { useProjects } from '@/hooks/useProjects';
import { cn } from '@/lib/utils';
interface ZipImportDialogProps {
onImport: (file: File, overwrite?: boolean, projectId?: string) => Promise<void>;
disabled?: boolean;
className?: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
export function ZipImportDialog({ onImport, disabled = false, className, open, onOpenChange }: ZipImportDialogProps) {
// Use controlled state if props are provided, otherwise use internal state
const [internalIsOpen, setInternalIsOpen] = useState(false);
const isOpen = open !== undefined ? open : internalIsOpen;
const setIsOpen = onOpenChange || setInternalIsOpen;
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [generatedId, setGeneratedId] = useState('');
const [isImporting, setIsImporting] = useState(false);
const [importProgress, setImportProgress] = useState(0);
const [error, setError] = useState<string | null>(null);
const [isDragOver, setIsDragOver] = useState(false);
const [existingProject, setExistingProject] = useState<{ id: string; name: string } | null>(null);
const [showOverwriteDialog, setShowOverwriteDialog] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const { data: projects = [] } = useProjects();
const handleFileSelect = (file: File) => {
// Only accept zip files
if (!file.name.toLowerCase().endsWith('.zip')) {
setError('Please select a ZIP file');
return;
}
setSelectedFile(file);
setError(null);
// Auto-generate ID from file name
const baseName = file.name.replace(/\.zip$/i, '');
const id = baseName
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
setGeneratedId(id);
};
// Check for existing project when generated ID changes
useEffect(() => {
if (generatedId && projects.length > 0) {
const existing = projects.find(project => project.id === generatedId);
setExistingProject(existing || null);
} else {
setExistingProject(null);
}
}, [generatedId, projects]);
// Drag and drop handlers
const handleDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDragOver(true);
}, []);
const handleDragLeave = useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDragOver(false);
}, []);
const handleDrop = useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDragOver(false);
const files = Array.from(e.dataTransfer.files);
if (files.length > 0) {
handleFileSelect(files[0]);
}
}, []);
const handleDragOverDialog = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(true);
}, []);
const handleDragLeaveDialog = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(false);
}, []);
const handleDropDialog = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(false);
const files = Array.from(e.dataTransfer.files);
if (files.length > 0) {
handleFileSelect(files[0]);
}
}, []);
const handleClickUpload = () => {
fileInputRef.current?.click();
};
const handleFileRemove = () => {
setSelectedFile(null);
setGeneratedId('');
setError(null);
};
const handleImport = async (overwrite = false) => {
if (!selectedFile) return;
setIsImporting(true);
setImportProgress(0);
setError(null);
try {
// Simulate progress for better UX
const progressInterval = setInterval(() => {
setImportProgress(prev => Math.min(prev + 10, 90));
}, 200);
await onImport(selectedFile, overwrite, generatedId);
clearInterval(progressInterval);
setImportProgress(100);
// Close dialog after a short delay
setTimeout(() => {
setIsOpen(false);
setSelectedFile(null);
setGeneratedId('');
setImportProgress(0);
setExistingProject(null);
}, 1000);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to import project');
setImportProgress(0);
} finally {
setIsImporting(false);
}
};
const handleImportWithOverwriteCheck = async () => {
if (!selectedFile || !generatedId) return;
// Check if project with this ID already exists
try {
// This would ideally be passed as a prop or through context
// For now, we'll assume the parent will handle the check and pass existing project info
if (existingProject) {
setShowOverwriteDialog(true);
} else {
await handleImport(false);
}
} catch (error) {
console.error('Error checking existing project:', error);
await handleImport(false);
}
};
const confirmOverwrite = async () => {
setShowOverwriteDialog(false);
await handleImport(true);
};
const handleClose = () => {
if (!isImporting) {
setIsOpen(false);
setSelectedFile(null);
setGeneratedId('');
setError(null);
setImportProgress(0);
}
};
// Only render DialogTrigger if this component is being used in uncontrolled mode
// (no open/onOpenChange props provided)
const isControlled = open !== undefined && onOpenChange !== undefined;
return (
<>
<Dialog open={isOpen} onOpenChange={setIsOpen}>
{!isControlled && (
<DialogTrigger asChild>
<Button
variant="outline"
disabled={disabled}
className={cn("gap-2", className)}
>
<FileArchive className="h-4 w-4" />
Import ZIP
</Button>
</DialogTrigger>
)}
<DialogContent
className="sm:max-w-md"
onDragOver={handleDragOverDialog}
onDragLeave={handleDragLeaveDialog}
onDrop={handleDropDialog}
>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Upload className="h-5 w-5" />
Import Project from ZIP
</DialogTitle>
<DialogDescription>
Upload a ZIP file containing your project source code to import it into Shakespeare.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
{!isImporting && (
<>
{/* Drag and Drop Area */}
<div
className={cn(
"relative border-2 border-dashed rounded-lg p-8 text-center transition-colors cursor-pointer",
isDragOver ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50 hover:bg-primary/5",
selectedFile && "border-green-500/50 bg-green-500/5"
)}
onClick={handleClickUpload}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
<input
ref={fileInputRef}
type="file"
onChange={(e) => {
const files = e.target.files;
if (files && files.length > 0) {
handleFileSelect(files[0]);
}
}}
accept=".zip"
className="hidden"
disabled={isImporting}
/>
<div className="space-y-3">
<div className="flex justify-center">
{selectedFile ? (
<FileText className="h-8 w-8 text-green-600" />
) : (
<Upload className="h-8 w-8 text-muted-foreground" />
)}
</div>
<div>
{selectedFile ? (
<div className="space-y-1">
<p className="text-sm font-medium text-green-600">
{selectedFile.name}
</p>
<p className="text-xs text-muted-foreground">
{(selectedFile.size / 1024 / 1024).toFixed(2)} MB
</p>
<button
onClick={(e) => {
e.stopPropagation();
handleFileRemove();
}}
className="text-xs text-destructive hover:underline"
>
Remove file
</button>
</div>
) : (
<div className="space-y-1">
<p className="text-sm font-medium">
Drop your ZIP file here or click to browse
</p>
<p className="text-xs text-muted-foreground">
Supports ZIP files up to 50MB
</p>
</div>
)}
</div>
</div>
</div>
{/* Error Display */}
{error && (
<div className="flex items-center gap-2 text-sm text-destructive">
<AlertCircle className="h-4 w-4" />
{error}
</div>
)}
{/* Overwrite Warning */}
{existingProject && (
<div className="flex items-center gap-2 text-xs text-amber-600 bg-amber-50 dark:bg-amber-950/20 p-2 rounded">
<AlertCircle className="h-3 w-3" />
A project with this ID already exists. You can choose to overwrite it.
</div>
)}
{/* Import Button */}
<div className="flex justify-end gap-2 pt-4">
<Button variant="outline" onClick={handleClose} disabled={isImporting}>
Cancel
</Button>
<Button
onClick={handleImportWithOverwriteCheck}
disabled={!selectedFile || !generatedId || isImporting}
className={existingProject ? "bg-amber-600 hover:bg-amber-700" : ""}
>
{existingProject ? (
<>
<Trash2 className="mr-2 h-4 w-4" />
Overwrite Project
</>
) : (
<>
<Upload className="mr-2 h-4 w-4" />
Import Project
</>
)}
</Button>
</div>
</>
)}
{/* Import Progress */}
{isImporting && (
<div className="space-y-3">
<div className="flex items-center gap-2 text-sm">
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div>
Importing project...
</div>
<Progress value={importProgress} className="w-full" />
<p className="text-xs text-muted-foreground text-center">
Extracting files and setting up project...
</p>
</div>
)}
{/* Success State */}
{!isImporting && importProgress === 100 && (
<div className="flex items-center gap-2 text-sm text-green-600">
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path>
</svg>
Project imported successfully!
</div>
)}
</div>
</DialogContent>
</Dialog>
{/* Overwrite Confirmation Dialog */}
<AlertDialog open={showOverwriteDialog} onOpenChange={setShowOverwriteDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2">
<AlertCircle className="h-5 w-5 text-amber-600" />
Overwrite Existing Project
</AlertDialogTitle>
<AlertDialogDescription className="space-y-2">
<p>
A project with the ID "<strong>{generatedId}</strong>" already exists.
Overwriting it will:
</p>
<ul className="list-disc list-inside text-sm space-y-1 ml-2">
<li><strong>Delete all existing files</strong> in the project</li>
<li><strong>Replace them with files</strong> from the ZIP archive</li>
<li><strong>Preserve Git history</strong> if it exists</li>
<li><strong>Keep AI chat history</strong> and session data</li>
</ul>
<p className="text-amber-600 font-medium">
This action cannot be undone. Are you sure you want to continue?
</p>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={confirmOverwrite}
className="bg-amber-600 hover:bg-amber-700"
>
Yes, Overwrite Project
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}
-88
View File
@@ -1,88 +0,0 @@
import { useState } from 'react';
import { Settings } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useAISettings } from '@/hooks/useAISettings';
export function AISettingsDialog() {
const { settings, updateSettings, isConfigured } = useAISettings();
const [open, setOpen] = useState(false);
const [localSettings, setLocalSettings] = useState(settings);
const handleSave = () => {
updateSettings(localSettings);
setOpen(false);
};
const handleCancel = () => {
setLocalSettings(settings);
setOpen(false);
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button variant="ghost" size="sm" className="gap-2">
<Settings className="h-4 w-4" />
AI Settings
{!isConfigured && (
<span className="ml-1 h-2 w-2 rounded-full bg-red-500" />
)}
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>AI Settings</DialogTitle>
<DialogDescription>
Configure your AI provider settings. These settings are stored locally in your browser.
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="grid gap-2">
<Label htmlFor="apiKey">API Key</Label>
<Input
id="apiKey"
type="password"
placeholder="Enter your API key"
value={localSettings.apiKey}
onChange={(e) => setLocalSettings({ ...localSettings, apiKey: e.target.value })}
/>
{!localSettings.apiKey && (
<p className="text-sm text-muted-foreground">
Required for AI functionality
</p>
)}
</div>
<div className="grid gap-2">
<Label htmlFor="baseUrl">Base URL</Label>
<Input
id="baseUrl"
placeholder="https://openrouter.ai/api/v1"
value={localSettings.baseUrl}
onChange={(e) => setLocalSettings({ ...localSettings, baseUrl: e.target.value })}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="model">Model</Label>
<Input
id="model"
placeholder="anthropic/claude-sonnet-4"
value={localSettings.model}
onChange={(e) => setLocalSettings({ ...localSettings, model: e.target.value })}
/>
</div>
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={handleCancel}>
Cancel
</Button>
<Button onClick={handleSave}>
Save Settings
</Button>
</div>
</DialogContent>
</Dialog>
);
}
-356
View File
@@ -1,356 +0,0 @@
import { memo } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { Code } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { DiffRenderer } from '@/components/ai/DiffRenderer';
import { ScriptRunner } from '@/components/ai/ScriptRunner';
import { FileViewer } from '@/components/ai/FileViewer';
import { FileWriter } from '@/components/ai/FileWriter';
import { ShellCommand } from '@/components/ai/ShellCommand';
import { PackageManager } from '@/components/ai/PackageManager';
import { GitCommit } from '@/components/ai/GitCommit';
import type { CoreAssistantMessage, CoreToolMessage } from 'ai';
interface AssistantContentProps {
content: CoreAssistantMessage['content'];
toolResults?: CoreToolMessage[];
}
export const AssistantContent = memo(({ content, toolResults = [] }: AssistantContentProps) => {
// Helper function to find tool result by call ID
const findToolResult = (toolCallId: string) => {
for (const toolMessage of toolResults) {
if (toolMessage.content) {
for (const resultPart of toolMessage.content) {
if (resultPart.toolCallId === toolCallId) {
return resultPart;
}
}
}
}
return null;
};
// Helper function to extract result text and error status
const extractToolResult = (toolCallId: string): { result?: string; isError: boolean } => {
const toolResult = findToolResult(toolCallId);
if (!toolResult) {
return { isError: false };
}
// Handle direct string results
if (typeof toolResult.result === 'string') {
return {
result: toolResult.result,
isError: toolResult.isError || false
};
}
// Handle CallToolResult structure
if (toolResult.result && typeof toolResult.result === 'object') {
const callResult = toolResult.result as {
content?: Array<{ type: string; text: string }>;
isError?: boolean;
};
if (callResult.content && Array.isArray(callResult.content) && callResult.content[0]?.text) {
return {
result: callResult.content[0].text,
isError: callResult.isError || false
};
}
}
return { isError: toolResult.isError || false };
};
// Handle string content (simple text messages)
if (typeof content === 'string') {
return (
<div className="prose prose-sm max-w-none dark:prose-invert">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
// Customize code blocks to match the existing tool styling
pre: ({ children }) => (
<pre className="bg-muted/50 rounded p-3 overflow-x-auto text-sm">
{children}
</pre>
),
code: ({ children, className }) => {
const isInline = !className;
if (isInline) {
return (
<code className="bg-muted px-1.5 py-0.5 rounded text-sm font-mono">
{children}
</code>
);
}
return <code className={className}>{children}</code>;
},
// Style links
a: ({ href, children }) => (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline"
>
{children}
</a>
),
// Style blockquotes
blockquote: ({ children }) => (
<blockquote className="border-l-4 border-muted-foreground/20 pl-4 italic text-muted-foreground">
{children}
</blockquote>
),
}}
>
{content}
</ReactMarkdown>
</div>
);
}
return (
<>
{content.map((item, index) => {
if (item.type === 'text') {
return (
<div key={index} className="prose prose-sm max-w-none dark:prose-invert">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
// Customize code blocks to match the existing tool styling
pre: ({ children }) => (
<pre className="bg-muted/50 rounded p-3 overflow-x-auto text-sm">
{children}
</pre>
),
code: ({ children, className }) => {
const isInline = !className;
if (isInline) {
return (
<code className="bg-muted px-1.5 py-0.5 rounded text-sm font-mono">
{children}
</code>
);
}
return <code className={className}>{children}</code>;
},
// Style links
a: ({ href, children }) => (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline"
>
{children}
</a>
),
// Style blockquotes
blockquote: ({ children }) => (
<blockquote className="border-l-4 border-muted-foreground/20 pl-4 italic text-muted-foreground">
{children}
</blockquote>
),
}}
>
{item.text}
</ReactMarkdown>
</div>
);
} else if (item.type === 'tool-call') {
// Special rendering for text_editor_str_replace tool
if (item.toolName === 'text_editor_str_replace' && item.args) {
const { path, old_str, new_str } = item.args as { path: string; old_str: string; new_str: string };
const { result, isError } = extractToolResult(item.toolCallId);
return (
<DiffRenderer
key={index}
path={path}
oldStr={old_str}
newStr={new_str}
result={result}
isError={isError}
/>
);
}
// Special rendering for run_script tool
if (item.toolName === 'run_script' && item.args) {
const { script } = item.args as { script: string };
const { result, isError } = extractToolResult(item.toolCallId);
return (
<ScriptRunner
key={index}
script={script}
result={result}
isError={isError}
/>
);
}
// Special rendering for text_editor_view tool
if (item.toolName === 'text_editor_view' && item.args) {
const { path } = item.args as { path: string };
const { result, isError } = extractToolResult(item.toolCallId);
return (
<FileViewer
key={index}
path={path}
result={result}
isError={isError}
/>
);
}
// Special rendering for text_editor_write tool
if (item.toolName === 'text_editor_write' && item.args) {
const { path, file_text } = item.args as { path: string; file_text: string };
const { result, isError } = extractToolResult(item.toolCallId);
return (
<FileWriter
key={index}
path={path}
fileText={file_text}
result={result}
isError={isError}
/>
);
}
// Special rendering for shell tool
if (item.toolName === 'shell' && item.args) {
const { command } = item.args as { command: string };
const { result, isError } = extractToolResult(item.toolCallId);
return (
<ShellCommand
key={index}
command={command}
result={result}
isError={isError}
/>
);
}
// Special rendering for npm_add_package tool
if (item.toolName === 'npm_add_package' && item.args) {
const { name, version, dev } = item.args as { name: string; version?: string; dev?: boolean };
const { result, isError } = extractToolResult(item.toolCallId);
return (
<PackageManager
key={index}
action="add"
registry="npm"
packageName={name}
version={version}
dev={dev}
result={result}
isError={isError}
/>
);
}
// Special rendering for npm_remove_package tool
if (item.toolName === 'npm_remove_package' && item.args) {
const { name } = item.args as { name: string };
const { result, isError } = extractToolResult(item.toolCallId);
return (
<PackageManager
key={index}
action="remove"
registry="npm"
packageName={name}
result={result}
isError={isError}
/>
);
}
// Special rendering for jsr_add_package tool
if (item.toolName === 'jsr_add_package' && item.args) {
const { name, version, dev } = item.args as { name: string; version?: string; dev?: boolean };
const { result, isError } = extractToolResult(item.toolCallId);
return (
<PackageManager
key={index}
action="add"
registry="jsr"
packageName={name}
version={version}
dev={dev}
result={result}
isError={isError}
/>
);
}
// Special rendering for jsr_remove_package tool
if (item.toolName === 'jsr_remove_package' && item.args) {
const { name } = item.args as { name: string };
const { result, isError } = extractToolResult(item.toolCallId);
return (
<PackageManager
key={index}
action="remove"
registry="jsr"
packageName={name}
result={result}
isError={isError}
/>
);
}
// Special rendering for git_commit tool
if (item.toolName === 'git_commit' && item.args) {
const { message } = item.args as { message: string };
const { result, isError } = extractToolResult(item.toolCallId);
return (
<GitCommit
key={index}
message={message}
result={result}
isError={isError}
/>
);
}
// Default tool rendering for other tools
return (
<Card key={index} className="mt-2 bg-muted/50">
<CardContent className="p-3">
<div className="flex items-center gap-2 mb-2">
<Code className="h-4 w-4 flex-shrink-0" />
<span className="font-mono text-sm break-all">{String(item.toolName)}</span>
</div>
{item.args && typeof item.args === 'object' && item.args !== null && Object.keys(item.args).length > 0 ? (
<div className="text-xs text-muted-foreground mb-2">
<pre className="overflow-hidden text-ellipsis">
{JSON.stringify(item.args, null, 2)}
</pre>
</div>
) : null}
</CardContent>
</Card>
);
}
return null;
})}
</>
);
});
AssistantContent.displayName = 'AssistantContent';
-164
View File
@@ -1,164 +0,0 @@
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { FileText, CheckCircle, XCircle } from 'lucide-react';
import { cn } from '@/lib/utils';
interface DiffRendererProps {
path: string;
oldStr: string;
newStr: string;
result?: string;
isError?: boolean;
className?: string;
}
export function DiffRenderer({ path, oldStr, newStr, result, isError = false, className }: DiffRendererProps) {
// Split strings into lines for diff rendering
const oldLines = oldStr.split('\n');
const newLines = newStr.split('\n');
// Simple diff algorithm - find common prefix and suffix
const findCommonPrefix = (a: string[], b: string[]) => {
let i = 0;
while (i < Math.min(a.length, b.length) && a[i] === b[i]) {
i++;
}
return i;
};
const findCommonSuffix = (a: string[], b: string[], prefixLength: number) => {
let i = 0;
const maxLength = Math.min(a.length - prefixLength, b.length - prefixLength);
while (i < maxLength && a[a.length - 1 - i] === b[b.length - 1 - i]) {
i++;
}
return i;
};
const prefixLength = findCommonPrefix(oldLines, newLines);
const suffixLength = findCommonSuffix(oldLines, newLines, prefixLength);
const commonPrefix = oldLines.slice(0, prefixLength);
const commonSuffix = oldLines.slice(oldLines.length - suffixLength);
const removedLines = oldLines.slice(prefixLength, oldLines.length - suffixLength);
const addedLines = newLines.slice(prefixLength, newLines.length - suffixLength);
return (
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<FileText className="h-4 w-4 text-muted-foreground" />
<span className="font-mono text-sm font-medium">{path}</span>
</div>
<div className="flex items-center gap-2">
{isError ? (
<Badge variant="destructive" className="text-xs">
<XCircle className="h-3 w-3 mr-1" />
Failed
</Badge>
) : (
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
<CheckCircle className="h-3 w-3 mr-1" />
Success
</Badge>
)}
</div>
</div>
</CardHeader>
<CardContent className="pt-0">
<div className="bg-muted/30 rounded-md overflow-x-auto overflow-y-hidden">
<div className="font-mono text-xs min-w-max">
{/* Context before changes */}
{commonPrefix.length > 0 && (
<div className="border-b border-muted/50">
{commonPrefix.slice(-3).map((line, index) => (
<div key={`prefix-${index}`} className="px-3 py-1 text-muted-foreground">
<span className="inline-block w-8 text-right mr-3 select-none">
{prefixLength - 3 + index + 1}
</span>
<span className="whitespace-pre whitespace-nowrap">{line || ' '}</span>
</div>
))}
</div>
)}
{/* Removed lines */}
{removedLines.map((line, index) => (
<div key={`removed-${index}`} className="px-3 py-1 bg-red-50 text-red-800 dark:bg-red-900/20 dark:text-red-300">
<span className="inline-block w-8 text-right mr-3 select-none text-red-600 dark:text-red-400">
-{prefixLength + index + 1}
</span>
<span className="whitespace-pre whitespace-nowrap">
<span className="bg-red-200 dark:bg-red-800/50">-</span>
{line || ' '}
</span>
</div>
))}
{/* Added lines */}
{addedLines.map((line, index) => (
<div key={`added-${index}`} className="px-3 py-1 bg-green-50 text-green-800 dark:bg-green-900/20 dark:text-green-300">
<span className="inline-block w-8 text-right mr-3 select-none text-green-600 dark:text-green-400">
+{prefixLength + index + 1}
</span>
<span className="whitespace-pre whitespace-nowrap">
<span className="bg-green-200 dark:bg-green-800/50">+</span>
{line || ' '}
</span>
</div>
))}
{/* Context after changes */}
{commonSuffix.length > 0 && (
<div className="border-t border-muted/50">
{commonSuffix.slice(0, 3).map((line, index) => (
<div key={`suffix-${index}`} className="px-3 py-1 text-muted-foreground">
<span className="inline-block w-8 text-right mr-3 select-none">
{prefixLength + Math.max(removedLines.length, addedLines.length) + index + 1}
</span>
<span className="whitespace-pre whitespace-nowrap">{line || ' '}</span>
</div>
))}
</div>
)}
{/* Handle case where there are no changes */}
{removedLines.length === 0 && addedLines.length === 0 && (
<div className="px-3 py-4 text-center text-muted-foreground">
No changes detected
</div>
)}
</div>
</div>
{/* Summary */}
<div className="mt-3 flex items-center gap-4 text-xs text-muted-foreground">
{removedLines.length > 0 && (
<span className="text-red-600 dark:text-red-400">
-{removedLines.length} line{removedLines.length !== 1 ? 's' : ''}
</span>
)}
{addedLines.length > 0 && (
<span className="text-green-600 dark:text-green-400">
+{addedLines.length} line{addedLines.length !== 1 ? 's' : ''}
</span>
)}
</div>
{/* Tool Result */}
{result && (
<div className={cn(
"mt-3 p-3 rounded-md text-sm",
isError
? "bg-destructive/10 text-destructive border border-destructive/20"
: "bg-muted/30 text-muted-foreground"
)}>
<pre className="whitespace-pre-wrap break-words">{result}</pre>
</div>
)}
</CardContent>
</Card>
);
}
-171
View File
@@ -1,171 +0,0 @@
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { oneDark, oneLight } from 'react-syntax-highlighter/dist/esm/styles/prism';
import { useTheme } from '@/hooks/useTheme';
import { cn } from '@/lib/utils';
interface FileContentsProps {
content: string;
filePath: string;
className?: string;
showLineNumbers?: boolean;
maxHeight?: string;
showHeader?: boolean;
headerContent?: React.ReactNode;
}
export function FileContents({
content,
filePath,
className,
showLineNumbers,
maxHeight = 'max-h-80',
showHeader = true,
headerContent
}: FileContentsProps) {
const { theme } = useTheme();
// Get file extension for syntax highlighting hints
const getFileExtension = (path: string) => {
const parts = path.split('.');
return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : '';
};
// Map file extensions to syntax highlighter languages
const getLanguageFromExtension = (ext: string): string => {
const languageMap: Record<string, string> = {
'ts': 'typescript',
'tsx': 'tsx',
'js': 'javascript',
'jsx': 'jsx',
'json': 'json',
'md': 'markdown',
'css': 'css',
'scss': 'scss',
'sass': 'sass',
'less': 'less',
'html': 'html',
'xml': 'xml',
'svg': 'xml',
'yml': 'yaml',
'yaml': 'yaml',
'toml': 'toml',
'py': 'python',
'rb': 'ruby',
'php': 'php',
'java': 'java',
'c': 'c',
'cpp': 'cpp',
'cs': 'csharp',
'go': 'go',
'rs': 'rust',
'sh': 'bash',
'bash': 'bash',
'zsh': 'bash',
'fish': 'bash',
'sql': 'sql',
'dockerfile': 'dockerfile',
'gitignore': 'gitignore',
'env': 'bash',
'ini': 'ini',
'conf': 'nginx',
'nginx': 'nginx',
'apache': 'apache',
'htaccess': 'apache',
'vim': 'vim',
'lua': 'lua',
'r': 'r',
'matlab': 'matlab',
'swift': 'swift',
'kotlin': 'kotlin',
'dart': 'dart',
'elm': 'elm',
'haskell': 'haskell',
'clojure': 'clojure',
'scala': 'scala',
'perl': 'perl',
'powershell': 'powershell',
'makefile': 'makefile',
'cmake': 'cmake',
'gradle': 'gradle',
'properties': 'properties',
'diff': 'diff',
'patch': 'diff',
'log': 'log'
};
return languageMap[ext] || 'text';
};
// Check if content should be syntax highlighted
const shouldHighlight = (ext: string, text: string): boolean => {
// Don't highlight very large files (over 50KB) for performance
if (text.length > 50000) return false;
// Don't highlight binary-looking content (check for null bytes and other binary indicators)
if (text.includes('\0') || text.includes('\uFFFD')) return false;
// Always highlight known code file extensions
const codeExtensions = ['ts', 'tsx', 'js', 'jsx', 'json', 'css', 'scss', 'html', 'xml', 'py', 'rb', 'php', 'java', 'c', 'cpp', 'cs', 'go', 'rs', 'sh', 'bash', 'sql', 'yml', 'yaml', 'toml', 'md'];
return codeExtensions.includes(ext);
};
const fileExtension = getFileExtension(filePath);
const shouldUseHighlighting = shouldHighlight(fileExtension, content);
// Determine if we should show line numbers
const shouldShowLineNumbers = showLineNumbers ?? (content.split('\n').length > 10);
return (
<div className={cn("bg-muted/30 rounded-md overflow-hidden", className)}>
{showHeader && (
<div className="bg-muted/50 px-3 py-2 text-xs font-mono text-muted-foreground border-b border-muted/50 flex items-center justify-between">
<span>File Contents</span>
{headerContent || (fileExtension && (
<span className="text-xs bg-muted px-2 py-1 rounded">
{fileExtension.toUpperCase()}
</span>
))}
</div>
)}
<div className={cn("p-0 overflow-auto", maxHeight)}>
{shouldUseHighlighting ? (
<SyntaxHighlighter
language={getLanguageFromExtension(fileExtension)}
style={theme === 'dark' ? oneDark : oneLight}
customStyle={{
margin: 0,
padding: '12px',
fontSize: '12px',
lineHeight: '1.4',
background: 'transparent',
border: 'none',
borderRadius: 0,
}}
codeTagProps={{
style: {
fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace',
}
}}
showLineNumbers={shouldShowLineNumbers}
lineNumberStyle={{
minWidth: '2.5em',
paddingRight: '1em',
color: theme === 'dark' ? '#6b7280' : '#9ca3af',
fontSize: '11px',
}}
wrapLines={false}
wrapLongLines={false}
>
{content}
</SyntaxHighlighter>
) : (
<div className="p-3">
<pre className="text-xs font-mono whitespace-pre text-foreground">
{content}
</pre>
</div>
)}
</div>
</div>
);
}
-175
View File
@@ -1,175 +0,0 @@
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { CheckCircle, XCircle, Eye } from 'lucide-react';
import { cn } from '@/lib/utils';
import { FileContents } from '@/components/ai/FileContents';
interface FileViewerProps {
path: string;
result?: string;
isError?: boolean;
className?: string;
}
export function FileViewer({ path, result, isError = false, className }: FileViewerProps) {
// Determine if it's a directory or file based on the result
const isDirectory = result?.includes('├──') || result?.includes('└──') || result?.includes('│');
// Get file extension for syntax highlighting hints
const getFileExtension = (filePath: string) => {
const parts = filePath.split('.');
return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : '';
};
const getFileIcon = (filePath: string, isDir: boolean) => {
if (isDir) return '📁';
const ext = getFileExtension(filePath);
switch (ext) {
case 'ts':
case 'tsx': return '🔷';
case 'js':
case 'jsx': return '🟨';
case 'json': return '📋';
case 'md': return '📝';
case 'css': return '🎨';
case 'html': return '🌐';
case 'svg': return '🖼️';
case 'png':
case 'jpg':
case 'jpeg':
case 'gif': return '🖼️';
case 'yml':
case 'yaml': return '⚙️';
case 'toml': return '⚙️';
case 'lock': return '🔒';
default: return '📄';
}
};
const fileIcon = getFileIcon(path, isDirectory || false);
const fileExtension = getFileExtension(path);
// Parse directory structure for better display
const parseDirectoryStructure = (content: string) => {
if (!isDirectory) return content;
const lines = content.split('\n').filter(line => line.trim());
return lines.map((line) => {
// Extract the file/folder name from tree structure
const match = line.match(/[├└]──\s*(.+)$/);
if (match) {
const name = match[1];
const isFolder = !name.includes('.');
const icon = isFolder ? '📁' : getFileIcon(name, false);
return { line, name, icon, isFolder };
}
return { line, name: line.trim(), icon: '📄', isFolder: false };
});
};
const directoryItems = isDirectory ? parseDirectoryStructure(result || '') : [];
const directoryItemsArray = Array.isArray(directoryItems) ? directoryItems : [];
return (
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<Eye className="h-4 w-4 text-muted-foreground" />
<span className="text-lg">{fileIcon}</span>
</div>
<div>
<div className="font-mono text-sm font-medium">{path}</div>
<div className="text-xs text-muted-foreground">
{isDirectory ? 'Directory listing' : `${fileExtension ? fileExtension.toUpperCase() + ' file' : 'File'} contents`}
</div>
</div>
</div>
<div className="flex items-center gap-2">
{result ? (
isError ? (
<Badge variant="destructive" className="text-xs">
<XCircle className="h-3 w-3 mr-1" />
Error
</Badge>
) : (
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
<CheckCircle className="h-3 w-3 mr-1" />
Viewed
</Badge>
)
) : (
<Badge variant="secondary" className="text-xs bg-gray-100 text-gray-800 dark:bg-gray-900/20 dark:text-gray-400">
<Eye className="h-3 w-3 mr-1" />
Loading
</Badge>
)}
</div>
</div>
</CardHeader>
{result && (
<CardContent className="pt-0">
{isError ? (
<div className="bg-destructive/10 text-destructive border border-destructive/20 rounded-md p-3 text-sm">
{result}
</div>
) : isDirectory ? (
<div className="bg-muted/30 rounded-md overflow-hidden">
<div className="bg-muted/50 px-3 py-2 text-xs font-mono text-muted-foreground border-b border-muted/50">
Directory Structure
</div>
<div className="p-3 max-h-80 overflow-y-auto">
<div className="space-y-1">
{directoryItemsArray.map((item, index) => (
<div key={index} className="flex items-center gap-2 text-sm font-mono">
<span className="text-muted-foreground">{item.line.replace(/[├└]──\s*(.+)$/, '')}</span>
<span className="text-xs">{item.icon}</span>
<span className={cn(
item.isFolder ? "text-blue-600 dark:text-blue-400 font-medium" : "text-foreground"
)}>
{item.name}
</span>
</div>
))}
</div>
</div>
</div>
) : (
<FileContents
content={result}
filePath={path}
headerContent={fileExtension && (
<span className="text-xs bg-muted px-2 py-1 rounded">
{fileExtension.toUpperCase()}
</span>
)}
/>
)}
{/* File stats */}
{!isError && result && (
<div className="mt-3 flex items-center gap-4 text-xs text-muted-foreground">
{isDirectory ? (
<span>
{directoryItemsArray.length} item{directoryItemsArray.length !== 1 ? 's' : ''}
</span>
) : (
<>
<span>
{result.split('\n').length} line{result.split('\n').length !== 1 ? 's' : ''}
</span>
<span>
{result.length} character{result.length !== 1 ? 's' : ''}
</span>
</>
)}
</div>
)}
</CardContent>
)}
</Card>
);
}
-152
View File
@@ -1,152 +0,0 @@
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { CheckCircle, XCircle, Edit3 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { FileContents } from '@/components/ai/FileContents';
interface FileWriterProps {
path: string;
fileText: string;
result?: string;
isError?: boolean;
className?: string;
}
export function FileWriter({ path, fileText, result, isError = false, className }: FileWriterProps) {
// Get file extension for syntax highlighting hints
const getFileExtension = (filePath: string) => {
const parts = filePath.split('.');
return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : '';
};
const getFileIcon = (filePath: string) => {
const ext = getFileExtension(filePath);
switch (ext) {
case 'ts':
case 'tsx': return '🔷';
case 'js':
case 'jsx': return '🟨';
case 'json': return '📋';
case 'md': return '📝';
case 'css': return '🎨';
case 'html': return '🌐';
case 'svg': return '🖼️';
case 'png':
case 'jpg':
case 'jpeg':
case 'gif': return '🖼️';
case 'yml':
case 'yaml': return '⚙️';
case 'toml': return '⚙️';
case 'lock': return '🔒';
default: return '📄';
}
};
const fileIcon = getFileIcon(path);
const fileExtension = getFileExtension(path);
const isNewFile = path.includes('new') || result?.includes('created') || result?.includes('Created');
// Calculate file stats
const lineCount = fileText.split('\n').length;
const charCount = fileText.length;
const wordCount = fileText.split(/\s+/).filter(word => word.length > 0).length;
// Preview first few lines for collapsed view
const previewLines = fileText.split('\n').slice(0, 5);
const hasMoreLines = lineCount > 5;
const previewContent = previewLines.join('\n') + (hasMoreLines ? `\n... (${lineCount - 5} more lines)` : '');
return (
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<Edit3 className="h-4 w-4 text-muted-foreground" />
<span className="text-lg">{fileIcon}</span>
</div>
<div>
<div className="font-mono text-sm font-medium">{path}</div>
<div className="text-xs text-muted-foreground">
{isNewFile ? 'Created new file' : 'Updated file contents'}
</div>
</div>
</div>
<div className="flex items-center gap-2">
{result !== undefined ? (
isError ? (
<Badge variant="destructive" className="text-xs">
<XCircle className="h-3 w-3 mr-1" />
Failed
</Badge>
) : (
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
<CheckCircle className="h-3 w-3 mr-1" />
{isNewFile ? 'Created' : 'Updated'}
</Badge>
)
) : (
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
<Edit3 className="h-3 w-3 mr-1" />
Writing
</Badge>
)}
</div>
</div>
</CardHeader>
<CardContent className="pt-0">
{/* Error display */}
{isError && result && (
<div className="mb-3 bg-destructive/10 text-destructive border border-destructive/20 rounded-md p-3 text-sm">
{result}
</div>
)}
{/* File stats */}
<div className="mb-3 flex items-center gap-4 text-xs">
<span className="text-muted-foreground">
{lineCount} line{lineCount !== 1 ? 's' : ''}
</span>
<span className="text-muted-foreground">
{wordCount} word{wordCount !== 1 ? 's' : ''}
</span>
<span className="text-muted-foreground">
{charCount} character{charCount !== 1 ? 's' : ''}
</span>
{fileExtension && (
<Badge variant="outline" className="text-xs">
{fileExtension.toUpperCase()}
</Badge>
)}
</div>
{/* File preview */}
<details className="group">
<summary className="cursor-pointer text-xs text-muted-foreground hover:text-foreground transition-colors mb-2 flex items-center gap-1">
<span className="group-open:rotate-90 transition-transform">▶</span>
Preview file contents
</summary>
<FileContents
content={hasMoreLines ? previewContent : fileText}
filePath={path}
showLineNumbers={false}
headerContent={fileExtension && (
<span className="text-xs bg-muted px-2 py-1 rounded">
{fileExtension.toUpperCase()}
</span>
)}
/>
</details>
{/* Success message */}
{!isError && result && (
<div className="mt-3 text-xs text-green-600 dark:text-green-400">
✓ File {isNewFile ? 'created' : 'updated'} successfully
</div>
)}
</CardContent>
</Card>
);
}
-175
View File
@@ -1,175 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { GitHistoryDialog } from './GitHistoryDialog';
// Mock isomorphic-git
vi.mock('isomorphic-git', () => ({
default: {
log: vi.fn(),
resolveRef: vi.fn(),
readCommit: vi.fn(),
listFiles: vi.fn(),
readBlob: vi.fn(),
add: vi.fn(),
remove: vi.fn(),
commit: vi.fn(),
},
}));
// Mock the useFS hook
vi.mock('@/hooks/useFS', () => ({
useFS: () => ({
fs: {
stat: vi.fn(),
unlink: vi.fn(),
mkdir: vi.fn(),
writeFile: vi.fn(),
},
}),
}));
// Mock the useToast hook
vi.mock('@/hooks/useToast', () => ({
useToast: () => ({
toast: vi.fn(),
}),
}));
describe('GitHistoryDialog', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('renders the history button', () => {
render(
<TestApp>
<GitHistoryDialog projectId="test-project" />
</TestApp>
);
expect(screen.getByRole('button', { name: /history/i })).toBeInTheDocument();
});
it('opens dialog when history button is clicked', async () => {
render(
<TestApp>
<GitHistoryDialog projectId="test-project" />
</TestApp>
);
const historyButton = screen.getByRole('button', { name: /history/i });
fireEvent.click(historyButton);
await waitFor(() => {
expect(screen.getByText('Git History')).toBeInTheDocument();
});
});
it('shows loading state when dialog opens', async () => {
render(
<TestApp>
<GitHistoryDialog projectId="test-project" />
</TestApp>
);
const historyButton = screen.getByRole('button', { name: /history/i });
fireEvent.click(historyButton);
await waitFor(() => {
expect(screen.getByText('Loading git history...')).toBeInTheDocument();
});
});
it('renders rollback buttons for commits (except the first one)', async () => {
const mockCommits = [
{
oid: 'commit1',
commit: {
message: 'Latest commit',
author: { name: 'User', email: '[email protected]', timestamp: Math.floor(Date.now() / 1000), timezoneOffset: 0 },
committer: { name: 'User', email: '[email protected]', timestamp: Math.floor(Date.now() / 1000), timezoneOffset: 0 },
parent: [],
tree: 'tree1',
},
payload: '',
},
{
oid: 'commit2',
commit: {
message: 'Previous commit',
author: { name: 'User', email: '[email protected]', timestamp: Math.floor(Date.now() / 1000) - 3600, timezoneOffset: 0 },
committer: { name: 'User', email: '[email protected]', timestamp: Math.floor(Date.now() / 1000) - 3600, timezoneOffset: 0 },
parent: [],
tree: 'tree2',
},
payload: '',
},
];
const git = await import('isomorphic-git');
vi.mocked(git.default.log).mockResolvedValue(mockCommits);
render(
<TestApp>
<GitHistoryDialog projectId="test-project" />
</TestApp>
);
const historyButton = screen.getByRole('button', { name: /history/i });
fireEvent.click(historyButton);
await waitFor(() => {
expect(screen.getByText('Latest commit')).toBeInTheDocument();
expect(screen.getByText('Previous commit')).toBeInTheDocument();
});
// Should have one rollback button (not for the latest commit)
const rollbackButtons = screen.getAllByText('Rollback');
expect(rollbackButtons).toHaveLength(1);
});
it('handles multi-line commit messages with expand/collapse', async () => {
const mockCommits = [
{
oid: 'commit1',
commit: {
message: 'Add new feature\n\nThis commit adds a new feature with the following changes:\n- Added component A\n- Updated component B\n- Fixed bug in component C',
author: { name: 'User', email: '[email protected]', timestamp: Math.floor(Date.now() / 1000), timezoneOffset: 0 },
committer: { name: 'User', email: '[email protected]', timestamp: Math.floor(Date.now() / 1000), timezoneOffset: 0 },
parent: [],
tree: 'tree1',
},
payload: '',
},
];
const git = await import('isomorphic-git');
vi.mocked(git.default.log).mockResolvedValue(mockCommits);
render(
<TestApp>
<GitHistoryDialog projectId="test-project" />
</TestApp>
);
const historyButton = screen.getByRole('button', { name: /history/i });
fireEvent.click(historyButton);
await waitFor(() => {
expect(screen.getByText('Add new feature')).toBeInTheDocument();
});
// Should show expand button for multi-line commit
const expandButton = screen.getByRole('button', { name: '' }); // ChevronDown button
expect(expandButton).toBeInTheDocument();
// Click to expand
fireEvent.click(expandButton);
// Should show the expanded content
await waitFor(() => {
expect(screen.getByText(/This commit adds a new feature/)).toBeInTheDocument();
});
});
});
+211 -44
View File
@@ -1,13 +1,14 @@
import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Badge } from '@/components/ui/badge';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
import { History, GitCommit, RotateCcw, AlertTriangle, ChevronDown, ChevronUp } from 'lucide-react';
import { useGit } from '@/hooks/useGit';
import { useFS } from '@/hooks/useFS';
import { useToast } from '@/hooks/useToast';
import git from 'isomorphic-git';
import { useGitStatus } from '@/hooks/useGitStatus';
interface GitCommit {
oid: string;
@@ -28,21 +29,28 @@ interface GitCommit {
interface GitHistoryDialogProps {
projectId: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
export function GitHistoryDialog({ projectId }: GitHistoryDialogProps) {
export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange }: GitHistoryDialogProps) {
const [commits, setCommits] = useState<GitCommit[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [isOpen, setIsOpen] = useState(false);
const [internalOpen, setInternalOpen] = useState(false);
// Use controlled or internal state
const isOpen = controlledOpen !== undefined ? controlledOpen : internalOpen;
const setIsOpen = onOpenChange || setInternalOpen;
const [isRollingBack, setIsRollingBack] = useState<string | null>(null);
const [expandedCommits, setExpandedCommits] = useState<Set<string>>(new Set());
const { fs } = useFS();
const { git } = useGit();
const { toast } = useToast();
const navigate = useNavigate();
const { data: gitStatus } = useGitStatus(projectId);
const loadGitHistory = useCallback(async () => {
if (!fs) return;
setIsLoading(true);
setError(null);
@@ -51,7 +59,7 @@ export function GitHistoryDialog({ projectId }: GitHistoryDialogProps) {
// Check if git repository exists
try {
await fs.stat(`${projectPath}/.git`);
await git.findRoot({ filepath: projectPath });
} catch {
setError('No git repository found in this project');
return;
@@ -59,7 +67,6 @@ export function GitHistoryDialog({ projectId }: GitHistoryDialogProps) {
// Get git log
const gitLog = await git.log({
fs,
dir: projectPath,
depth: 50, // Limit to last 50 commits
});
@@ -71,7 +78,7 @@ export function GitHistoryDialog({ projectId }: GitHistoryDialogProps) {
} finally {
setIsLoading(false);
}
}, [fs, projectId]);
}, [git, projectId]);
const rollbackToCommit = useCallback(async (targetCommit: GitCommit) => {
if (!fs) return;
@@ -83,7 +90,6 @@ export function GitHistoryDialog({ projectId }: GitHistoryDialogProps) {
// Get the current HEAD commit
const currentCommit = await git.resolveRef({
fs,
dir: projectPath,
ref: 'HEAD',
});
@@ -99,7 +105,6 @@ export function GitHistoryDialog({ projectId }: GitHistoryDialogProps) {
// Get all commits between the target commit and HEAD
const allCommits = await git.log({
fs,
dir: projectPath,
depth: 1000,
});
@@ -132,14 +137,12 @@ export function GitHistoryDialog({ projectId }: GitHistoryDialogProps) {
// Get all files from the target commit
const targetFiles = await git.listFiles({
fs,
dir: projectPath,
ref: targetCommit.oid,
});
// Get current files to know what to remove
const currentFiles = await git.listFiles({
fs,
dir: projectPath,
ref: 'HEAD',
});
@@ -150,7 +153,6 @@ export function GitHistoryDialog({ projectId }: GitHistoryDialogProps) {
try {
await fs.unlink(`${projectPath}/${filepath}`);
await git.remove({
fs,
dir: projectPath,
filepath,
});
@@ -165,7 +167,6 @@ export function GitHistoryDialog({ projectId }: GitHistoryDialogProps) {
for (const filepath of targetFiles) {
try {
const { blob } = await git.readBlob({
fs,
dir: projectPath,
oid: targetCommit.oid,
filepath,
@@ -182,7 +183,6 @@ export function GitHistoryDialog({ projectId }: GitHistoryDialogProps) {
// Stage the file
await git.add({
fs,
dir: projectPath,
filepath,
});
@@ -204,7 +204,6 @@ ${commitsToRevert.map(c => {
}).join('\n')}`;
await git.commit({
fs,
dir: projectPath,
message: revertMessage,
author: {
@@ -218,8 +217,9 @@ ${commitsToRevert.map(c => {
description: `Reverted ${commitsToRevert.length} commit(s) back to ${targetCommit.oid.substring(0, 7)}`,
});
// Reload the git history to show the new commit
await loadGitHistory();
// Close the dialog and navigate to project page with build query parameter
setIsOpen(false);
navigate(`/project/${projectId}?build`);
} catch (err) {
console.error('Failed to rollback:', err);
@@ -231,7 +231,106 @@ ${commitsToRevert.map(c => {
} finally {
setIsRollingBack(null);
}
}, [fs, projectId, toast, loadGitHistory]);
}, [git, fs, projectId, toast, navigate, setIsOpen]);
const resetToHead = useCallback(async () => {
if (!fs) return;
setIsRollingBack('HEAD');
try {
const projectPath = `/projects/${projectId}`;
// Get the current HEAD commit
const headCommit = await git.resolveRef({
dir: projectPath,
ref: 'HEAD',
});
// Get all files from HEAD
const headFiles = await git.listFiles({
dir: projectPath,
ref: 'HEAD',
});
// Get current files in working directory
const currentFiles = await git.listFiles({
dir: projectPath,
});
// Remove files that don't exist in HEAD (equivalent to git clean -fd for tracked files)
for (const filepath of currentFiles) {
if (!headFiles.includes(filepath)) {
try {
await fs.unlink(`${projectPath}/${filepath}`);
} catch (err) {
console.warn(`Could not remove ${filepath}:`, err);
}
}
}
// Reset all files to HEAD state (equivalent to git reset --hard HEAD)
for (const filepath of headFiles) {
try {
const { blob } = await git.readBlob({
dir: projectPath,
oid: headCommit,
filepath,
});
// Ensure directory exists
const dirPath = filepath.split('/').slice(0, -1).join('/');
if (dirPath) {
await fs.mkdir(`${projectPath}/${dirPath}`, { recursive: true });
}
// Write the file
await fs.writeFile(`${projectPath}/${filepath}`, blob);
} catch (err) {
console.error(`Failed to reset ${filepath}:`, err);
}
}
// Remove untracked files and directories (equivalent to git clean -fd)
// Get git status to find untracked files
const status = await git.statusMatrix({
dir: projectPath,
});
const untrackedFiles = status
.filter(([, headStatus, workdirStatus, stageStatus]) =>
headStatus === 0 && workdirStatus === 1 && stageStatus === 0
)
.map(([filepath]) => filepath);
for (const filepath of untrackedFiles) {
try {
await fs.unlink(`${projectPath}/${filepath}`);
} catch (err) {
console.warn(`Could not remove untracked file ${filepath}:`, err);
}
}
toast({
title: "Reset successful",
description: "All changes have been discarded and working directory reset to HEAD",
});
// Close the dialog and navigate to project page with build query parameter
setIsOpen(false);
navigate(`/project/${projectId}?build`);
} catch (err) {
console.error('Failed to reset:', err);
toast({
title: "Reset failed",
description: err instanceof Error ? err.message : 'Failed to reset to HEAD',
variant: "destructive",
});
} finally {
setIsRollingBack(null);
}
}, [git, fs, projectId, toast, navigate, setIsOpen]);
useEffect(() => {
if (isOpen) {
@@ -280,28 +379,31 @@ ${commitsToRevert.map(c => {
return (
<Dialog open={isOpen} onOpenChange={setIsOpen}>
<DialogTrigger asChild>
<Button
variant="outline"
size="sm"
className="gap-1 sm:gap-2 hover:bg-secondary/10 hover:border-secondary/20"
>
<History className="h-4 w-4" />
<span className="hidden sm:inline">History</span>
</Button>
</DialogTrigger>
<DialogContent className="max-w-4xl max-h-[80vh]">
{/* Only show trigger if not controlled externally */}
{controlledOpen === undefined && (
<DialogTrigger asChild>
<Button
variant="outline"
size="sm"
className="gap-1 sm:gap-2 hover:bg-secondary/10 hover:border-secondary/20"
>
<History className="h-4 w-4" />
<span className="hidden sm:inline">History</span>
</Button>
</DialogTrigger>
)}
<DialogContent className="max-w-4xl max-h-[80vh] overflow-hidden">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<GitCommit className="h-5 w-5" />
Git History
<History className="h-5 w-5" />
Rollback
</DialogTitle>
<DialogDescription>
View the commit history for this project
Revert to an older commit
</DialogDescription>
</DialogHeader>
<div className="flex-1 min-h-0">
<div className="flex-1 min-h-0 max-w-full overflow-hidden">
{isLoading ? (
<div className="flex items-center justify-center py-8">
<div className="flex items-center gap-2 text-muted-foreground">
@@ -330,7 +432,7 @@ ${commitsToRevert.map(c => {
</div>
</div>
) : (
<ScrollArea className="h-[60vh]">
<div className="h-[60vh] overflow-y-scroll">
<div className="space-y-1 pr-4">
{commits.map((commit, index) => {
const { firstLine, hasMoreLines, fullMessage } = getCommitMessageLines(commit.commit.message);
@@ -341,7 +443,7 @@ ${commitsToRevert.map(c => {
<div className="flex items-start justify-between gap-3">
<div className="flex-1 min-w-0 space-y-1">
<div className="flex items-center gap-2 mb-1">
<h3 className="font-medium text-sm text-foreground break-words">
<h3 className="font-medium text-sm text-foreground truncate">
{firstLine}
</h3>
{hasMoreLines && (
@@ -373,7 +475,76 @@ ${commitsToRevert.map(c => {
</div>
<div className="flex items-center gap-2 shrink-0">
{index > 0 && ( // Don't show rollback for the most recent commit
{index === 0 ? (
// Show "Current" or "Rollback" for the most recent commit
gitStatus?.hasUncommittedChanges ? (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
variant="outline"
size="sm"
className="h-7 px-2 text-xs gap-1 hover:bg-destructive/10 hover:border-destructive/20 hover:text-destructive"
disabled={isRollingBack !== null}
>
<RotateCcw className="h-3 w-3" />
Rollback
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-destructive" />
Discard All Changes
</AlertDialogTitle>
<AlertDialogDescription className="space-y-2">
<p>
This will discard all unstaged changes and reset your working directory to the current commit:
</p>
<div className="bg-muted p-3 rounded-md text-sm">
<div className="font-medium break-words">{firstLine}</div>
<div className="text-muted-foreground text-xs mt-1">
{commit.oid.substring(0, 7)} • {formatRelativeTime(commit.commit.author.timestamp)}
</div>
</div>
<p className="text-sm">
This action cannot be undone.
</p>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={resetToHead}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
disabled={isRollingBack !== null}
>
{isRollingBack === 'HEAD' ? (
<>
<div className="h-3 w-3 animate-spin rounded-full border border-current border-t-transparent mr-1" />
Discarding...
</>
) : (
<>
<RotateCcw className="h-3 w-3 mr-1" />
Discard Changes
</>
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
) : (
<Button
variant="outline"
size="sm"
className="h-7 px-2 text-xs gap-1 cursor-default"
disabled
>
Current
</Button>
)
) : (
// Show rollback button for older commits
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
@@ -431,17 +602,13 @@ ${commitsToRevert.map(c => {
</AlertDialogContent>
</AlertDialog>
)}
<Badge variant="secondary" className="text-xs font-mono">
{commit.oid.substring(0, 7)}
</Badge>
</div>
</div>
</div>
);
})}
</div>
</ScrollArea>
</div>
)}
</div>
</DialogContent>
-74
View File
@@ -1,74 +0,0 @@
import { memo } from 'react';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { AssistantContent } from '@/components/ai/AssistantContent';
import { Bot, User } from 'lucide-react';
import type { CoreUserMessage, CoreAssistantMessage, CoreToolMessage } from 'ai';
interface MessageItemProps {
message: (CoreUserMessage | CoreAssistantMessage | CoreToolMessage) & { id: string };
userDisplayName?: string;
userProfileImage?: string;
toolResults?: CoreToolMessage[];
}
export const MessageItem = memo(({
message,
userDisplayName = 'You',
userProfileImage,
toolResults = []
}: MessageItemProps) => {
// Don't render tool messages as separate items - they're integrated into assistant messages
if (message.role === 'tool') {
return null;
}
return (
<div className="flex gap-3">
<Avatar className="h-8 w-8 flex-shrink-0">
{message.role === 'user' ? (
<>
<AvatarImage src={userProfileImage} alt={userDisplayName} />
<AvatarFallback>
<User className="h-4 w-4" />
</AvatarFallback>
</>
) : (
<>
<AvatarFallback>
<Bot className="h-4 w-4" />
</AvatarFallback>
</>
)}
</Avatar>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<span className="font-medium text-sm">
{message.role === 'user' ? userDisplayName : 'Assistant'}
</span>
<span className="text-xs text-muted-foreground">
{message.role === 'user' ? 'User' : 'AI'}
</span>
</div>
<div className="text-sm">
{message.role === 'user' ? (
<div className="whitespace-pre-wrap break-words">
{typeof message.content === 'string' ? message.content :
message.content.map((part, _i) => {
if (part.type === 'text') return part.text;
return null;
}).join('')
}
</div>
) : message.role === 'assistant' ? (
<AssistantContent
content={(message as CoreAssistantMessage).content}
toolResults={toolResults}
/>
) : null}
</div>
</div>
</div>
);
});
MessageItem.displayName = 'MessageItem';
Loaded 100 of 362 files, more files were not shown because too many files have changed in this diff. Show more