Compare commits

...
Author SHA1 Message Date
Chad Curtis 898c6a8286 Use orange for overwrite warning (akin to original implementation 2025-09-28 18:46:12 +00:00
Chad Curtis 7f14194ae4 rm space 2025-09-28 18:34:00 +00:00
Chad Curtis 2ea05addcc Cleanup 2025-09-28 18:31:10 +00:00
Chad Curtis 9507177aaa Update clone dialog to use project import dialog 2025-09-28 18:24:46 +00:00
Chad Curtis 669bbb8a1f merge in from upstream and resolve conflicts 2025-09-28 18:21:16 +00: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
Chad Curtis 15567ee4cf Close zip dialog immediately after import. 2025-09-26 18:20:10 +00:00
Chad Curtis 2d163e8fed Further unification and refactoring. 2025-09-26 18:20:10 +00:00
Chad Curtis f6f9a0038b Invalidate projects list after mass import 2025-09-26 18:20:10 +00:00
Chad Curtis c26f447072 Merge in from upstream and resolve conflicts. 2025-09-26 18:20:10 +00:00
Chad Curtis 3253b198c7 Init zip bulk import 2025-09-26 18:20:10 +00: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
Alex Gleason 27fb8103a3 Remove pointless separators from settings pages 2025-09-20 12:59:17 -05: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
Alex Gleason 62f5a4fe87 Expose model description 2025-09-20 12:12:26 -05: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
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
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
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
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
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
173 changed files with 14187 additions and 3865 deletions

No files matched your search

+2
View File
@@ -11,6 +11,8 @@ stages:
test:
stage: test
script:
- npm run typecheck
- npm run build
- npm run test
pages:
+4 -1
View File
@@ -51,6 +51,7 @@ Shakespeare provides AI agents with specialized tools for project development (n
- **NostrReadNipsIndexTool**: Read the full list of NIPs, kinds, and tags
- **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
@@ -168,6 +169,8 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `/src/components/ai/`: AI-related components (GitCommit, GitHistoryDialog)
- `/src/components/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
@@ -182,7 +185,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `useSessionManager`: Access session management for AI chat sessions
- `useGitStatus`: Real-time Git repository status monitoring
- `useProjects`: Project management and CRUD operations
- `useProjectsManager`: Advanced project operations (creation, cloning, building)
- `useProjectsManager`: Advanced project operations (creation, cloning, building, ZIP import)
- `useTheme`: Theme management
- `useToast`: Toast notifications
- `useLocalStorage`: Persistent local storage
+30
View File
@@ -148,6 +148,36 @@ consistent handling of both text and binary data across the messaging protocol.
**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
+29 -1
View File
@@ -136,7 +136,27 @@ The system now uses a simplified JSON-RPC 2.0 protocol with two methods:
- 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
@@ -322,6 +342,14 @@ 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:
+227 -1
View File
@@ -13,6 +13,11 @@ class JSONRPCClient {
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) {
@@ -148,19 +153,202 @@ class ConsoleInterceptor {
}
}
// 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);
}
}
@@ -212,6 +400,20 @@ class FetchClient {
}
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",
@@ -232,10 +434,33 @@ class FetchClient {
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");
@@ -266,7 +491,8 @@ class FetchClient {
document.body.appendChild(newScript);
});
console.log("Document replaced with site content");
// Ensure initial navigation after document is loaded
this.ensureInitialNavigation();
}
showError(message, error) {
+60 -14
View File
@@ -68,23 +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 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;
// 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,
};
@@ -109,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);
});
@@ -134,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>
+71 -15
View File
@@ -8,6 +8,9 @@
"name": "mkstack",
"version": "0.0.0",
"dependencies": {
"@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",
@@ -43,7 +46,6 @@
"@radix-ui/react-toggle-group": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.4",
"@std/encoding": "npm:@jsr/std__encoding@^1.0.10",
"@std/path": "npm:@jsr/std__path@^1.1.1",
"@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
@@ -78,6 +80,7 @@
"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",
@@ -98,6 +101,7 @@
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@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",
@@ -348,6 +352,59 @@
"node": ">=18"
}
},
"node_modules/@dnd-kit/accessibility": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",
"integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==",
"license": "MIT",
"dependencies": {
"tslib": "^2.0.0"
},
"peerDependencies": {
"react": ">=16.8.0"
}
},
"node_modules/@dnd-kit/core": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
"license": "MIT",
"dependencies": {
"@dnd-kit/accessibility": "^3.1.1",
"@dnd-kit/utilities": "^3.2.2",
"tslib": "^2.0.0"
},
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
}
},
"node_modules/@dnd-kit/sortable": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/@dnd-kit/sortable/-/sortable-10.0.0.tgz",
"integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==",
"license": "MIT",
"dependencies": {
"@dnd-kit/utilities": "^3.2.2",
"tslib": "^2.0.0"
},
"peerDependencies": {
"@dnd-kit/core": "^6.3.0",
"react": ">=16.8.0"
}
},
"node_modules/@dnd-kit/utilities": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz",
"integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==",
"license": "MIT",
"dependencies": {
"tslib": "^2.0.0"
},
"peerDependencies": {
"react": ">=16.8.0"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.5.tgz",
@@ -1251,11 +1308,6 @@
"resolved": "https://npm.jsr.io/~/11/@jsr/std__encoding/0.224.3.tgz",
"integrity": "sha512-zAuX2QV1zwJ5RSmrnDGVerAtN3pBXpYYNlGzhERW9AiQ1UJd2/xruyB3i5NdTWy2OK2pjETswOj+0+prYTPlxQ=="
},
"node_modules/@jsr/std__internal": {
"version": "1.0.9",
"resolved": "https://npm.jsr.io/~/11/@jsr/std__internal/1.0.9.tgz",
"integrity": "sha512-s+f4qrJzZgPAy7XuFOtgaSaxyPLnnEmAfXGLvRXGxPTL76URLVHkF+hOzqXz+bmk8/awybF6BRsasxtAQOV23Q=="
},
"node_modules/@mixmark-io/domino": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@mixmark-io/domino/-/domino-2.2.0.tgz",
@@ -3194,15 +3246,6 @@
"resolved": "https://npm.jsr.io/~/11/@jsr/std__encoding/1.0.10.tgz",
"integrity": "sha512-WK2njnDTyKefroRNk2Ooq7GStp6Y0ccAvr4To+Z/zecRAGe7+OSvH9DbiaHpAKwEi2KQbmpWMOYsdNt+TsdmSw=="
},
"node_modules/@std/path": {
"name": "@jsr/std__path",
"version": "1.1.1",
"resolved": "https://npm.jsr.io/~/11/@jsr/std__path/1.1.1.tgz",
"integrity": "sha512-+x5LgcNUSpMzOZIRmFSjqrMTCxHlgXjWzK8ZFr7lwgHfWZxoVXeis3MFQlkR5mN5uQ61Y1P30Li1PU0yx9uluA==",
"dependencies": {
"@jsr/std__internal": "^1.0.9"
}
},
"node_modules/@swc/core": {
"version": "1.11.24",
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.11.24.tgz",
@@ -3808,6 +3851,13 @@
"integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",
"license": "MIT"
},
"node_modules/@types/uri-templates": {
"version": "0.1.34",
"resolved": "https://registry.npmjs.org/@types/uri-templates/-/uri-templates-0.1.34.tgz",
"integrity": "sha512-13v4r/Op3iEO1y6FvEHQjrUNnrNyO67SigdFC9n80sVfsrM2AWJRNYbE1pBs4/p87I7z1J979JGeLAo3rM1L/Q==",
"dev": true,
"license": "MIT"
},
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.31.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.31.1.tgz",
@@ -10586,6 +10636,12 @@
"punycode": "^2.1.0"
}
},
"node_modules/uri-templates": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/uri-templates/-/uri-templates-0.2.0.tgz",
"integrity": "sha512-EWkjYEN0L6KOfEoOH6Wj4ghQqU7eBZMJqRHQnxQAq+dSEzRPClkWjf8557HkWQXF6BrAUoLSAyy9i3RVTliaNg==",
"license": "http://geraintluff.github.io/tv4/LICENSE.txt"
},
"node_modules/use-callback-ref": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.3.tgz",
+7 -2
View File
@@ -6,10 +6,14 @@
"scripts": {
"dev": "npm i --silent && vite",
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
"test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'",
"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": {
"@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",
@@ -45,7 +49,6 @@
"@radix-ui/react-toggle-group": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.4",
"@std/encoding": "npm:@jsr/std__encoding@^1.0.10",
"@std/path": "npm:@jsr/std__path@^1.1.1",
"@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
@@ -80,6 +83,7 @@
"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",
@@ -100,6 +104,7 @@
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@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;
}
};
+261 -234
View File
@@ -1,35 +1,45 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
<!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>
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
<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.
of this license document, but changing it is not allowed.</p>
Preamble
<h4 id="preamble">Preamble</h4>
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
<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>
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>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>
When we speak of free software, we are referring to freedom, not
<p>When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
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.
free programs, and that you know you can do these things.</p>
Developers that use our General Public Licenses protect your rights
<p>Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
and/or modify the software.</p>
A secondary benefit of defending all users' freedom is that
<p>A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
@@ -37,78 +47,79 @@ encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
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.
source code to the public.</p>
The GNU Affero General Public License is designed specifically to
<p>The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
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.
code of the modified version.</p>
An older license, called the Affero General Public License and
<p>An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
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.
this license.</p>
The precise terms and conditions for copying, distribution and
modification follow.
<p>The precise terms and conditions for copying, distribution and
modification follow.</p>
TERMS AND CONDITIONS
<h4 id="terms">TERMS AND CONDITIONS</h4>
0. Definitions.
<h4 id="section0">0. Definitions.</h4>
"This License" refers to version 3 of the GNU Affero General Public License.
<p>"This License" refers to version 3 of the GNU Affero General Public
License.</p>
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
<p>"Copyright" also means copyright-like laws that apply to other kinds
of works, such as semiconductor masks.</p>
"The Program" refers to any copyrightable work licensed under this
<p>"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
"recipients" may be individuals or organizations.</p>
To "modify" a work means to copy from or adapt all or part of the work
<p>To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
earlier work or a work "based on" the earlier work.</p>
A "covered work" means either the unmodified Program or a work based
on the Program.
<p>A "covered work" means either the unmodified Program or a work based
on the Program.</p>
To "propagate" a work means to do anything with it that, without
<p>To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
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.
public, and in some countries other activities as well.</p>
To "convey" a work means any kind of propagation that enables other
<p>To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
a computer network, with no transfer of a copy, is not conveying.</p>
An interactive user interface displays "Appropriate Legal Notices"
<p>An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
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.
menu, a prominent item in the list meets this criterion.</p>
1. Source Code.
<h4 id="section1">1. Source Code.</h4>
The "source code" for a work means the preferred form of the work
<p>The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
form of a work.</p>
A "Standard Interface" means an interface that either is an official
<p>A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
is widely used among developers working in that language.</p>
The "System Libraries" of an executable work include anything, other
<p>The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
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
@@ -117,9 +128,9 @@ implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(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.
produce the work, or an object code interpreter used to run it.</p>
The "Corresponding Source" for a work in object code form means all
<p>The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
@@ -130,26 +141,26 @@ includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
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.
subprograms and other parts of the work.</p>
The Corresponding Source need not include anything that users
<p>The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
Source.</p>
The Corresponding Source for a work in source code form is that
same work.
<p>The Corresponding Source for a work in source code form is that
same work.</p>
2. Basic Permissions.
<h4 id="section2">2. Basic Permissions.</h4>
All rights granted under this License are granted for the term of
<p>All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
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.
rights of fair use or other equivalent, as provided by copyright law.</p>
You may make, run and propagate covered works that you do not
<p>You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
@@ -158,69 +169,73 @@ the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
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.
your copyrighted material outside their relationship with you.</p>
Conveying under any other circumstances is permitted solely under
<p>Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
makes it unnecessary.</p>
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
<h4 id="section3">3. Protecting Users' Legal Rights From Anti-Circumvention Law.</h4>
No covered work shall be deemed part of an effective technological
<p>No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
measures.</p>
When you convey a covered work, you waive any legal power to forbid
<p>When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
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.
technological measures.</p>
4. Conveying Verbatim Copies.
<h4 id="section4">4. Conveying Verbatim Copies.</h4>
You may convey verbatim copies of the Program's source code as you
<p>You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
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.
recipients a copy of this License along with the Program.</p>
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
<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>
5. Conveying Modified Source Versions.
<h4 id="section5">5. Conveying Modified Source Versions.</h4>
You may convey a work based on the Program, or the modifications to
<p>You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
terms of section 4, provided that you also meet all of these conditions:</p>
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
<ul>
b) The work must carry prominent notices stating that it is
<li>a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.</li>
<li>b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
"keep intact all notices".</li>
c) You must license the entire work, as a whole, under this
<li>c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License 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.
invalidate such permission if you have separately received it.</li>
d) If the work has interactive user interfaces, each must display
<li>d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
work need not make them do so.</li>
A compilation of a covered work with other separate and independent
</ul>
<p>A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
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
@@ -228,21 +243,23 @@ in or on a volume of a storage or distribution medium, is called an
used to limit the access or legal rights of the compilation's users
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.
parts of the aggregate.</p>
6. Conveying Non-Source Forms.
<h4 id="section6">6. Conveying Non-Source Forms.</h4>
You may convey a covered work in object code form under the terms
<p>You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
in one of these ways:</p>
a) Convey the object code in, or embodied in, a physical product
<ul>
<li>a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
customarily used for software interchange.</li>
b) Convey the object code in, or embodied in, a physical product
<li>b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
@@ -252,15 +269,15 @@ in one of these ways:
medium customarily used for software interchange, for a price no
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.
Corresponding Source from a network server at no charge.</li>
c) Convey individual copies of the object code with a copy of the
<li>c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
with subsection 6b.</li>
d) Convey the object code by offering access from a designated
<li>d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
@@ -271,18 +288,20 @@ in one of these ways:
clear directions next to the object code saying where to find the
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.
available for as long as needed to satisfy these requirements.</li>
e) Convey the object code using peer-to-peer transmission, provided
<li>e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
charge under subsection 6d.</li>
A separable portion of the object code, whose source code is excluded
</ul>
<p>A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
included in conveying the object code work.</p>
A "User Product" is either (1) a "consumer product", which means any
<p>A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
@@ -293,17 +312,17 @@ of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
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.
the only significant mode of use of the product.</p>
"Installation Information" for a User Product means any methods,
<p>"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
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.
modification has been made.</p>
If you convey an object code work under this section in, or with, or
<p>If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
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
@@ -312,133 +331,137 @@ 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).
been installed in ROM).</p>
The requirement to provide Installation Information does not include a
<p>The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
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.
protocols for communication across the network.</p>
Corresponding Source conveyed, and Installation Information provided,
<p>Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
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.
unpacking, reading or copying.</p>
7. Additional Terms.
<h4 id="section7">7. Additional Terms.</h4>
"Additional permissions" are terms that supplement the terms of this
<p>"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
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.
this License without regard to the additional permissions.</p>
When you convey a copy of a covered work, you may at your option
<p>When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
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.
for which you have or can give appropriate copyright permission.</p>
Notwithstanding any other provision of this License, for material you
<p>Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
that material) supplement the terms of this License with terms:</p>
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
<ul>
b) Requiring preservation of specified reasonable legal notices or
<li>a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or</li>
<li>b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
Notices displayed by works containing it; or</li>
c) Prohibiting misrepresentation of the origin of that material, or
<li>c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
reasonable ways as different from the original version; or</li>
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
<li>d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or</li>
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
<li>e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or</li>
f) Requiring indemnification of licensors and authors of that
<li>f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
those licensors and authors.</li>
All other non-permissive additional terms are considered "further
</ul>
<p>All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
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.
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>
If you add terms to a covered work in accord with this section, you
<p>If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
where to find the applicable terms.</p>
Additional terms, permissive or non-permissive, may be stated in the
<p>Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
the above requirements apply either way.</p>
8. Termination.
<h4 id="section8">8. Termination.</h4>
You may not propagate or modify a covered work except as expressly
<p>You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
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).
paragraph of section 11).</p>
However, if you cease all violation of this License, then your
<p>However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
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.
prior to 60 days after the cessation.</p>
Moreover, your license from a particular copyright holder is
<p>Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
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.
your receipt of the notice.</p>
Termination of your rights under this section does not terminate the
<p>Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
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.
material under section 10.</p>
9. Acceptance Not Required for Having Copies.
<h4 id="section9">9. Acceptance Not Required for Having Copies.</h4>
You are not required to accept this License in order to receive or
<p>You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
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.
covered work, you indicate your acceptance of this License to do so.</p>
10. Automatic Licensing of Downstream Recipients.
<h4 id="section10">10. Automatic Licensing of Downstream Recipients.</h4>
Each time you convey a covered work, the recipient automatically
<p>Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
for enforcing compliance by third parties with this License.</p>
An "entity transaction" is a transaction transferring control of an
<p>An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
@@ -446,23 +469,23 @@ transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
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.
the predecessor has it or can get it with reasonable efforts.</p>
You may not impose any further restrictions on the exercise of the
<p>You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
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.
sale, or importing the Program or any portion of it.</p>
11. Patents.
<h4 id="section11">11. Patents.</h4>
A "contributor" is a copyright holder who authorizes use under this
<p>A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
work thus licensed is called the contributor's "contributor version".</p>
A contributor's "essential patent claims" are all patent claims
<p>A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
@@ -470,21 +493,21 @@ but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
this License.</p>
Each contributor grants you a non-exclusive, worldwide, royalty-free
<p>Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
propagate the contents of its contributor version.</p>
In the following three paragraphs, a "patent license" is any express
<p>In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(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.
patent against the party.</p>
If you convey a covered work, knowingly relying on a patent license,
<p>If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
@@ -496,17 +519,17 @@ license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
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.
country that you have reason to believe are valid.</p>
If, pursuant to or in connection with a single transaction or
<p>If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
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.
work and works based on it.</p>
A patent license is "discriminatory" if it does not include within
<p>A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
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
@@ -519,15 +542,15 @@ patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
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.
or that patent license was granted, prior to 28 March 2007.</p>
Nothing in this License shall be construed as excluding or limiting
<p>Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
otherwise be available to you under applicable patent law.</p>
12. No Surrender of Others' Freedom.
<h4 id="section12">12. No Surrender of Others' Freedom.</h4>
If conditions are imposed on you (whether by court order, agreement or
<p>If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
@@ -535,11 +558,11 @@ License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
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.
License would be to refrain entirely from conveying the Program.</p>
13. Remote Network Interaction; Use with the GNU General Public License.
<h4 id="section13">13. Remote Network Interaction; Use with the GNU General Public License.</h4>
Notwithstanding any other provision of this License, if you modify the
<p>Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
@@ -548,56 +571,56 @@ from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
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.
following paragraph.</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>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>
14. Revised Versions of this License.
<h4 id="section14">14. Revised Versions of this License.</h4>
The Free Software Foundation may publish revised and/or new versions of
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>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>
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>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>
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>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>
Later license versions may give you additional or different
<p>Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
later version.</p>
15. Disclaimer of Warranty.
<h4 id="section15">15. Disclaimer of Warranty.</h4>
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
<p>THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
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.
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.</p>
16. Limitation of Liability.
<h4 id="section16">16. Limitation of Liability.</h4>
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
<p>IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
@@ -605,37 +628,37 @@ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
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.
SUCH DAMAGES.</p>
17. Interpretation of Sections 15 and 16.
<h4 id="section17">17. Interpretation of Sections 15 and 16.</h4>
If the disclaimer of warranty and limitation of liability provided
<p>If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
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.
copy of the Program in return for a fee.</p>
END OF TERMS AND CONDITIONS
<p>END OF TERMS AND CONDITIONS</p>
How to Apply These Terms to Your New Programs
<h4 id="howto">How to Apply These Terms to Your New Programs</h4>
If you develop a new program, and you want it to be of the greatest
<p>If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
free software which everyone can redistribute and change under these terms.</p>
To do so, attach the following notices to the program. It is safest
<p>To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
the "copyright" line and a pointer to where the full notice is found.</p>
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
<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.
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
@@ -643,19 +666,23 @@ the "copyright" line and a pointer to where the full notice is found.
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;.
</pre>
Also add information on how to contact you by electronic and paper mail.
<p>Also add information on how to contact you by electronic and paper mail.</p>
If your software can interact with users remotely through a computer
<p>If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
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.
specific requirements.</p>
You should also get your employer (if you work as a programmer) or school,
<p>You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
&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": "/favicon.png",
"src": "/shakespeare.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/favicon.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

+1 -1
View File
@@ -38,7 +38,7 @@ const queryClient = new QueryClient({
});
const defaultConfig: AppConfig = {
theme: "light",
theme: "system",
relayUrl: "wss://relay.primal.net",
deployServer: "shakespeare.wtf",
};
+1
View File
@@ -11,6 +11,7 @@ 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";
+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

+93 -26
View File
@@ -16,14 +16,12 @@ interface AIMessageItemProps {
message: AIMessage;
isCurrentlyLoading?: boolean;
toolCall?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined; // Tool call data passed from the assistant message
reasoningContent?: string; // Reasoning content for streaming messages
}
export const AIMessageItem = memo(({
message,
isCurrentlyLoading = false,
toolCall,
reasoningContent
}: AIMessageItemProps) => {
const [isToolExpanded, setIsToolExpanded] = useState(false);
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
@@ -186,6 +184,75 @@ export const AIMessageItem = memo(({
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 */}
@@ -202,13 +269,7 @@ export const AIMessageItem = memo(({
</span>
</button>
{isToolExpanded && (
<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>
)}
{isToolExpanded && renderSpecialContent()}
</div>
);
}
@@ -233,16 +294,19 @@ export const AIMessageItem = memo(({
);
}
// 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">
<div className="text-sm space-y-3">
{/* Reasoning content display */}
{((reasoningContent && reasoningContent.trim()) ||
(hasReasoningContent(message) && message.reasoning_content.trim()) ||
(reasoningContent !== undefined && !getContent().trim() && isCurrentlyLoading)) && (
<div className="mb-3">
{hasReasoningContent(message) && message.reasoning_content.trim() && (
<div>
<button
onClick={() => setIsReasoningExpanded(!isReasoningExpanded)}
className={cn(
@@ -250,7 +314,7 @@ export const AIMessageItem = memo(({
"hover:bg-muted/30 rounded transition-colors duration-200"
)}
>
{reasoningContent !== undefined && !getContent().trim() && isCurrentlyLoading ? (
{!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" />
@@ -260,7 +324,7 @@ export const AIMessageItem = memo(({
</span>
</button>
{isReasoningExpanded && (reasoningContent?.trim() || (hasReasoningContent(message) && message.reasoning_content.trim())) && (
{isReasoningExpanded && (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
<div className="whitespace-pre-wrap break-words">
<Streamdown
@@ -268,7 +332,7 @@ export const AIMessageItem = memo(({
parseIncompleteMarkdown={isCurrentlyLoading}
shikiTheme={displayTheme === 'dark' ? 'github-dark' : 'github-light'}
>
{reasoningContent || (hasReasoningContent(message) ? message.reasoning_content : '') || ''}
{message.reasoning_content}
</Streamdown>
</div>
</div>
@@ -276,15 +340,18 @@ export const AIMessageItem = memo(({
</div>
)}
<div className="break-words">
<Streamdown
className='size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0'
parseIncompleteMarkdown={isCurrentlyLoading}
shikiTheme={displayTheme === 'dark' ? 'github-dark' : 'github-light'}
>
{getContent()}
</Streamdown>
</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>
+9 -7
View File
@@ -31,7 +31,7 @@ describe('AISettingsProvider', () => {
// Mock the read function to return default settings
const { readAISettings } = await import('@/lib/configUtils');
vi.mocked(readAISettings).mockResolvedValue({
providers: {},
providers: [],
recentlyUsedModels: [],
});
});
@@ -122,12 +122,13 @@ describe('AISettingsProvider', () => {
it('should migrate old settings without recentlyUsedModels', async () => {
const oldSettings = {
providers: {
openrouter: {
providers: [
{
id: 'openrouter',
baseURL: 'https://openrouter.ai/api/v1',
apiKey: 'test-key'
}
},
],
recentlyUsedModels: []
};
@@ -169,12 +170,13 @@ describe('AISettingsProvider', () => {
act(() => {
result.current.updateSettings({
providers: {
'test-provider': {
providers: [
{
id: 'test-provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key'
}
}
]
});
});
+36 -30
View File
@@ -1,6 +1,6 @@
import { useQueryClient } from '@tanstack/react-query';
import { ReactNode, useState, useEffect } from 'react';
import { AISettingsContext, type AISettings, type AIConnection, 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';
@@ -9,7 +9,7 @@ interface AISettingsProviderProps {
}
const DEFAULT_SETTINGS: AISettings = {
providers: {},
providers: [],
recentlyUsedModels: [],
};
@@ -57,43 +57,49 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
// 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 addProvider = (name: string, connection: AIConnection) => {
setSettings(prev => ({
...prev,
providers: {
...prev.providers,
[name]: connection,
},
}));
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
};
const removeProvider = (name: string) => {
const setProvider = (provider: AIProvider) => {
setSettings(prev => {
const { [name]: removed, ...rest } = prev.providers;
return {
...prev,
providers: rest,
};
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 updateProvider = (name: string, connection: Partial<AIConnection>) => {
const removeProvider = (id: string) => {
setSettings(prev => ({
...prev,
providers: {
...prev.providers,
[name]: {
...prev.providers[name],
...connection,
},
},
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) => {
@@ -120,14 +126,14 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
});
};
const isConfigured = Object.entries(settings.providers).length > 0;
const isConfigured = settings.providers.length > 0;
const contextValue: AISettingsContextType = {
settings,
updateSettings,
addProvider,
setProvider,
removeProvider,
updateProvider,
setProviders,
addRecentlyUsedModel,
isConfigured,
};
+380
View File
@@ -0,0 +1,380 @@
import { useState, useEffect } from 'react';
import { ArrowRight, ArrowLeft, Download, Upload, ExternalLink, Sparkles } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { useAISettings } from '@/hooks/useAISettings';
import { useAICredits } from '@/hooks/useAICredits';
import { useLocalStorage } from '@/hooks/useLocalStorage';
interface Act1DialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
type DialogStep = 'welcome' | 'migration' | 'credits' | 'conclusion';
const SHAKESPEARE_PROVIDER = {
id: "shakespeare",
baseURL: "https://ai.shakespeare.diy/v1",
nostr: true,
};
const MKSTACK_NSP_ADDR = '31999:4bcaa7b5606e3c14df05cd497e588f5d3fe559b4e9a425e8b418a43af1ffb015:mkstack';
export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
const [step, setStep] = useState<DialogStep>('welcome');
const [isSettingUp, setIsSettingUp] = useState(false);
const { setProvider, updateSettings } = useAISettings();
// Get the selectedNSPAddr from localStorage
const [selectedNSPAddr] = useLocalStorage<string | null>('selectedNSPAddr', null);
// Get user's credits
const { data: creditsData } = useAICredits(SHAKESPEARE_PROVIDER);
const handleGetStarted = async () => {
setIsSettingUp(true);
try {
// Add Shakespeare provider to their config
setProvider(SHAKESPEARE_PROVIDER);
// Configure recently used models based on credits or NSP
const hasCredits = creditsData?.amount && creditsData.amount > 0;
const hasMKStackNSP = selectedNSPAddr === MKSTACK_NSP_ADDR;
if (hasCredits || hasMKStackNSP) {
// User has credits or MKStack NSP - set to shakespeare model
updateSettings({ recentlyUsedModels: ['shakespeare/shakespeare'] });
} else {
// No credits - set to tybalt model (free)
updateSettings({ recentlyUsedModels: ['shakespeare/tybalt'] });
}
// Move to migration step
setStep('migration');
} catch (error) {
console.error('Failed to configure Shakespeare provider:', error);
} finally {
setIsSettingUp(false);
}
};
const handleContinue = () => {
setStep('credits');
};
const handleCreditsNext = () => {
setStep('conclusion');
};
const handleFinish = () => {
// Mark that the user is a previous Act 1 user
localStorage.setItem('act1', 'true');
// Remove the selectedNSPAddr from localStorage
localStorage.removeItem('selectedNSPAddr');
onOpenChange(false);
};
const handleVisitAct1 = () => {
window.open('https://act1.shakespeare.diy', '_blank');
};
// Reset state when dialog opens/closes
useEffect(() => {
if (open) {
setStep('welcome');
setIsSettingUp(false);
}
}, [open]);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-hidden">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
{step === 'migration' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('welcome')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{step === 'credits' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('migration')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{step === 'conclusion' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('credits')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
<span className="text-xl">
{step === 'welcome' && 'Welcome to Shakespeare: Act 2! 🎭'}
{step === 'migration' && 'Migrating Your Projects'}
{step === 'credits' && 'Your Credits'}
{step === 'conclusion' && "You're All Set!"}
</span>
</DialogTitle>
</DialogHeader>
<div className="overflow-y-auto max-h-[calc(90vh-120px)] pr-2">
<div className="space-y-6 py-4">
{step === 'welcome' && (
<div className="text-center space-y-6">
<div className="text-6xl mb-4">🎭✨</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Welcome to Act 2!
</h2>
<p className="text-lg text-muted-foreground max-w-lg mx-auto">
We're excited to see you again! Shakespeare has been completely rebuilt
with new features, improved performance, and a better development experience.
</p>
</div>
<Card className="max-w-lg mx-auto text-left">
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<span className="text-2xl">🔄</span>
What's Changed
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="flex items-start gap-3">
<Badge variant="secondary" className="mt-0.5">New</Badge>
<div>
<p className="font-medium">Use any AI Provider</p>
<p className="text-sm text-muted-foreground">Your browser connects to AI providers directly</p>
</div>
</div>
<div className="flex items-start gap-3">
<Badge variant="secondary" className="mt-0.5">New</Badge>
<div>
<p className="font-medium">Git Integration</p>
<p className="text-sm text-muted-foreground">Push to GitHub, Nostr relays, and more</p>
</div>
</div>
<div className="flex items-start gap-3">
<Badge variant="secondary" className="mt-0.5">New</Badge>
<div>
<p className="font-medium">Your Files</p>
<p className="text-sm text-muted-foreground">Files are stored on your device directly in your browser</p>
</div>
</div>
</CardContent>
</Card>
<div className="bg-amber-50 dark:bg-amber-950/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4 max-w-lg mx-auto">
<div className="flex items-start gap-3">
<span className="text-amber-600 dark:text-amber-400 text-lg">⚠️</span>
<div className="text-left">
<p className="font-medium text-amber-800 dark:text-amber-200">Act 2 is in Development</p>
<p className="text-sm text-amber-700 dark:text-amber-300">
While we're working hard to make Act 2 stable, you may encounter bugs.
Your Act 1 projects remain safe and accessible.
</p>
</div>
</div>
</div>
<Button
onClick={handleGetStarted}
disabled={isSettingUp}
size="lg"
className="gap-2"
>
{isSettingUp ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white" />
Setting up...
</>
) : (
<>
<Sparkles className="h-4 w-4" />
Configure Act 2
</>
)}
</Button>
</div>
)}
{step === 'migration' && (
<div className="space-y-6">
<div className="text-center space-y-3">
<h2 className="text-xl font-bold">Your Act 1 Projects & Credits</h2>
<p className="text-muted-foreground max-w-lg mx-auto">
All your Act 1 projects and credits are safe and still accessible.
Here's how to work with them in Act 2.
</p>
</div>
<div className="text-center">
<Button
variant="outline"
onClick={handleVisitAct1}
className="gap-2"
>
<ExternalLink className="h-4 w-4" />
Visit Act 1
</Button>
</div>
<div className="grid gap-4">
<Card>
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<Download className="h-5 w-5 text-green-500" />
Export from Act 1
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-sm text-muted-foreground">
In Act 1, you can export your projects as ZIP files using the project menu.
</p>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<Upload className="h-5 w-5 text-purple-500" />
Import to Act 2
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-sm text-muted-foreground">
In Act 2, use the "Import Project" option in the sidebar to upload your exported ZIP files.
</p>
</CardContent>
</Card>
</div>
<div className="flex justify-end pt-4">
<Button
onClick={handleContinue}
className="gap-2"
>
Continue
<ArrowRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
{step === 'credits' && (
<div className="text-center space-y-6">
<div className="text-6xl mb-4">💳</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold">Your Credits</h2>
<p className="text-lg text-muted-foreground max-w-md mx-auto">
Your Act 1 credits are still available through the Shakespeare AI provider.
</p>
</div>
<Card className="max-w-md mx-auto">
<CardContent className="pt-6">
{creditsData?.amount && creditsData.amount > 0 ? (
<div className="text-center space-y-4">
<div className="space-y-2">
<div className="text-3xl font-bold text-green-600 dark:text-green-400">
${creditsData.amount.toFixed(2)}
</div>
<p className="text-sm text-muted-foreground">
Available credits
</p>
</div>
<div className="bg-green-50 dark:bg-green-950/20 border border-green-200 dark:border-green-800 rounded-lg p-3">
<p className="text-sm text-green-800 dark:text-green-200">
✅ You're all set! We've configured the premium Shakespeare model for you.
</p>
</div>
</div>
) : (
<div className="text-center space-y-4">
<div className="space-y-2">
<div className="text-2xl">🆓</div>
<p className="font-medium">Free Access</p>
</div>
<div className="bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800 rounded-lg p-3">
<p className="text-sm text-blue-800 dark:text-blue-200">
You can continue using Shakespeare for free with the Tybalt model.
It's perfect for learning and building amazing projects!
</p>
</div>
</div>
)}
</CardContent>
</Card>
<div className="flex justify-end pt-4">
<Button
onClick={handleCreditsNext}
className="gap-2"
>
Continue
<ArrowRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
{step === 'conclusion' && (
<div className="text-center space-y-6">
<div className="text-5xl mb-4">🎉</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold">Welcome to the Future!</h2>
<p className="text-lg text-muted-foreground max-w-md mx-auto">
You're all set up with Act 2! Your AI assistant is configured
and ready to help you build amazing Nostr applications.
</p>
</div>
<div className="bg-muted/50 rounded-lg p-4 max-w-md mx-auto">
<p className="text-sm text-muted-foreground italic">
"Create a decentralized social media app with custom feeds and real-time messaging..."
</p>
</div>
<div className="space-y-3">
<Button onClick={handleFinish} size="lg" className="gap-2">
<Sparkles className="h-4 w-4" />
Start Building in Act 2
</Button>
<div className="text-xs text-muted-foreground">
Remember: You can always access Act 1 at{' '}
<button
onClick={handleVisitAct1}
className="text-primary hover:underline"
>
act1.shakespeare.diy
</button>
</div>
</div>
</div>
)}
</div>
</div>
</DialogContent>
</Dialog>
);
}
+23 -253
View File
@@ -4,193 +4,45 @@ import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import {
GitBranch,
MoreHorizontal,
MessageSquarePlus,
Play,
CloudUpload,
Loader2,
GitBranch,
Download,
Trash2,
Settings,
GitMerge,
History,
Folder,
} from 'lucide-react';
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
import { GitDialog } from '@/components/GitDialog';
import { AppSettingsDialog } from '@/components/AppSettingsDialog';
import { useNavigate } from 'react-router-dom';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useToast } from '@/hooks/useToast';
import { useGit } from '@/hooks/useGit';
import { useFS } from '@/hooks/useFS';
import JSZip from 'jszip';
interface ActionsMenuProps {
projectId: string;
projectName: string;
onNewChat: () => void;
onBuild: () => void;
onDeploy: () => void;
onProjectDetails?: () => void;
isLoading?: boolean;
isBuildLoading?: boolean;
isDeployLoading?: boolean;
disabled?: boolean;
onFirstInteraction?: () => void;
onProjectDeleted?: () => void;
}
export function ActionsMenu({
projectId,
projectName,
projectName: _projectName,
onNewChat,
onBuild,
onDeploy,
onProjectDetails,
isLoading = false,
isBuildLoading = false,
isDeployLoading = false,
disabled = false,
onFirstInteraction,
onProjectDeleted
onFirstInteraction: _onFirstInteraction,
}: ActionsMenuProps) {
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
const [gitDialogOpen, setGitDialogOpen] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const [isExporting, setIsExporting] = useState(false);
const navigate = useNavigate();
const projectsManager = useProjectsManager();
const { toast } = useToast();
const git = useGit();
const { fs } = useFS();
const isAnyLoading = isLoading || isBuildLoading;
const isAnyLoading = isLoading || isBuildLoading || isDeployLoading || isDeleting || isExporting;
const handleDeleteProject = async () => {
setIsDeleting(true);
try {
await projectsManager.deleteProject(projectId);
toast({
title: "Project deleted",
description: `"${projectName}" has been permanently deleted.`,
});
// 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/${projectId}`;
// 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 = `${projectName}.zip`;
try {
// Get the current commit hash
const commits = await git.log({
dir: projectPath,
depth: 1,
});
if (commits.length > 0) {
const commitHash = commits[0].oid.substring(0, 7); // Truncate to 7 characters
filename = `${projectName}-${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: `"${projectName}" 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 (
<>
@@ -216,118 +68,34 @@ export function ActionsMenu({
New Chat
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setGitDialogOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<GitMerge className="h-4 w-4" />
Git Status
</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" />
Git History
</DropdownMenuItem>
<AppSettingsDialog>
<DropdownMenuItem
disabled={isAnyLoading}
className="gap-2"
onSelect={(e) => e.preventDefault()}
>
<Settings className="h-4 w-4" />
Settings
</DropdownMenuItem>
</AppSettingsDialog>
<DropdownMenuItem
onClick={handleExportProject}
disabled={isAnyLoading}
className="gap-2"
>
{isExporting ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Download className="h-4 w-4" />
)}
{isExporting ? 'Exporting...' : 'Export Project'}
Repository
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
if (onFirstInteraction) onFirstInteraction();
onBuild();
}}
onClick={onProjectDetails}
disabled={isAnyLoading}
className="gap-2"
>
{isBuildLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Play className="h-4 w-4" />
)}
{isBuildLoading ? 'Building...' : 'Build'}
<Folder className="h-4 w-4" />
Project Details
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
if (onFirstInteraction) onFirstInteraction();
onDeploy();
}}
disabled={isAnyLoading}
className="gap-2"
>
{isDeployLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<CloudUpload className="h-4 w-4" />
)}
{isDeployLoading ? 'Deploying...' : 'Deploy'}
</DropdownMenuItem>
<DropdownMenuSeparator />
<AlertDialog>
<AlertDialogTrigger asChild>
<DropdownMenuItem
className="text-destructive focus:text-destructive cursor-pointer gap-2"
onSelect={(e) => e.preventDefault()}
>
<Trash2 className="h-4 w-4" />
Delete Project
</DropdownMenuItem>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Project</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete "{projectName}"? 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>
</DropdownMenuContent>
</DropdownMenu>
@@ -343,6 +111,8 @@ export function ActionsMenu({
open={gitHistoryOpen}
onOpenChange={setGitHistoryOpen}
/>
</>
);
}
-4
View File
@@ -18,7 +18,6 @@ interface AppLayoutProps {
export function AppLayout({
children,
selectedProject = null,
title = "Shakespeare",
showSidebar = true,
headerContent
}: AppLayoutProps) {
@@ -85,9 +84,6 @@ export function AppLayout({
<Menu className="h-4 w-4" />
</Button>
)}
<h1 className="text-lg font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
{title}
</h1>
</div>
{headerContent}
</header>
-108
View File
@@ -1,108 +0,0 @@
import { useState } from 'react';
import { Settings, Save } 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 { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { useAppContext } from '@/hooks/useAppContext';
import { useToast } from '@/hooks/useToast';
interface AppSettingsDialogProps {
children?: React.ReactNode;
}
export function AppSettingsDialog({ children }: AppSettingsDialogProps) {
const { config, updateConfig } = useAppContext();
const { toast } = useToast();
const [open, setOpen] = useState(false);
const [deployServer, setDeployServer] = useState(config.deployServer);
const handleSave = () => {
// Validate deploy server
if (!deployServer.trim()) {
toast({
title: "Invalid deploy server",
description: "Deploy server cannot be empty.",
variant: "destructive",
});
return;
}
// Remove protocol if present
const cleanDeployServer = deployServer.replace(/^https?:\/\//, '');
updateConfig((current) => ({
...current,
deployServer: cleanDeployServer,
}));
toast({
title: "Settings saved",
description: "Your deployment settings have been updated.",
});
setOpen(false);
};
const handleCancel = () => {
// Reset to current config
setDeployServer(config.deployServer);
setOpen(false);
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
{children || (
<Button variant="outline" size="sm">
<Settings className="h-4 w-4 mr-2" />
Settings
</Button>
)}
</DialogTrigger>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle>App Settings</DialogTitle>
<DialogDescription>
Configure your application preferences and deployment settings.
</DialogDescription>
</DialogHeader>
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="text-lg">Deployment</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="deployServer">Deploy Server</Label>
<Input
id="deployServer"
value={deployServer}
onChange={(e) => setDeployServer(e.target.value)}
placeholder="shakespeare.wtf"
className="font-mono"
/>
<p className="text-xs text-muted-foreground">
Your projects will be deployed to subdomains of this server.
Example: yourproject.{deployServer || 'shakespeare.wtf'}
</p>
</div>
</CardContent>
</Card>
</div>
<div className="flex justify-end space-x-2">
<Button variant="outline" onClick={handleCancel}>
Cancel
</Button>
<Button onClick={handleSave}>
<Save className="h-4 w-4 mr-2" />
Save Settings
</Button>
</div>
</DialogContent>
</Dialog>
);
}
+6 -16
View File
@@ -2,7 +2,6 @@ import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { CreditsBadge } from './CreditsBadge';
import type { AIConnection } from '@/contexts/AISettingsContext';
// Mock the useAICredits hook
vi.mock('@/hooks/useAICredits', () => ({
@@ -16,7 +15,8 @@ vi.mock('@/hooks/useAICredits', () => ({
// Mock the fetch function
global.fetch = vi.fn();
const mockConnection: AIConnection = {
const mockProvider = {
id: 'test-provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
};
@@ -25,10 +25,7 @@ describe('CreditsBadge', () => {
it('renders the credits amount', () => {
render(
<TestApp>
<CreditsBadge
providerId="test-provider"
connection={mockConnection}
/>
<CreditsBadge provider={mockProvider} />
</TestApp>
);
@@ -41,8 +38,7 @@ describe('CreditsBadge', () => {
render(
<TestApp>
<CreditsBadge
providerId="test-provider"
connection={mockConnection}
provider={mockProvider}
onOpenDialog={mockCallback}
/>
</TestApp>
@@ -57,10 +53,7 @@ describe('CreditsBadge', () => {
it('has proper styling for clickable badge', () => {
render(
<TestApp>
<CreditsBadge
providerId="test-provider"
connection={mockConnection}
/>
<CreditsBadge provider={mockProvider} />
</TestApp>
);
@@ -72,10 +65,7 @@ describe('CreditsBadge', () => {
it('does not render dialog directly', () => {
render(
<TestApp>
<CreditsBadge
providerId="test-provider"
connection={mockConnection}
/>
<CreditsBadge provider={mockProvider} />
</TestApp>
);
+4 -5
View File
@@ -1,10 +1,9 @@
import { Badge } from '@/components/ui/badge';
import { AIProvider } from '@/contexts/AISettingsContext';
import { useAICredits } from '@/hooks/useAICredits';
import type { AIConnection } from '@/contexts/AISettingsContext';
interface CreditsBadgeProps {
providerId: string;
connection: AIConnection;
provider: AIProvider;
className?: string;
onOpenDialog?: () => void;
}
@@ -12,8 +11,8 @@ interface CreditsBadgeProps {
/**
* Displays a clickable credits badge showing the remaining credits for an AI provider
*/
export function CreditsBadge({ providerId, connection, className, onOpenDialog }: CreditsBadgeProps) {
const { data: credits, isLoading, error } = useAICredits(providerId, connection);
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) {
+10 -27
View File
@@ -2,14 +2,16 @@ import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { CreditsDialog } from './CreditsDialog';
import type { AIConnection } from '@/contexts/AISettingsContext';
import type { AIProvider } from '@/contexts/AISettingsContext';
// Mock the fetch function
global.fetch = vi.fn();
const mockConnection: AIConnection = {
const mockProvider: AIProvider = {
id: 'test-provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
nostr: false,
};
describe('CreditsDialog', () => {
@@ -19,8 +21,7 @@ describe('CreditsDialog', () => {
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
provider={mockProvider}
/>
</TestApp>
);
@@ -36,8 +37,7 @@ describe('CreditsDialog', () => {
<CreditsDialog
open={false}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
provider={mockProvider}
/>
</TestApp>
);
@@ -51,8 +51,7 @@ describe('CreditsDialog', () => {
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
provider={mockProvider}
/>
</TestApp>
);
@@ -67,8 +66,7 @@ describe('CreditsDialog', () => {
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
provider={mockProvider}
/>
</TestApp>
);
@@ -80,20 +78,7 @@ describe('CreditsDialog', () => {
expect(screen.getByText('$100')).toBeInTheDocument();
});
it('shows login requirement when user is not logged in', () => {
render(
<TestApp>
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
/>
</TestApp>
);
expect(screen.getByText('Please log in to purchase credits')).toBeInTheDocument();
});
it('calls onDialogStateChange callback when dialog state changes', () => {
const mockCallback = vi.fn();
@@ -102,8 +87,7 @@ describe('CreditsDialog', () => {
<CreditsDialog
open={false}
onOpenChange={mockCallback}
providerId="test-provider"
connection={mockConnection}
provider={mockProvider}
/>
</TestApp>
);
@@ -114,8 +98,7 @@ describe('CreditsDialog', () => {
<CreditsDialog
open={true}
onOpenChange={mockCallback}
providerId="test-provider"
connection={mockConnection}
provider={mockProvider}
/>
</TestApp>
);
+21 -41
View File
@@ -13,13 +13,12 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
import { useToast } from '@/hooks/useToast';
import { createAIClient } from '@/lib/ai-client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import type { AIConnection } from '@/contexts/AISettingsContext';
import { AIProvider } from '@/contexts/AISettingsContext';
interface CreditsDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
providerId: string;
connection: AIConnection;
provider: AIProvider;
}
interface Payment {
@@ -182,7 +181,7 @@ function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) {
);
}
export function CreditsDialog({ open, onOpenChange, providerId, connection }: CreditsDialogProps) {
export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogProps) {
const { user } = useCurrentUser();
const { toast } = useToast();
const queryClient = useQueryClient();
@@ -194,13 +193,13 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
// Query for payment history
const { data: payments, isLoading: isLoadingPayments } = useQuery({
queryKey: ['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId],
queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
queryFn: async (): Promise<Payment[]> => {
const ai = createAIClient(connection, user);
const ai = createAIClient(provider, user);
const data = await ai.get('/credits/payments?limit=50') as PaymentsResponse;
return data.data;
},
enabled: open && !!user,
enabled: open,
retry: false,
refetchOnWindowFocus: false,
});
@@ -208,7 +207,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
// Mutation for adding credits
const addCreditsMutation = useMutation({
mutationFn: async (request: AddCreditsRequest): Promise<Payment> => {
const ai = createAIClient(connection, user);
const ai = createAIClient(provider, user);
return await ai.post('/credits/add', {
body: request,
}) as Payment;
@@ -228,12 +227,12 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
// Refresh payments list
queryClient.invalidateQueries({
queryKey: ['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId],
queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
});
// Refresh credits balance
queryClient.invalidateQueries({
queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId],
queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
});
},
onError: (error: Error) => {
@@ -249,7 +248,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
// Mutation for checking payment status
const checkPaymentMutation = useMutation({
mutationFn: async (paymentId: string): Promise<Payment> => {
const ai = createAIClient(connection, user);
const ai = createAIClient(provider, user);
return await ai.get(`/credits/payments/${paymentId}`) as Payment;
},
onMutate: async (paymentId: string) => {
@@ -266,7 +265,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
// Update the specific payment in the cache instead of refetching
queryClient.setQueryData<Payment[]>(
['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId],
['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
(oldPayments) => {
if (!oldPayments) return oldPayments;
return oldPayments.map(payment =>
@@ -278,7 +277,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
// If payment completed, refresh credits balance
if (updatedPayment.status === 'completed') {
queryClient.invalidateQueries({
queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId],
queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
});
toast({
title: 'Payment completed!',
@@ -316,15 +315,6 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
});
const handleAddCredits = () => {
if (!user) {
toast({
title: 'Authentication required',
description: 'Please log in to purchase credits.',
variant: 'destructive',
});
return;
}
if (amount <= 0) {
toast({
title: 'Invalid amount',
@@ -409,7 +399,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-full max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none">
<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 ? (
@@ -498,7 +488,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
<Button
onClick={handleAddCredits}
disabled={!user || amount <= 0 || addCreditsMutation.isPending}
disabled={amount <= 0 || addCreditsMutation.isPending}
className="w-full h-12 text-base font-medium"
size="lg"
>
@@ -506,12 +496,6 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
{paymentMethod === 'stripe' ? 'Pay with Card' : 'Generate Invoice'}
{amount > 0 && ` - ${formatCurrency(amount)}`}
</Button>
{!user && (
<p className="text-sm text-muted-foreground text-center px-4">
Please log in to purchase credits
</p>
)}
</div>
<div className="flex-shrink-0 px-1 -mx-1 py-4">
@@ -525,17 +509,13 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
</div>
<div className="flex-1 min-h-0 overflow-y-auto">
{isLoadingPayments ? (
<div className="space-y-3">
{Array.from({ length: 3 }).map((_, i) => (
<div key={i} className="p-3 border rounded-lg space-y-2">
<div className="flex items-center gap-2">
<Skeleton className="h-4 w-4 rounded" />
<Skeleton className="h-4 w-24" />
<Skeleton className="h-4 w-16 ml-auto" />
</div>
<Skeleton className="h-3 w-32" />
</div>
))}
<div 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">
+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>
);
}
+52 -20
View File
@@ -43,17 +43,10 @@ vi.mock('@/hooks/useToast', () => ({
})),
}));
const mockUseGitSettings = vi.fn();
vi.mock('@/hooks/useGitSettings', () => ({
useGitSettings: vi.fn(() => ({
settings: {
credentials: {
'https://github.com': {
username: 'git',
password: 'github-token',
},
},
},
})),
useGitSettings: () => mockUseGitSettings(),
}));
describe('GitDialog', () => {
@@ -62,9 +55,20 @@ describe('GitDialog', () => {
data: baseGitStatus,
refetch: mockRefetch,
});
mockUseGitSettings.mockReturnValue({
settings: {
credentials: {
'https://github.com': {
username: 'git',
password: 'github-token',
},
},
},
});
});
it('renders git repository information', () => {
it('renders git dialog without repository information section', () => {
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
@@ -73,11 +77,9 @@ describe('GitDialog', () => {
</TestApp>
);
expect(screen.getByText('Git Repository Status')).toBeInTheDocument();
expect(screen.getByText('Repository Information')).toBeInTheDocument();
expect(screen.getByText('main')).toBeInTheDocument();
expect(screen.getByText('5')).toBeInTheDocument();
expect(screen.getAllByText('origin')).toHaveLength(2); // Appears in remotes and credentials sections
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', () => {
@@ -145,7 +147,7 @@ describe('GitDialog', () => {
expect(pushButton.closest('button')).toBeDisabled();
});
it('shows configured credentials status', () => {
it('does not show credentials warning when credentials are configured', () => {
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
@@ -154,8 +156,38 @@ describe('GitDialog', () => {
</TestApp>
);
expect(screen.getByText('Authentication')).toBeInTheDocument();
expect(screen.getByText('github.com')).toBeInTheDocument();
expect(screen.getByText('Configured')).toBeInTheDocument();
// 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
});
});
+454 -203
View File
@@ -1,10 +1,9 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useState, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
@@ -19,6 +18,8 @@ import {
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,
@@ -31,16 +32,22 @@ import {
Plus,
Minus,
Edit,
RefreshCw,
Settings,
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, getOriginDisplayName } from '@/lib/gitCredentials';
import { findCredentialsForRepo } from '@/lib/gitCredentials';
import { nip19 } from 'nostr-tools';
const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev"];
interface GitDialogProps {
projectId: string;
@@ -52,25 +59,288 @@ interface GitDialogProps {
export function GitDialog({ projectId, children, open, onOpenChange }: GitDialogProps) {
const [isPushing, setIsPushing] = useState(false);
const [isPulling, setIsPulling] = useState(false);
const [pushResult, setPushResult] = useState<string | null>(null);
const [pullResult, setPullResult] = useState<string | null>(null);
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 { git } = useGit();
const { toast } = useToast();
const { user } = useCurrentUser();
const { nostr } = useNostr();
const { mutateAsync: publishEvent } = useNostrPublish();
const projectPath = `/projects/${projectId}`;
// Get credentials for the current repository
const getCredentialsForCurrentRepo = () => {
if (!gitStatus?.remotes.length) return null;
const remoteUrl = gitStatus.remotes[0].url; // Use first remote (usually 'origin')
return findCredentialsForRepo(remoteUrl, settings.credentials);
// 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 currentCredentials = getCredentialsForCurrentRepo();
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) {
@@ -101,27 +371,19 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
}
setIsPushing(true);
setPushResult(null);
try {
const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin')
// Prepare authentication if credentials are available
const authOptions = currentCredentials ? {
onAuth: () => ({
username: currentCredentials.username,
password: currentCredentials.password
}),
} : {};
await git.push({
dir: projectPath,
remote: remote.name,
ref: gitStatus.currentBranch,
...authOptions,
onAuth: (url) => findCredentialsForRepo(url, settings.credentials),
signer: user?.signer, // For signing if pushing to Nostr
});
setPushResult(`✅ Successfully pushed ${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} to ${remote.name}/${gitStatus.currentBranch}`);
toast({
title: "Push successful",
description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`,
@@ -131,11 +393,11 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
await refetchGitStatus();
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
setPushResult(`❌ Push failed: ${errorMessage}`);
toast({
title: "Push failed",
description: errorMessage,
variant: "destructive",
duration: Infinity,
});
} finally {
setIsPushing(false);
@@ -162,18 +424,15 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
}
setIsPulling(true);
setPullResult(null);
try {
const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin')
// Prepare authentication if credentials are available
const authOptions = currentCredentials ? {
onAuth: () => ({
username: currentCredentials.username,
password: currentCredentials.password
}),
} : {};
// Get the current HEAD commit before pulling
const beforeCommit = await git.resolveRef({
dir: projectPath,
ref: 'HEAD',
});
await git.pull({
dir: projectPath,
@@ -183,35 +442,48 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
name: 'shakespeare.diy',
email: '[email protected]',
},
...authOptions,
onAuth: (url) => findCredentialsForRepo(url, settings.credentials),
});
setPullResult(`✅ Successfully pulled from ${remote.name}/${gitStatus.currentBranch}`);
// 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: `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}`,
description: repoChanged
? `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}`
: `Already up to date with ${remote.name}/${gitStatus.currentBranch}`,
});
// Refresh git status after pull
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';
setPullResult(`❌ Pull failed: ${errorMessage}`);
toast({
title: "Pull failed",
description: errorMessage,
variant: "destructive",
duration: Infinity,
});
} finally {
setIsPulling(false);
}
};
const handleRefresh = async () => {
await refetchGitStatus();
setPushResult(null);
setPullResult(null);
};
const getFileStatusIcon = (status: string) => {
switch (status) {
@@ -281,158 +553,131 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
return (
<Dialog open={open} onOpenChange={onOpenChange}>
{children && <DialogTrigger asChild>{children}</DialogTrigger>}
<DialogContent className="max-w-2xl max-h-[80vh]">
<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" />
Git Repository Status
Repository
</DialogTitle>
<DialogDescription>
View repository status and sync with remote repositories
</DialogDescription>
</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">
{/* Repository Info */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm flex items-center justify-between">
Repository Information
<Button
variant="ghost"
size="sm"
onClick={handleRefresh}
className="h-7 w-7 p-0"
>
<RefreshCw className="h-3 w-3" />
</Button>
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{gitStatus?.isGitRepo ? (
<>
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">Current Branch:</span>
<Badge variant="outline" className="font-mono">
{gitStatus.currentBranch || 'unknown'}
</Badge>
</div>
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">Total Commits:</span>
<Badge variant="secondary">{gitStatus.totalCommits}</Badge>
</div>
{gitStatus.latestCommit && (
<div className="space-y-2">
<span className="text-sm text-muted-foreground">Latest Commit:</span>
<div className="bg-muted/50 rounded-md p-2 space-y-1">
<div className="font-mono text-xs text-muted-foreground">
{gitStatus.latestCommit.oid.substring(0, 7)}
</div>
<div className="text-sm">{gitStatus.latestCommit.message}</div>
<div className="text-xs text-muted-foreground flex items-center gap-1">
<Clock className="h-3 w-3" />
{new Date(gitStatus.latestCommit.author.timestamp * 1000).toLocaleString()}
</div>
</div>
</div>
)}
{gitStatus.remotes.length > 0 && (
<div className="space-y-2">
<span className="text-sm text-muted-foreground">Remotes:</span>
{gitStatus.remotes.map((remote) => (
<div key={remote.name} className="bg-muted/50 rounded-md p-2">
<div className="flex items-center justify-between">
<Badge variant="outline">{remote.name}</Badge>
<span className="font-mono text-xs text-muted-foreground truncate ml-2">
{remote.url}
</span>
</div>
</div>
))}
</div>
)}
</>
) : (
<div className="text-center py-4 text-muted-foreground">
<AlertCircle className="h-8 w-8 mx-auto mb-2" />
<p>Not a Git repository</p>
</div>
)}
</CardContent>
</Card>
{/* Credentials Status */}
{gitStatus?.isGitRepo && gitStatus.remotes.length > 0 && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm flex items-center justify-between">
Authentication
<Button
variant="ghost"
size="sm"
onClick={() => navigate('/settings/git')}
className="h-7 gap-1 text-xs"
>
<Settings className="h-3 w-3" />
Settings
</Button>
</CardTitle>
<CardDescription>
Credentials for push/pull operations
</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
{gitStatus.remotes.map((remote) => {
const credentials = findCredentialsForRepo(remote.url, settings.credentials);
const originDisplayName = getOriginDisplayName(remote.url);
return (
<div key={remote.name} className="space-y-2">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Badge variant="outline">{remote.name}</Badge>
<span className="text-sm text-muted-foreground">
{originDisplayName}
</span>
</div>
{credentials ? (
<div className="flex items-center gap-1 text-green-600">
<CheckCircle className="h-3 w-3" />
<span className="text-xs">Configured</span>
</div>
) : (
<div className="flex items-center gap-1 text-amber-600">
<AlertTriangle className="h-3 w-3" />
<span className="text-xs">No credentials</span>
</div>
)}
</div>
{!credentials && (
<Alert className="border-amber-200 bg-amber-50">
<AlertTriangle className="h-4 w-4" />
<AlertDescription className="text-sm">
No credentials configured for {originDisplayName}.
Push/pull operations may fail for private repositories.{' '}
<button
onClick={() => navigate('/settings/git')}
className="underline hover:no-underline font-medium"
>
Configure credentials
</button>
</AlertDescription>
</Alert>
)}
</div>
);
})}
</CardContent>
</Card>
)}
{/* Sync Status */}
{gitStatus?.isGitRepo && (
@@ -452,7 +697,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
<div className="flex gap-2">
<Button
onClick={handlePull}
disabled={isPulling || isPushing}
disabled={isPulling || isPushing || isPushingToNostr}
variant="outline"
size="sm"
className="flex-1"
@@ -467,7 +712,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
<Button
onClick={handlePush}
disabled={isPushing || isPulling || gitStatus.ahead === 0}
disabled={isPushing || isPulling || isPushingToNostr || gitStatus.ahead === 0}
variant="outline"
size="sm"
className="flex-1"
@@ -482,21 +727,27 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
</div>
)}
{/* Operation Results */}
{(pushResult || pullResult) && (
<div className="mt-3 space-y-2">
{pushResult && (
<div className="text-xs font-mono bg-muted/50 rounded p-2">
{pushResult}
</div>
)}
{pullResult && (
<div className="text-xs font-mono bg-muted/50 rounded p-2">
{pullResult}
</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>
)}
+3 -3
View File
@@ -179,7 +179,7 @@ describe('GitSettingsProvider', () => {
password: 'test-token',
}
},
corsProxy: 'https://cors.isomorphic-git.org'
corsProxy: 'https://proxy.shakespeare.diy/?url={href}'
})
);
});
@@ -220,7 +220,7 @@ describe('GitSettingsProvider', () => {
);
await waitFor(() => {
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://cors.isomorphic-git.org');
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://proxy.shakespeare.diy/?url={href}');
});
});
@@ -232,7 +232,7 @@ describe('GitSettingsProvider', () => {
);
await waitFor(() => {
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://cors.isomorphic-git.org');
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://proxy.shakespeare.diy/?url={href}');
});
fireEvent.click(screen.getByText('Update CORS Proxy'));
+5 -1
View File
@@ -9,7 +9,7 @@ interface GitSettingsProviderProps {
const DEFAULT_SETTINGS: GitSettings = {
credentials: {},
corsProxy: 'https://cors.isomorphic-git.org',
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
};
export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
@@ -22,6 +22,10 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
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);
+18
View File
@@ -47,6 +47,24 @@ export function LanguagePicker({ className }: LanguagePickerProps) {
{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>
);
+7 -7
View File
@@ -1,6 +1,7 @@
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', () => ({
@@ -18,9 +19,11 @@ const mockWebLN = {
// We need to import the component after mocking
const { CreditsDialog } = await import('./CreditsDialog');
const mockConnection = {
const mockProvider: AIProvider = {
id: 'test-provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
nostr: false,
};
describe('Lightning Payment', () => {
@@ -39,8 +42,7 @@ describe('Lightning Payment', () => {
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
provider={mockProvider}
/>
</TestApp>
);
@@ -61,8 +63,7 @@ describe('Lightning Payment', () => {
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
provider={mockProvider}
/>
</TestApp>
);
@@ -77,8 +78,7 @@ describe('Lightning Payment', () => {
<CreditsDialog
open={true}
onOpenChange={() => {}}
providerId="test-provider"
connection={mockConnection}
provider={mockProvider}
/>
</TestApp>
);
+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();
});
});
+78 -45
View File
@@ -17,6 +17,8 @@ interface ModelSelectorProps {
className?: string;
disabled?: boolean;
placeholder?: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
export function ModelSelector({
@@ -25,9 +27,16 @@ export function ModelSelector({
className,
disabled = false,
placeholder,
open: controlledOpen,
onOpenChange: setControlledOpen,
}: ModelSelectorProps) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
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();
@@ -50,6 +59,29 @@ export function ModelSelector({
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
@@ -117,51 +149,29 @@ export function ModelSelector({
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>
<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 && <CommandInput placeholder={t('searchModels')} className="h-9" />}
{(isConfigured && models.length >= 5) && (
<CommandInput placeholder={t('searchModels')} className="h-9" />
)}
<CommandList className="max-h-[300px]">
{/* Custom model option and manage providers */}
<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>
<CommandSeparator />
<CommandEmpty>
<div className="py-6 text-center text-sm text-muted-foreground">
<p>{t('noModelsFound')}</p>
@@ -169,7 +179,7 @@ export function ModelSelector({
</div>
</CommandEmpty>
{recentlyUsedModels.length > 0 && (
{shouldShowRecentlyUsed && (
<CommandGroup heading={t('recentlyUsed')}>
{recentlyUsedModels.map((model) => (
<CommandItem
@@ -190,7 +200,7 @@ export function ModelSelector({
</CommandGroup>
)}
{recentlyUsedModels.length > 0 && <CommandSeparator />}
{shouldShowRecentlyUsed && <CommandSeparator />}
{/* Loading state */}
{isLoading && (
@@ -252,6 +262,29 @@ export function ModelSelector({
</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>
+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);
+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();
});
});
+347
View File
@@ -0,0 +1,347 @@
import { Decimal } from 'decimal.js';
import { useState, useEffect } from 'react';
import { generateSecretKey } from 'nostr-tools';
import { nip19 } from 'nostr-tools';
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft } 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 { 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 { ShakespeareLogo } from '@/components/ShakespeareLogo';
interface OnboardingDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
type OnboardingStep = 'welcome' | 'model-selection' | 'conclusion';
const SHAKESPEARE_PROVIDER = {
id: "shakespeare",
baseURL: "https://ai.shakespeare.diy/v1",
nostr: true,
};
export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) {
const [step, setStep] = useState<OnboardingStep>('welcome');
const [selectedModel, setSelectedModel] = useState<string>('');
const [isSettingUp, setIsSettingUp] = useState(false);
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
const { setProvider, addRecentlyUsedModel } = useAISettings();
const { user } = useCurrentUser();
const login = useLoginActions();
const { models, isLoading: isLoadingModels } = useProviderModels();
// Filter models to only show Shakespeare provider models
const shakespeareModels = models.filter(model => model.provider === 'shakespeare');
const handleGetStarted = async () => {
setIsSettingUp(true);
try {
// If user is not logged in, generate and login with secret key
if (!user) {
const secretKey = generateSecretKey();
const nsec = nip19.nsecEncode(secretKey);
login.nsec(nsec);
}
// Add Shakespeare provider to their config
setProvider(SHAKESPEARE_PROVIDER);
// 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 = shakespeareModels.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');
setSelectedModel('');
setIsSettingUp(false);
setShowCreditsDialog(false);
}
}, [open]);
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl max-h-[90vh] sm:max-h-[80vh] flex flex-col">
<DialogHeader className="flex-shrink-0">
<DialogTitle className="flex items-center gap-2">
{step === 'model-selection' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('welcome')}
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 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 === '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>
))}
</>
) : shakespeareModels.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>
) : (
shakespeareModels.map((model) => {
const isSelected = selectedModel === model.fullId;
const isFree = model.pricing?.prompt.equals(0) && model.pricing?.completion.equals(0);
const isPremium = !isFree;
return (
<Card
key={model.fullId}
className={`cursor-pointer transition-all hover:shadow-md ${
isSelected ? 'ring-2 ring-primary' : ''
}`}
onClick={() => handleModelSelect(model.fullId)}
>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex-1">
<CardTitle className={`text-xl font-semibold ${isPremium ? 'bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent' : ''}`}>
{ model.name || model.description || model.id}
</CardTitle>
{model.description && (
<p className="text-sm text-muted-foreground mt-1">
{model.description || model.id}
</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>
<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 border-t 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 && (
<CreditsDialog
open={showCreditsDialog}
onOpenChange={(open) => {
if (!open) {
handleCreditsDialogClose();
}
}}
provider={SHAKESPEARE_PROVIDER}
/>
)}
</>
);
}
+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>
);
}
+685
View File
@@ -0,0 +1,685 @@
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 { Checkbox } from '@/components/ui/checkbox';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Upload, FileArchive, AlertCircle, FileText, Trash2, FolderOpen, CheckSquare, Square, AlertTriangle } from 'lucide-react';
import { useProjects } from '@/hooks/useProjects';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { cn } from '@/lib/utils';
import JSZip from 'jszip';
interface ProjectInfo {
id: string;
name: string;
path: string;
files: string[];
isConflict: boolean;
selected: boolean;
}
interface ProjectImportDialogProps {
mode?: 'single' | 'bulk';
onImport: (data: { file: File; projectId?: string } | { projects: { id: string; files: { [path: string]: Uint8Array } }[] }, overwrite: boolean) => Promise<void>;
disabled?: boolean;
className?: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
export function ProjectImportDialog({
mode = 'single',
onImport,
disabled = false,
className,
open,
onOpenChange
}: ProjectImportDialogProps) {
// 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 [discoveredProjects, setDiscoveredProjects] = useState<ProjectInfo[]>([]);
const [isAnalyzing, setIsAnalyzing] = useState(false);
const [isImporting, setIsImporting] = useState(false);
const [importProgress, setImportProgress] = useState(0);
const [error, setError] = useState<string | null>(null);
const [isDragOver, setIsDragOver] = useState(false);
const [showOverwriteDialog, setShowOverwriteDialog] = useState(false);
const [zipData, setZipData] = useState<JSZip | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const { data: existingProjects = [] } = useProjects();
const projectsManager = useProjectsManager();
// Analyze ZIP for bulk import
const analyzeZipForProjects = useCallback(async (zip: JSZip): Promise<ProjectInfo[]> => {
const projects: ProjectInfo[] = [];
const projectPaths = new Set<string>();
// Find all potential project directories
for (const [path] of Object.entries(zip.files)) {
const pathParts = path.split('/').filter(part => part !== '');
// Skip files in root directory - we're looking for project directories
if (pathParts.length < 2) continue;
// Check if this looks like a project indicator file
if (isProjectIndicator(path)) {
let projectPath: string;
// If structure is projects/project-name/file, extract project-name
if (pathParts[0] === 'projects' && pathParts.length >= 3) {
projectPath = `projects/${pathParts[1]}`;
} else {
// Otherwise, assume first directory is the project
projectPath = pathParts[0];
}
projectPaths.add(projectPath);
}
}
// For each discovered project path, gather information
for (const projectPath of projectPaths) {
const files: string[] = [];
// Collect all files in this project directory
for (const [path, zipEntry] of Object.entries(zip.files)) {
if (path.startsWith(projectPath + '/') && !zipEntry.dir) {
const relativePath = path.substring(projectPath.length + 1);
files.push(relativePath);
}
}
// Generate project ID and name from directory path
let id: string;
let name: string;
if (projectPath.startsWith('projects/')) {
const projectName = projectPath.substring('projects/'.length);
id = projectName
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
name = projectName;
} else {
id = projectPath
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
name = projectPath;
}
// Skip if no files found (empty directory)
if (files.length === 0) continue;
// Check if this project conflicts with existing projects
const isConflict = existingProjects.some(existing => existing.id === id);
projects.push({
id,
name,
path: projectPath,
files,
isConflict,
selected: !isConflict, // Auto-select non-conflicting projects
});
}
return projects;
}, [existingProjects]);
// Handle file selection
const handleFileSelect = useCallback(async (file: File) => {
// Only accept zip files
if (!file.name.toLowerCase().endsWith('.zip')) {
setError('Please select a ZIP file');
return;
}
setSelectedFile(file);
setError(null);
setGeneratedId('');
// Auto-generate ID from file name for single mode
if (mode === 'single') {
const baseName = file.name.replace(/\.zip$/i, '');
const id = baseName
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
setGeneratedId(id);
}
// For bulk mode, analyze the ZIP to discover projects
if (mode === 'bulk') {
setIsAnalyzing(true);
setDiscoveredProjects([]);
try {
const arrayBuffer = await file.arrayBuffer();
const zip = await JSZip.loadAsync(arrayBuffer);
setZipData(zip);
const projects = await analyzeZipForProjects(zip);
setDiscoveredProjects(projects);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to analyze ZIP file');
} finally {
setIsAnalyzing(false);
}
}
}, [mode, analyzeZipForProjects]);
const isProjectIndicator = (path: string): boolean => {
const indicators = [
'package.json',
'index.html',
'src/',
'public/',
'tsconfig.json',
'vite.config.',
'webpack.config.',
'README.md',
'.git/',
];
return indicators.some(indicator => path.includes('/' + indicator));
};
// Check for existing project when generated ID changes (single mode)
useEffect(() => {
if (mode === 'single' && generatedId && existingProjects.length > 0) {
const existing = existingProjects.find(project => project.id === generatedId);
if (existing) {
setError(`A project with ID "${generatedId}" already exists. You can choose to overwrite it.`);
} else {
setError(null);
}
}
}, [generatedId, existingProjects, mode]);
// 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]);
}
}, [handleFileSelect]);
const handleClickUpload = () => {
fileInputRef.current?.click();
};
const handleFileRemove = () => {
setSelectedFile(null);
setGeneratedId('');
setDiscoveredProjects([]);
setZipData(null);
setError(null);
};
// Bulk import project selection handlers
const handleProjectToggle = (projectId: string, checked: boolean) => {
setDiscoveredProjects(prev =>
prev.map(project =>
project.id === projectId ? { ...project, selected: checked } : project
)
);
};
const handleSelectAll = () => {
setDiscoveredProjects(prev =>
prev.map(project => ({ ...project, selected: true }))
);
};
const handleDeselectAll = () => {
setDiscoveredProjects(prev =>
prev.map(project => ({ ...project, selected: false }))
);
};
const selectedProjects = discoveredProjects.filter(project => project.selected);
const conflictingProjects = selectedProjects.filter(project => project.isConflict);
const handleImport = async (overwrite = false) => {
if (!selectedFile) return;
setIsImporting(true);
setImportProgress(0);
setError(null);
try {
if (mode === 'single') {
// Single project import
const progressInterval = setInterval(() => {
setImportProgress(prev => Math.min(prev + 10, 90));
}, 200);
await onImport({ file: selectedFile, projectId: generatedId }, overwrite);
clearInterval(progressInterval);
setImportProgress(100);
} else {
// Bulk project import
const projectsToImport = await Promise.all(
selectedProjects.map(async (project) => {
const files = await projectsManager.extractFilesFromZip(zipData!, project.path);
return {
id: project.id,
files,
};
})
);
const progressInterval = setInterval(() => {
setImportProgress(prev => Math.min(prev + 5, 90));
}, 100);
await onImport({ projects: projectsToImport }, overwrite);
clearInterval(progressInterval);
setImportProgress(100);
}
// Close dialog and reset state immediately
setIsOpen(false);
handleFileRemove();
setImportProgress(0);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to import projects');
setImportProgress(0);
} finally {
setIsImporting(false);
}
};
const handleImportWithOverwriteCheck = async () => {
if (mode === 'single') {
// For single mode, check if project exists
const existingProject = existingProjects.find(project => project.id === generatedId);
if (existingProject) {
setShowOverwriteDialog(true);
} else {
await handleImport(false);
}
} else {
// For bulk mode, check for conflicts
if (conflictingProjects.length > 0) {
setShowOverwriteDialog(true);
} else {
await handleImport(false);
}
}
};
const confirmOverwrite = async () => {
setShowOverwriteDialog(false);
await handleImport(true);
};
const handleClose = () => {
if (!isImporting && !isAnalyzing) {
setIsOpen(false);
handleFileRemove();
setImportProgress(0);
}
};
// Only render DialogTrigger if this component is being used in uncontrolled mode
const isControlled = open !== undefined && onOpenChange !== undefined;
const canImport = mode === 'single'
? selectedFile && generatedId
: selectedProjects.length > 0;
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" />
{mode === 'single' ? 'Import ZIP' : 'Import Projects'}
</Button>
</DialogTrigger>
)}
<DialogContent className={cn(
"h-auto max-h-[90vh] flex flex-col",
mode === 'single' ? "sm:max-w-md" : "sm:max-w-xl"
)}>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Upload className="h-5 w-5" />
{mode === 'single' ? 'Import Project from ZIP' : 'Import Multiple Projects'}
</DialogTitle>
<DialogDescription>
{mode === 'single'
? 'Upload a ZIP file containing your project source code to import it into Shakespeare.'
: 'Upload a ZIP file containing multiple projects to import them into Shakespeare.'
}
</DialogDescription>
</DialogHeader>
<div className="flex-1 flex flex-col overflow-hidden min-h-0 space-y-4">
{!isImporting && !isAnalyzing && (
<>
{/* Drag and Drop Area */}
<div
className={cn(
"relative border-2 border-dashed rounded-lg p-4 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 || isAnalyzing}
/>
<div className="space-y-2">
<div className="flex justify-center">
{selectedFile ? (
<FileText className="h-6 w-6 text-green-600" />
) : (
<Upload className="h-6 w-6 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">
{mode === 'single'
? 'Supports ZIP files up to 50MB'
: 'Supports ZIP files containing exported Shakespeare projects'
}
</p>
</div>
)}
</div>
</div>
</div>
{/* Error Display */}
{error && (
<div className="flex items-center gap-2 text-sm text-amber-600 mb-4">
<AlertTriangle className="h-4 w-4" />
{error}
</div>
)}
{/* Project List (Bulk Mode Only) */}
{mode === 'bulk' && discoveredProjects.length > 0 && (
<div className="space-y-3 flex-1 flex flex-col min-h-0">
<div className="flex items-center justify-between flex-shrink-0">
<h3 className="text-sm font-medium">
Found {discoveredProjects.length} project{discoveredProjects.length !== 1 ? 's' : ''}
</h3>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={handleSelectAll}
className="h-8 text-xs"
>
<CheckSquare className="h-3 w-3 mr-1" />
Select All
</Button>
<Button
variant="outline"
size="sm"
onClick={handleDeselectAll}
className="h-8 text-xs"
>
<Square className="h-3 w-3 mr-1" />
Deselect All
</Button>
</div>
</div>
<div className="border rounded-lg overflow-hidden">
<ScrollArea className="h-64">
<div className="p-2 space-y-1">
{discoveredProjects.map((project) => (
<div
key={project.id}
className={cn(
"flex items-start space-x-3 p-2 rounded-lg border transition-colors",
project.selected ? "bg-primary/5 border-primary/20" : "bg-background",
project.isConflict && "border-amber-200 bg-amber-50/50 dark:border-amber-800 dark:bg-amber-950/20"
)}
>
<Checkbox
id={`project-${project.id}`}
checked={project.selected}
onCheckedChange={(checked) => handleProjectToggle(project.id, checked as boolean)}
className="mt-1"
/>
<div className="flex-1 min-w-0 space-y-1">
<div className="flex items-center gap-2">
<FolderOpen className="h-4 w-4 text-primary flex-shrink-0" />
<span className="font-medium text-sm truncate">{project.name}</span>
{project.isConflict && (
<div className="hidden sm:flex items-center gap-1 text-amber-600 flex-shrink-0">
<AlertTriangle className="h-3 w-3" />
<span className="text-xs">Conflict</span>
</div>
)}
</div>
{project.isConflict && (
<div className="sm:hidden flex items-center gap-1 text-amber-600">
<AlertTriangle className="h-3 w-3" />
<span className="text-xs font-medium">Conflict - Will overwrite existing project</span>
</div>
)}
<p className="text-xs text-muted-foreground">
{project.files.length} file{project.files.length !== 1 ? 's' : ''}
{project.isConflict && <span className="hidden sm:inline"> • Will overwrite existing project</span>}
</p>
</div>
</div>
))}
</div>
</ScrollArea>
</div>
</div>
)}
{/* Import Button */}
{selectedFile && (mode === 'single' || discoveredProjects.length > 0) && (
<div className="flex justify-end gap-2 pt-3 border-t flex-shrink-0">
<Button variant="outline" onClick={handleClose} disabled={isImporting}>
Cancel
</Button>
<Button
onClick={handleImportWithOverwriteCheck}
disabled={!canImport || isImporting}
className={mode === 'single' && error ? "bg-amber-600 hover:bg-amber-700" : conflictingProjects.length > 0 ? "bg-amber-600 hover:bg-amber-700" : ""}
>
{mode === 'single' ? (
error ? (
<>
<Trash2 className="mr-2 h-4 w-4" />
Overwrite Project
</>
) : (
<>
<Upload className="mr-2 h-4 w-4" />
Import Project
</>
)
) : (
<>
{conflictingProjects.length > 0 ? <Trash2 className="mr-2 h-4 w-4" /> : <Upload className="mr-2 h-4 w-4" />}
{conflictingProjects.length > 0 ? 'Import & Overwrite' : 'Import Projects'} ({selectedProjects.length})
</>
)}
</Button>
</div>
)}
</>
)}
{/* Analysis Progress (Bulk Mode Only) */}
{mode === 'bulk' && isAnalyzing && (
<div className="space-y-2 py-6">
<div className="flex items-center gap-2 text-sm justify-center">
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div>
Analyzing ZIP file...
</div>
<p className="text-xs text-muted-foreground text-center">
Discovering projects and checking for conflicts...
</p>
</div>
)}
{/* Import Progress */}
{isImporting && (
<div className="space-y-3 py-6">
<div className="flex items-center gap-2 text-sm justify-center">
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div >
{mode === 'single' ? 'Importing project...' : `Importing ${selectedProjects.length} project${selectedProjects.length !== 1 ? 's' : ''}...`}
</div>
<Progress value={importProgress} className="w-full" />
<p className="text-xs text-muted-foreground text-center">
Extracting files and setting up projects...
</p>
</div>
)}
{/* Success State */}
{!isImporting && !isAnalyzing && importProgress === 100 && (
<div className="flex items-center gap-2 text-sm text-green-600 justify-center py-3">
<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>
{mode === 'single' ? 'Project imported successfully!' : 'Projects 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" />
{mode === 'single' ? 'Overwrite Existing Project' : 'Overwrite Existing Projects'}
</AlertDialogTitle>
<AlertDialogDescription className="space-y-3">
{mode === 'single' ? (
<>
<p>
A project with 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 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>
You have selected <strong>{conflictingProjects.length}</strong> project{conflictingProjects.length !== 1 ? 's' : ''} that already exist:
</p>
<ul className="list-disc list-inside text-sm space-y-1 ml-2 max-h-32 overflow-y-auto">
{conflictingProjects.map((project) => (
<li key={project.id}>
<strong>{project.name}</strong> (ID: {project.id})
</li>
))}
</ul>
<p>Overwriting will:</p>
<ul className="list-disc list-inside text-sm space-y-1 ml-2">
<li><strong>Delete all existing files</strong> in these projects</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, {mode === 'single' ? 'Overwrite Project' : 'Overwrite Projects'}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}
-359
View File
@@ -1,359 +0,0 @@
import { useState, useEffect } from 'react';
import { type Project } from '@/lib/ProjectsManager';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useGitStatus } from '@/hooks/useGitStatus';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Skeleton } from '@/components/ui/skeleton';
import {
Calendar,
Folder,
GitBranch,
Package,
FileText,
GitCommit,
GitMerge,
Globe,
Clock,
User,
Hash,
AlertCircle,
CheckCircle,
Plus,
Minus,
Edit,
Eye
} from 'lucide-react';
interface ProjectInfoDialogProps {
project: Project;
open: boolean;
onOpenChange: (open: boolean) => void;
}
interface ProjectMetadata {
description?: string;
version?: string;
nostrRepoAddress?: string;
fileCount?: number;
}
export function ProjectInfoDialog({ project, open, onOpenChange }: ProjectInfoDialogProps) {
const [metadata, setMetadata] = useState<ProjectMetadata>({});
const [isLoading, setIsLoading] = useState(false);
const projectsManager = useProjectsManager();
const gitStatus = useGitStatus(project.id);
useEffect(() => {
if (!open) return;
const loadProjectMetadata = async () => {
setIsLoading(true);
try {
const meta: ProjectMetadata = {};
// Try to read package.json
try {
const packageJsonContent = await projectsManager.readFile(project.id, 'package.json');
const packageJson = JSON.parse(packageJsonContent);
meta.description = packageJson.description;
meta.version = packageJson.version;
} catch {
// package.json doesn't exist or is invalid
}
// Get Nostr repo address
try {
const repoAddress = await projectsManager.getNostrRepoAddress(project.id);
if (repoAddress) {
meta.nostrRepoAddress = repoAddress;
}
} catch {
// No Nostr repo configured
}
// Calculate file count and size (simplified)
try {
const files = await projectsManager.listFiles(project.id);
meta.fileCount = files.length;
} catch {
// Can't read directory
}
setMetadata(meta);
} catch (error) {
console.error('Failed to load project metadata:', error);
} finally {
setIsLoading(false);
}
};
loadProjectMetadata();
}, [open, project.id, projectsManager]);
const formatDate = (date: Date) => {
return new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}).format(date);
};
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`;
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Folder className="h-5 w-5" />
{project.name}
</DialogTitle>
<DialogDescription>
Project information and metadata
</DialogDescription>
</DialogHeader>
{isLoading ? (
<div className="space-y-4">
<div className="animate-pulse">
<div className="h-4 bg-muted rounded w-3/4 mb-2"></div>
<div className="h-4 bg-muted rounded w-1/2"></div>
</div>
</div>
) : (
<div className="space-y-6">
{/* Basic Information */}
<div className="space-y-3">
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
Basic Information
</h3>
<div className="grid grid-cols-2 gap-4 text-sm">
<div className="flex items-center gap-2">
<Folder className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Project ID:</span>
<code className="bg-muted px-1.5 py-0.5 rounded text-xs">{project.id}</code>
</div>
<div className="flex items-center gap-2">
<Calendar className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Last Modified:</span>
<span>{formatDistanceToNow(project.lastModified)}</span>
</div>
{metadata.version && (
<div className="flex items-center gap-2">
<Package className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Version:</span>
<Badge variant="secondary">{metadata.version}</Badge>
</div>
)}
{metadata.fileCount !== undefined && (
<div className="flex items-center gap-2">
<FileText className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Files:</span>
<span>{metadata.fileCount}</span>
</div>
)}
</div>
<div className="text-sm">
<span className="text-muted-foreground">Created:</span>
<span className="ml-2">{formatDate(project.lastModified)}</span>
</div>
{metadata.description && (
<div className="text-sm">
<span className="text-muted-foreground">Description:</span>
<p className="mt-1 text-foreground">{metadata.description}</p>
</div>
)}
</div>
{/* Nostr Information */}
{metadata.nostrRepoAddress && (
<>
<Separator />
<div className="space-y-3">
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-2">
<GitBranch className="h-4 w-4" />
Nostr Repository
</h3>
<div className="text-sm">
<span className="text-muted-foreground">Repository Address:</span>
<code className="ml-2 bg-muted px-1.5 py-0.5 rounded text-xs break-all">
{metadata.nostrRepoAddress}
</code>
</div>
</div>
</>
)}
{/* Git Status Information */}
<Separator />
<div className="space-y-3">
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-2">
<GitCommit className="h-4 w-4" />
Git Repository
</h3>
{gitStatus.isLoading ? (
<div className="space-y-2">
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4 w-1/2" />
<Skeleton className="h-4 w-2/3" />
</div>
) : !gitStatus.data?.isGitRepo ? (
<div className="text-sm text-muted-foreground flex items-center gap-2">
<AlertCircle className="h-4 w-4" />
This project is not a Git repository
</div>
) : (
<div className="space-y-4">
{/* Repository Status */}
<div className="grid grid-cols-2 gap-4 text-sm">
{/* Current Branch */}
<div className="flex items-center gap-2">
<GitBranch className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Branch:</span>
<Badge variant="outline" className="text-xs">
{gitStatus.data?.currentBranch || 'unknown'}
</Badge>
</div>
{/* Uncommitted Changes */}
<div className="flex items-center gap-2">
{gitStatus.data?.hasUncommittedChanges ? (
<>
<AlertCircle className="h-4 w-4 text-orange-500" />
<span className="text-muted-foreground">Status:</span>
<Badge variant="destructive" className="text-xs">
{gitStatus.data.changedFiles.length} uncommitted changes
</Badge>
</>
) : (
<>
<CheckCircle className="h-4 w-4 text-green-500" />
<span className="text-muted-foreground">Status:</span>
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
Clean working tree
</Badge>
</>
)}
</div>
{/* Total Commits */}
<div className="flex items-center gap-2">
<Hash className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Commits:</span>
<span>{gitStatus.data?.totalCommits || 0}</span>
</div>
{/* All Branches */}
<div className="flex items-center gap-2">
<GitMerge className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Branches:</span>
<span>{gitStatus.data?.branches.length || 0}</span>
</div>
</div>
{/* Latest Commit */}
{gitStatus.data?.latestCommit && (
<div className="space-y-2">
<h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
Latest Commit
</h4>
<div className="bg-muted/30 rounded-md p-3 space-y-2">
<div className="flex items-start gap-2">
<GitCommit className="h-4 w-4 text-muted-foreground mt-0.5" />
<div className="flex-1 min-w-0">
<div className="text-sm font-medium break-words">
{gitStatus.data.latestCommit.message.split('\n')[0]}
</div>
<div className="text-xs text-muted-foreground font-mono">
{gitStatus.data.latestCommit.oid.substring(0, 7)}
</div>
</div>
</div>
<div className="flex items-center gap-4 text-xs text-muted-foreground">
<div className="flex items-center gap-1">
<User className="h-3 w-3" />
{gitStatus.data.latestCommit.author.name}
</div>
<div className="flex items-center gap-1">
<Clock className="h-3 w-3" />
{new Date(gitStatus.data.latestCommit.author.timestamp * 1000).toLocaleDateString()}
</div>
</div>
</div>
</div>
)}
{/* Changed Files */}
{gitStatus.data?.hasUncommittedChanges && gitStatus.data.changedFiles.length > 0 && (
<div className="space-y-2">
<h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
Uncommitted Changes
</h4>
<div className="space-y-1 max-h-32 overflow-y-auto">
{gitStatus.data.changedFiles.map((file, index) => (
<div key={index} className="flex items-center gap-2 text-sm">
{file.status === 'added' && <Plus className="h-3 w-3 text-green-500" />}
{file.status === 'modified' && <Edit className="h-3 w-3 text-blue-500" />}
{file.status === 'deleted' && <Minus className="h-3 w-3 text-red-500" />}
{file.status === 'untracked' && <Eye className="h-3 w-3 text-orange-500" />}
{file.status === 'staged' && <CheckCircle className="h-3 w-3 text-purple-500" />}
<span className="text-muted-foreground capitalize">{file.status}:</span>
<code className="text-xs bg-muted px-1 py-0.5 rounded font-mono">
{file.filepath}
</code>
</div>
))}
</div>
</div>
)}
{/* Remotes */}
{gitStatus.data?.remotes && gitStatus.data.remotes.length > 0 && (
<div className="space-y-2">
<h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
Remote Repositories
</h4>
<div className="space-y-1">
{gitStatus.data.remotes.map((remote, index) => (
<div key={index} className="flex items-center gap-2 text-sm">
<Globe className="h-3 w-3 text-muted-foreground" />
<span className="text-muted-foreground font-medium">{remote.name}:</span>
<code className="text-xs bg-muted px-1 py-0.5 rounded font-mono break-all">
{remote.url}
</code>
</div>
))}
</div>
</div>
)}
</div>
)}
</div>
</div>
)}
</DialogContent>
</Dialog>
);
}
+1 -1
View File
@@ -60,7 +60,7 @@ describe('ProjectSidebar', () => {
</TestApp>
);
expect(screen.getByText('🎭')).toBeInTheDocument();
expect(screen.getByAltText('Shakespeare')).toBeInTheDocument();
expect(screen.getByText('Shakespeare')).toBeInTheDocument();
});
+2 -1
View File
@@ -12,6 +12,7 @@ import { useIsMobile } from '@/hooks/useIsMobile';
import type { Project } from '@/lib/ProjectsManager';
import { cn } from '@/lib/utils';
import { useQueryClient } from '@tanstack/react-query';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
interface ProjectItemProps {
project: Project;
@@ -134,7 +135,7 @@ export function ProjectSidebar({
onClick={() => navigateAndClose('/')}
className="flex items-center gap-3 hover:opacity-80 transition-opacity text-left"
>
<span className="text-2xl">🎭</span>
<ShakespeareLogo className="w-6 h-6" />
<h1 className="text-xl font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Shakespeare
</h1>
+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>
);
}
+3 -3
View File
@@ -17,13 +17,13 @@ export function SessionManagerProvider({ children }: SessionManagerProviderProps
const { fs } = useFS();
const { settings } = useAISettings();
const { models } = useProviderModels();
const { user } = useCurrentUser();
const { user, metadata } = useCurrentUser();
const sessionManager = useMemo(() => {
const getProviderModels = () => models;
const getCurrentUser = () => user;
const getCurrentUser = () => ({ user, metadata });
return new SessionManager(fs, settings, getProviderModels, getCurrentUser);
}, [fs, settings, models, user]);
}, [fs, settings, models, user, metadata]);
// Cleanup on unmount
useEffect(() => {
@@ -1,110 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { ChatPane } from './ChatPane';
// Mock the AI settings hook to return configured state
vi.mock('@/hooks/useAISettings', () => ({
useAISettings: () => ({
isConfigured: true,
settings: {
recentlyUsedModels: ['gpt-4'],
},
addRecentlyUsedModel: vi.fn(),
}),
}));
// Mock other hooks
vi.mock('@/hooks/useFS', () => ({
useFS: () => ({
fs: {},
}),
}));
vi.mock('@/hooks/useCurrentUser', () => ({
useCurrentUser: () => ({
user: null,
metadata: null,
}),
}));
vi.mock('@/hooks/useKeepAlive', () => ({
useKeepAlive: () => ({
updateMetadata: vi.fn(),
}),
}));
vi.mock('@/hooks/useAIChat', () => ({
useAIChat: () => ({
messages: [],
streamingMessage: null,
isLoading: false,
totalCost: 0,
lastInputTokens: 0,
sendMessage: vi.fn(),
startGeneration: vi.fn(),
stopGeneration: vi.fn(),
startNewSession: vi.fn(),
}),
}));
vi.mock('@/hooks/useProviderModels', () => ({
useProviderModels: () => ({
models: [
{
fullId: 'gpt-4',
contextLength: 8192,
},
],
}),
}));
describe('ChatPane', () => {
it('handles image paste from clipboard', async () => {
render(
<TestApp>
<ChatPane projectId="test-project" />
</TestApp>
);
const textarea = screen.getByPlaceholderText(/Ask me to add features/);
expect(textarea).toBeInTheDocument();
// Create a mock image file
const imageFile = new File(['fake-image-data'], 'test.png', {
type: 'image/png',
});
// Create mock clipboard data
const mockClipboardItem = {
type: 'image/png',
getAsFile: () => imageFile,
} as DataTransferItem;
const mockClipboardData = {
items: [mockClipboardItem],
length: 1,
} as unknown as DataTransfer;
// Fire the paste event on the textarea using fireEvent
fireEvent.paste(textarea, {
clipboardData: mockClipboardData,
});
// The file should be added to the attached files
// We can't easily test the internal state, but we can verify the event was handled
// without throwing an error
expect(textarea).toBeInTheDocument();
});
it('renders welcome message when no messages exist', () => {
render(
<TestApp>
<ChatPane projectId="test-project" />
</TestApp>
);
expect(screen.getByText('Welcome to Shakespeare')).toBeInTheDocument();
expect(screen.getByText(/Your AI-powered development assistant/)).toBeInTheDocument();
});
});
+242 -115
View File
@@ -7,6 +7,7 @@ import { Skeleton } from '@/components/ui/skeleton';
import { CircularProgress } from '@/components/ui/circular-progress';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { FileAttachment } from '@/components/ui/file-attachment';
import { OnboardingDialog } from '@/components/OnboardingDialog';
import { Square, Loader2, ChevronDown, ArrowUp } from 'lucide-react';
import { useAISettings } from '@/hooks/useAISettings';
import { useFS } from '@/hooks/useFS';
@@ -33,24 +34,26 @@ import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool';
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
import { ShellTool } from '@/lib/tools/ShellTool';
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
import { Git } from '@/lib/git';
import { ReadConsoleMessagesTool, ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool';
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
import { Tool } from '@/lib/tools/Tool';
import OpenAI from 'openai';
import { makeSystemPrompt } from '@/lib/system';
import { assistantContentEmpty } from '@/lib/ai-messages';
import { saveFileToTmp } from '@/lib/fileUtils';
import { useGit } from '@/hooks/useGit';
import { Quilly } from '@/components/Quilly';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
// Clean interfaces now handled by proper hooks
interface ChatPaneProps {
projectId: string;
onNewChat?: () => void;
onBuild?: () => void;
onDeploy?: () => void;
onNewChat: () => void;
onFirstInteraction?: () => void;
onLoadingChange?: (isLoading: boolean) => void;
isLoading?: boolean;
isBuildLoading?: boolean;
isDeployLoading?: boolean;
consoleError?: ProjectPreviewConsoleError | null;
onDismissConsoleError?: () => void;
}
export interface ChatPaneRef {
@@ -59,31 +62,44 @@ export interface ChatPaneRef {
export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
projectId,
onNewChat: _onNewChat,
onBuild: _onBuild,
onDeploy: _onDeploy,
onNewChat,
onFirstInteraction,
onLoadingChange,
isLoading: externalIsLoading,
isBuildLoading: externalIsBuildLoading,
isDeployLoading: externalIsDeployLoading
consoleError,
onDismissConsoleError,
}, ref) => {
const { t } = useTranslation();
const [searchParams, setSearchParams] = useSearchParams();
const { fs } = useFS();
const { git } = useGit();
const { user } = useCurrentUser();
const { models } = useProviderModels();
const [input, setInput] = useState('');
const [systemPrompt, setSystemPrompt] = useState('');
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
const [isDragOver, setIsDragOver] = useState(false);
const [scrolledProjects] = useState(() => new Set<string>());
const [showOnboarding, setShowOnboarding] = useState(false);
const [isStuck, setIsStuck] = useState(false);
const [aiError, setAIError] = useState<Error | null>(null);
// Determine which error to show - console error takes priority over AI errors
const displayError = consoleError || aiError;
// Use external state if provided, otherwise default to false
const isBuildLoading = externalIsBuildLoading || false;
const isDeployLoading = externalIsDeployLoading || false;
const scrollAreaRef = useRef<HTMLDivElement>(null);
const { isConfigured, settings, addRecentlyUsedModel } = useAISettings();
const [providerModel, setProviderModel] = useState(() => {
// Initialize with first recently used model if available, otherwise empty
return settings.recentlyUsedModels?.[0] || '';
});
// State to control model selector dropdown
const [isModelSelectorOpen, setIsModelSelectorOpen] = useState(false);
const [shouldAutostart, setShouldAutostart] = useState(false);
const autostartedRef = useRef(false);
useEffect(() => {
if (!providerModel && settings.recentlyUsedModels?.length) {
@@ -91,15 +107,32 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
}, [providerModel, settings.recentlyUsedModels]);
const [searchParams, setSearchParams] = useSearchParams();
const { fs } = useFS();
const { user, metadata } = useCurrentUser();
const { models } = useProviderModels();
useEffect(() => {
const urlModel = searchParams.get('model');
const autostart = searchParams.get('autostart');
if (urlModel && !providerModel) {
setProviderModel(urlModel);
}
if (autostart === 'true') {
setShouldAutostart(true);
}
// Clear the autostart and model parameters
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.delete('autostart');
newSearchParams.delete('model');
setSearchParams(newSearchParams, { replace: true });
}, [providerModel, searchParams, setSearchParams])
// Reset error state when navigating between projects and switching models
useEffect(() => {
setAIError(null);
}, [projectId, providerModel]);
// Initialize AI chat with tools
const cwd = `/projects/${projectId}`;
const customTools = useMemo(() => {
const git = new Git(fs);
const baseTools = {
git_commit: new GitCommitTool(fs, cwd, git),
text_editor_view: new TextEditorViewTool(fs, cwd),
@@ -117,6 +150,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
nostr_read_nips_index: new NostrReadNipsIndexTool(),
nostr_generate_kind: new NostrGenerateKindTool(),
shell: new ShellTool(fs, cwd, git),
read_console_messages: new ReadConsoleMessagesTool(),
};
// Add deploy tool only if user is logged in
@@ -128,7 +162,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
return baseTools;
}, [fs, cwd, user, projectId]);
}, [fs, git, cwd, user, projectId]);
// Convert tools to OpenAI format
const tools = useMemo(() => {
@@ -141,12 +175,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
// Keep-alive functionality to prevent tab throttling during AI processing
const { updateMetadata } = useKeepAlive({
enabled: externalIsLoading || isBuildLoading || isDeployLoading,
enabled: externalIsLoading || isBuildLoading,
title: 'Shakespeare',
artist: `Working on ${projectId}...`,
artwork: [
{
src: '/favicon.png',
src: '/shakespeare.png',
sizes: '512x512',
type: 'image/png'
}
@@ -158,18 +192,10 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
updateMetadata(title, description);
}, [updateMetadata]);
useEffect(() => {
makeSystemPrompt({
cwd,
fs,
mode: "agent",
name: "Shakespeare",
profession: "software extraordinaire",
tools: Object.values(tools),
user,
metadata,
}).then(setSystemPrompt)
}, [fs, cwd, tools, user, metadata]);
// Handle AI errors from the SessionManager
const onAIError = useCallback((error: Error) => {
setAIError(error);
}, []);
const {
messages,
@@ -185,10 +211,24 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
projectId,
tools,
customTools,
systemPrompt,
onUpdateMetadata,
onAIError,
});
// Handle console error help requests
const handleConsoleErrorHelp = useCallback(() => {
sendMessage('Read the console messages and fix any errors present.', providerModel);
}, [sendMessage, providerModel]);
// Handle error dismissal
const handleErrorDismiss = useCallback(() => {
if (consoleError && onDismissConsoleError) {
onDismissConsoleError();
} else {
setAIError(null);
}
}, [consoleError, onDismissConsoleError]);
// Use external loading state if provided, otherwise use internal state
const isLoading = externalIsLoading !== undefined ? externalIsLoading : internalIsLoading;
@@ -210,41 +250,47 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
}, [internalIsLoading, onLoadingChange]);
// Check for autostart parameter and trigger AI generation
// Timer to detect when AI appears stuck during tool generation
useEffect(() => {
const autostart = searchParams.get('autostart');
const urlModel = searchParams.get('model');
if (autostart === 'true' && isConfigured) {
// Use model from URL if available, otherwise use current selection
const modelToUse = urlModel?.trim() || providerModel.trim();
if (modelToUse) {
// Update provider model if it came from URL
if (urlModel?.trim() && urlModel.trim() !== providerModel) {
setProviderModel(urlModel.trim());
}
// Clear the autostart and model parameters so they don't trigger again
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.delete('autostart');
newSearchParams.delete('model');
setSearchParams(newSearchParams, { replace: true });
// Start AI generation
addRecentlyUsedModel(modelToUse);
startGeneration(modelToUse);
}
}
}, [addRecentlyUsedModel, isConfigured, providerModel, searchParams, setSearchParams, startGeneration]);
// Start a 2-second timer
const timer = streamingMessage
? setTimeout(() => setIsStuck(true), 2000)
: undefined;
return () => {
setIsStuck(false);
clearTimeout(timer);
};
}, [streamingMessage]);
// Function to scroll to bottom
const scrollToBottom = () => {
const scrollToBottom = useCallback(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
};
}, []);
// Function to open model selector dropdown
const openModelSelector = useCallback(() => {
setIsModelSelectorOpen(true);
}, []);
// Scroll to bottom when AI error occurs
useEffect(() => {
scrollToBottom();
}, [aiError, scrollToBottom]);
// Check for autostart parameter and trigger AI generation
useEffect(() => {
if (autostartedRef.current) return;
if (shouldAutostart && providerModel && isConfigured) {
// Start AI generation
addRecentlyUsedModel(providerModel);
startGeneration(providerModel);
autostartedRef.current = true;
}
}, [addRecentlyUsedModel, isConfigured, providerModel, shouldAutostart, startGeneration]);
// Simple scroll event listener
useEffect(() => {
@@ -280,7 +326,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
if (isNearBottom) {
container.scrollTop = container.scrollHeight;
}
}
}, [messages, streamingMessage, isLoading]);
@@ -295,7 +340,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
return () => clearTimeout(timer);
}
}, [projectId, scrolledProjects]);
}, [projectId, scrolledProjects, scrollToBottom]);
const handleFileSelect = (file: File) => {
setAttachedFiles(prev => [...prev, file]);
@@ -305,8 +350,62 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
setAttachedFiles(prev => prev.filter(file => file !== fileToRemove));
};
const handleSend = async () => {
if ((!input.trim() && attachedFiles.length === 0) || isLoading || !providerModel.trim()) return;
// Drag and drop handlers
const handleDragEnter = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(true);
};
const handleDragOver = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
if (!isDragOver) {
setIsDragOver(true);
}
};
const handleDragLeave = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
// Only reset drag state if we're actually leaving the container
// This prevents flickering when dragging over child elements
const container = e.currentTarget;
const relatedTarget = e.relatedTarget as Node;
if (!container.contains(relatedTarget)) {
setIsDragOver(false);
}
};
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(false);
if (isLoading || !providerModel.trim()) return;
const files = Array.from(e.dataTransfer.files);
if (files.length === 0) return;
// Add all files without validation
setAttachedFiles(prev => [...prev, ...files]);
};
const send = useCallback(async (input: string, attachedFiles: File[]) => {
if ((!input.trim() && attachedFiles.length === 0) || isLoading) return;
// If AI is not configured, show onboarding dialog
if (!isConfigured) {
setShowOnboarding(true);
return;
}
// If configured but no model selected, don't proceed
if (!providerModel.trim()) return;
setAIError(null);
const modelToUse = providerModel.trim();
@@ -350,15 +449,14 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
// Add model to recently used when sending a message
addRecentlyUsedModel(modelToUse);
try {
// Send as text parts if we have multiple parts, otherwise send as string for simplicity
const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts;
await sendMessage(messageContent, modelToUse);
} catch (error) {
console.error('AI chat error:', error);
// Error handling is done in the useAIChat hook
}
};
// Send as text parts if we have multiple parts, otherwise send as string for simplicity
const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts;
await sendMessage(messageContent, modelToUse);
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage]);
const handleSend = useCallback(async () => {
await send(input, attachedFiles);
}, [input, attachedFiles, send]);
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
@@ -396,6 +494,16 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
};
// Handle textarea focus - show onboarding if not configured
const handleTextareaFocus = () => {
if (!isConfigured) {
setShowOnboarding(true);
}
if (onFirstInteraction) {
onFirstInteraction();
}
};
// Handle first user interaction to enable audio context
const handleFirstInteraction = () => {
// This will be handled automatically by the useKeepAlive hook
@@ -412,29 +520,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
}), [internalStartNewSession]);
if (!isConfigured) {
return (
<div className="h-full flex flex-col">
<div className="flex-1 flex items-center justify-center bg-gradient-to-br from-primary/5 to-accent/5">
<div className="text-center space-y-4 max-w-md mx-auto p-6">
<div className="text-4xl mb-4">🤖</div>
<div>
<h3 className="text-lg font-semibold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">{t('aiNotConfigured')}</h3>
<p className="text-sm text-muted-foreground mb-4">
{t('configureAI')}
</p>
<p className="text-sm text-muted-foreground">
{t('useMenuForAI')}
</p>
</div>
</div>
</div>
</div>
);
}
return (
<div className="h-full flex flex-col relative">
@@ -444,7 +529,9 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
{messages.length === 0 && !streamingMessage && !isLoading && (
<div className="flex-1 flex items-center justify-center min-h-[400px]">
<div className="text-center space-y-4 max-w-md mx-auto">
<div className="text-6xl mb-6">🎭</div>
<div className="mb-6">
<ShakespeareLogo className="w-16 h-16 mx-auto" />
</div>
<div>
<h3 className="text-xl font-semibold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
{t('welcomeToShakespeare')}
@@ -464,11 +551,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
)}
{messages.map((message, index) => {
// Skip assistant messages with no content
if (message.role === 'assistant' && assistantContentEmpty(message.content)) {
return null;
}
// Find the corresponding tool call for tool messages
let toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined = undefined;
if (message.role === 'tool') {
@@ -492,12 +574,23 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
})}
{streamingMessage && (
streamingMessage.content || streamingMessage.reasoning_content ? (
<AIMessageItem
key="streaming-message"
message={streamingMessage}
isCurrentlyLoading={isLoading}
reasoningContent={streamingMessage.reasoning_content}
/>
<>
<AIMessageItem
key="streaming-message"
message={streamingMessage}
isCurrentlyLoading={isLoading}
/>
{/* Show loading skeleton if AI appears stuck generating tools */}
{isStuck && (
<div key="stuck-loading-skeleton" className="flex">
<div className="flex-1 min-w-0">
<div className="text-sm space-y-2">
<Skeleton className="h-4 w-3/4" />
</div>
</div>
</div>
)}
</>
) : (
!(streamingMessage?.tool_calls?.[0]?.type === 'function') && (
<div key="streaming-loading" className="flex">
@@ -520,6 +613,18 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</div>
</div>
)}
{/* Error Alert (Console or AI) */}
{displayError && (
<Quilly
error={displayError}
onDismiss={handleErrorDismiss}
onNewChat={onNewChat}
onOpenModelSelector={openModelSelector}
onRequestConsoleErrorHelp={handleConsoleErrorHelp}
providerModel={providerModel}
/>
)}
</div>
</div>
@@ -539,17 +644,31 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<div className="border-t p-4">
{/* Chat Input Container */}
<div className="flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all">
<div
className={`flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
}`}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
<Textarea
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onFocus={handleFirstInteraction}
placeholder={providerModel.trim() ? t('askToAddFeatures') : t('selectModelFirst')}
onFocus={handleTextareaFocus}
placeholder={
!isConfigured
? t('askToAddFeatures')
: providerModel.trim()
? t('askToAddFeatures')
: t('selectModelFirst')
}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isLoading || !providerModel.trim()}
disabled={isLoading || (isConfigured && !providerModel.trim())}
rows={1}
aria-label="Chat message input"
style={{
height: 'auto',
minHeight: '96px'
@@ -620,6 +739,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
className="w-full"
disabled={isLoading}
placeholder={t('chooseModel')}
open={isModelSelectorOpen}
onOpenChange={setIsModelSelectorOpen}
/>
</div>
@@ -638,7 +759,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<Button
onClick={handleSend}
onMouseDown={handleFirstInteraction}
disabled={(!input.trim() && attachedFiles.length === 0) || !providerModel.trim()}
disabled={(!input.trim() && attachedFiles.length === 0) || (isConfigured && !providerModel.trim())}
size="sm"
className="size-8 [&_svg]:size-5 rounded-full p-0"
>
@@ -649,6 +770,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</div>
</div>
</div>
{/* Onboarding Dialog */}
<OnboardingDialog
open={showOnboarding}
onOpenChange={setShowOnboarding}
/>
</div>
);
});
+508 -234
View File
@@ -3,21 +3,32 @@ 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, ScrollBar } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { FolderOpen, ArrowLeft, X, Bug, Copy, Check } 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';
@@ -25,6 +36,10 @@ const IFRAME_DOMAIN = import.meta.env.VITE_IFRAME_DOMAIN || 'local-shakespeare.d
interface PreviewPaneProps {
projectId: string;
activeTab: 'preview' | 'code';
onToggleView?: () => void;
projectName?: string;
onFirstInteraction?: () => void;
isPreviewable?: boolean;
}
interface JSONRPCRequest {
@@ -57,29 +72,57 @@ interface JSONRPCResponse {
id: number;
}
interface ConsoleMessage {
id: number;
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
message: string;
}
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 [consoleMessages, setConsoleMessages] = useState<ConsoleMessage[]>([]);
const [copiedMessageId, setCopiedMessageId] = useState<number | null>(null);
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 {
@@ -129,68 +172,23 @@ 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);
}
}, []);
const navigateToPath = useCallback((path: string) => {
if (iframeRef.current) {
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
const newUrl = `${baseUrl}${path}`;
iframeRef.current.src = newUrl;
setCurrentPath(path);
// Update navigation history
const newHistory = navigationHistory.slice(0, historyIndex + 1);
newHistory.push(path);
setNavigationHistory(newHistory);
setHistoryIndex(newHistory.length - 1);
}
}, [projectId, navigationHistory, historyIndex]);
const goBack = useCallback(() => {
if (historyIndex > 0) {
const newIndex = historyIndex - 1;
const path = navigationHistory[newIndex];
setHistoryIndex(newIndex);
setCurrentPath(path);
if (iframeRef.current) {
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
const newUrl = `${baseUrl}${path}`;
iframeRef.current.src = newUrl;
}
}
}, [historyIndex, navigationHistory, projectId]);
const goForward = useCallback(() => {
if (historyIndex < navigationHistory.length - 1) {
const newIndex = historyIndex + 1;
const path = navigationHistory[newIndex];
setHistoryIndex(newIndex);
setCurrentPath(path);
if (iframeRef.current) {
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
const newUrl = `${baseUrl}${path}`;
iframeRef.current.src = newUrl;
}
}
}, [historyIndex, navigationHistory, projectId]);
}, [projectId]);
const sendResponse = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
console.log(`Sending response to iframe:`, message);
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
}
@@ -219,24 +217,98 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
normalizedLevel = params.level as ConsoleMessage['level'];
}
const newConsoleMessage: ConsoleMessage = {
id: Date.now(),
level: normalizedLevel,
message: params.message,
};
setConsoleMessages(prev => [...prev, newConsoleMessage]);
// 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);
@@ -259,6 +331,9 @@ 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 bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath);
@@ -279,11 +354,27 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
});
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 bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html');
console.log(`Serving index.html fallback for: ${path}`);
@@ -303,8 +394,6 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
});
} catch {
// Even index.html doesn't exist
console.log(`No files found, returning 404 for: ${path}`);
sendResponse({
jsonrpc: '2.0',
result: {
@@ -348,12 +437,14 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
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, handleConsoleMessage, projectId]);
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId]);
useEffect(() => {
if (selectedFile) {
@@ -361,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]);
@@ -372,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);
@@ -399,151 +503,239 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
};
const ConsoleDropdown = () => {
const getLevelColor = (level: ConsoleMessage['level']) => {
switch (level) {
case 'error': return 'text-red-500';
case 'warn': return 'text-yellow-500';
case 'info': return 'text-blue-500';
case 'debug': return 'text-gray-500';
default: return 'text-gray-400';
}
};
const [isOpen, setIsOpen] = useState(false);
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
const getLevelIcon = (level: ConsoleMessage['level']) => {
switch (level) {
case 'error': return '!';
case 'warn': return '⚠';
case 'info': return 'ℹ';
case 'debug': return '🔍';
default: return '•';
}
};
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 clearConsole = () => {
setConsoleMessages([]);
};
const consoleMessages = getConsoleMessages();
const messageCount = consoleMessages.length;
const hasErrors = consoleMessages.some(msg => msg.level === 'error');
const copyMessageToClipboard = async (msg: ConsoleMessage) => {
try {
// Create a formatted string with all message details
const formattedMessage = `[${msg.level.toUpperCase()}] ${msg.message}`;
await navigator.clipboard.writeText(formattedMessage);
setCopiedMessageId(msg.id);
// Reset the copied state after 2 seconds
setTimeout(() => {
setCopiedMessageId(null);
}, 2000);
} catch (error) {
console.error('Failed to copy message to clipboard:', error);
}
};
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm" className="h-8 w-8 p-0 relative">
<Bug className="h-4 w-4" />
{consoleMessages.some(msg => msg.level === 'error') && (
<span className="absolute bottom-0 left-0 h-2 w-2 bg-red-500 rounded-full"></span>
)}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-96 max-w-96 max-h-96 overflow-x-hidden">
<div className="flex items-center justify-between p-2 border-b">
<span className="font-medium text-sm">Console Output ({consoleMessages.length})</span>
<Button variant="ghost" size="sm" onClick={clearConsole}>
<X className="h-3 w-3" />
return (
<Popover open={isOpen} onOpenChange={setIsOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 relative hover:bg-accent hover:text-accent-foreground transition-colors"
>
<Bug className="h-4 w-4" />
{hasErrors && (
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
)}
</Button>
</div>
<ScrollArea className="h-80 w-full max-w-full overflow-x-hidden">
<div className="space-y-1 p-2 w-full max-w-full overflow-x-hidden">
{consoleMessages.length === 0 ? (
<div className="text-center text-muted-foreground text-sm py-4">
No console messages
</div>
) : (
consoleMessages.map((msg) => (
<div
key={msg.id}
className={`text-xs font-mono p-2 rounded ${getLevelColor(msg.level)} bg-muted/50 group relative w-full overflow-hidden`}
>
<div className="flex items-start justify-between w-full">
<div className="whitespace-pre-wrap break-all flex-1 pr-2 overflow-x-hidden">{getLevelIcon(msg.level)} {msg.message}</div>
</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={() => copyMessageToClipboard(msg)}
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex-shrink-0"
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"
>
{copiedMessageId === msg.id ? (
<Check className="h-3 w-3 text-green-500" />
{copiedMessageIndex === index ? (
<Check className="h-2 w-2 text-success" />
) : (
<Copy className="h-3 w-3" />
<Copy className="h-2 w-2" />
)}
</Button>
</div>
</div>
))
)}
))
)}
</div>
</div>
</ScrollArea>
</DropdownMenuContent>
</DropdownMenu>
);
};
{/* Close button */}
<button
onClick={() => setIsOpen(false)}
className="absolute top-2 right-2 h-8 w-8 p-0 bg-muted/50 hover:bg-muted/70 rounded-md z-10 flex items-center justify-center border"
>
<X className="h-5 w-5 text-muted-foreground" />
</button>
</PopoverContent>
</Popover>
);
};
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 border-b w-full">
<BrowserAddressBar
currentPath={currentPath}
onNavigate={navigateToPath}
onRefresh={refreshIframe}
onBack={goBack}
onForward={goForward}
canGoBack={historyIndex > 0}
canGoForward={historyIndex < navigationHistory.length - 1}
extraContent={<ConsoleDropdown />}
/>
</div>
<iframe
ref={iframeRef}
src={`https://${projectId}.${IFRAME_DOMAIN}${currentPath}`}
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">{t('projectPreview')}</h3>
<p className="text-muted-foreground mb-4">
{t('buildProjectToSeePreview')}
</p>
</div>
{/* Content area */}
<div className="flex-1">
{hasBuiltProject ? (
<iframe
ref={iframeRef}
src={`https://${projectId}.${IFRAME_DOMAIN}/`}
className="w-full h-full border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin"
/>
) : (
<div className="h-full flex items-center justify-center bg-muted">
<div className="text-center">
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
<p className="text-muted-foreground mb-4">
{t('buildProjectToSeePreview')}
</p>
<Button
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>
</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">
<div className="flex items-center justify-between">
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">{t('fileExplorer')}</h3>
<GitStatusIndicator projectId={projectId} />
</div>
</div>
<ScrollArea className="flex-1">
<div className="flex-1 relative min-h-0">
<ScrollArea className="h-full">
<ScrollBar orientation="horizontal" />
<div className="min-w-max">
<FileTree
@@ -553,6 +745,34 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
/>
</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>
</>
) : (
<>
@@ -602,49 +822,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">
<div className="flex items-center justify-between">
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">{t('fileExplorer')}</h3>
<GitStatusIndicator projectId={projectId} />
</div>
<div 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)]">
<ScrollBar orientation="horizontal" />
<div className="min-w-max">
<FileTree
projectId={projectId}
onFileSelect={handleFileSelect}
selectedFile={selectedFile}
/>
</div>
</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}
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 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}
/>
);
}
+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>
);
}
+187 -19
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 { useGitStatus } from '@/hooks/useGitStatus';
interface GitCommit {
oid: string;
@@ -43,9 +44,11 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
const setIsOpen = onOpenChange || setInternalOpen;
const [isRollingBack, setIsRollingBack] = useState<string | null>(null);
const [expandedCommits, setExpandedCommits] = useState<Set<string>>(new Set());
const git = useGit();
const { fs } = useFS();
const { git } = useGit();
const { toast } = useToast();
const navigate = useNavigate();
const { data: gitStatus } = useGitStatus(projectId);
const loadGitHistory = useCallback(async () => {
setIsLoading(true);
@@ -214,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);
@@ -227,7 +231,106 @@ ${commitsToRevert.map(c => {
} finally {
setIsRollingBack(null);
}
}, [git, 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) {
@@ -289,18 +392,18 @@ ${commitsToRevert.map(c => {
</Button>
</DialogTrigger>
)}
<DialogContent className="max-w-4xl max-h-[80vh]">
<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">
@@ -329,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);
@@ -340,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 && (
@@ -372,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
@@ -430,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>
+2 -2
View File
@@ -35,12 +35,12 @@ vi.mock('@/components/RelaySelector', () => ({
)
}));
vi.mock('./LoginDialog', () => ({
vi.mock('./SimpleLoginDialog', () => ({
default: ({ isOpen }: { isOpen: boolean; onClose: () => void }) =>
isOpen ? <div data-testid="login-dialog">Login Dialog</div> : null
}));
vi.mock('./SignupDialog', () => ({
vi.mock('./SimpleSignupDialog', () => ({
default: ({ isOpen }: { isOpen: boolean; onClose: () => void }) =>
isOpen ? <div data-testid="signup-dialog">Signup Dialog</div> : null
}));
+15 -11
View File
@@ -12,8 +12,8 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu.tsx';
import { Avatar, AvatarFallback } from '@/components/ui/avatar.tsx';
import LoginDialog from './LoginDialog';
import SignupDialog from './SignupDialog';
import SimpleLoginDialog from './SimpleLoginDialog';
import SimpleSignupDialog from './SimpleSignupDialog';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
import { AccountSwitcher } from './AccountSwitcher';
import { cn } from '@/lib/utils';
@@ -70,13 +70,6 @@ export function LoginArea({ className }: LoginAreaProps) {
<span>{t('help')}</span>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => setLoginDialogOpen(true)}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
>
<User className='w-4 h-4' />
<span>{t('logIn')}</span>
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setSignupDialogOpen(true)}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
@@ -84,20 +77,31 @@ export function LoginArea({ className }: LoginAreaProps) {
<UserPlus className='w-4 h-4' />
<span>{t('signUp')}</span>
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setLoginDialogOpen(true)}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
>
<User className='w-4 h-4' />
<span>{t('logIn')}</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
<LoginDialog
<SimpleLoginDialog
isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)}
onLogin={handleLogin}
onSignup={() => setSignupDialogOpen(true)}
/>
<SignupDialog
<SimpleSignupDialog
isOpen={signupDialogOpen}
onClose={() => setSignupDialogOpen(false)}
onLogin={() => {
setSignupDialogOpen(false);
setLoginDialogOpen(true);
}}
/>
</div>
);
+349
View File
@@ -0,0 +1,349 @@
import React, { useState, useEffect, useRef } from 'react';
import { Cloud, Upload } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
// Alert components removed as they're not used in the simplified design
import { useLoginActions } from '@/hooks/useLoginActions';
import { cn } from '@/lib/utils';
// Only using key-add step now
interface SimpleLoginDialogProps {
isOpen: boolean;
onClose: () => void;
onLogin: () => void;
onSignup?: () => void;
}
const validateNsec = (nsec: string) => {
return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec);
};
const validateBunkerUri = (uri: string) => {
return uri.startsWith('bunker://');
};
const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
isOpen,
onClose,
onLogin,
onSignup
}) => {
// Removed step state - we only have one step now
const [isLoading, setIsLoading] = useState(false);
const [isFileLoading, setIsFileLoading] = useState(false);
const [nsec, setNsec] = useState('');
const [bunkerUri, setBunkerUri] = useState('');
const [activeTab, setActiveTab] = useState<'nsec' | 'bunker'>('nsec');
const [errors, setErrors] = useState<{
nsec?: string;
bunker?: string;
extension?: string;
file?: string;
}>({});
const fileInputRef = useRef<HTMLInputElement>(null);
const login = useLoginActions();
// Reset state when dialog opens/closes
useEffect(() => {
if (isOpen) {
setIsLoading(false);
setIsFileLoading(false);
setNsec('');
setBunkerUri('');
setActiveTab('nsec');
setErrors({});
// Reset file input
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
}
}, [isOpen]);
const handleExtensionLogin = async () => {
setIsLoading(true);
setErrors(prev => ({ ...prev, extension: undefined }));
try {
if (!('nostr' in window)) {
throw new Error('Nostr extension not found. Please install a NIP-07 extension.');
}
await login.extension();
onLogin();
onClose();
} catch (e: unknown) {
const error = e as Error;
setErrors(prev => ({
...prev,
extension: error instanceof Error ? error.message : 'Extension login failed'
}));
} finally {
setIsLoading(false);
}
};
const handleKeyLogin = () => {
if (!nsec.trim()) {
setErrors(prev => ({ ...prev, nsec: 'Please enter your secret key' }));
return;
}
if (!validateNsec(nsec)) {
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
return;
}
executeLogin(nsec);
};
const handleBunkerLogin = async () => {
if (!bunkerUri.trim()) {
setErrors(prev => ({ ...prev, bunker: 'Please enter a bunker URI' }));
return;
}
if (!validateBunkerUri(bunkerUri)) {
setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' }));
return;
}
setIsLoading(true);
setErrors(prev => ({ ...prev, bunker: undefined }));
try {
await login.bunker(bunkerUri);
onLogin();
onClose();
setBunkerUri('');
} catch {
setErrors(prev => ({
...prev,
bunker: 'Failed to connect to bunker. Please check the URI.'
}));
} finally {
setIsLoading(false);
}
};
const executeLogin = (key: string) => {
setIsLoading(true);
setErrors({});
// Use a timeout to allow the UI to update before the synchronous login call
setTimeout(() => {
try {
login.nsec(key);
onLogin();
onClose();
} catch {
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
setIsLoading(false);
}
}, 50);
};
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setIsFileLoading(true);
setErrors({});
const reader = new FileReader();
reader.onload = (event) => {
setIsFileLoading(false);
const content = event.target?.result as string;
if (content) {
const trimmedContent = content.trim();
if (validateNsec(trimmedContent)) {
executeLogin(trimmedContent);
} else {
setErrors({ file: 'File does not contain a valid secret key.' });
}
} else {
setErrors({ file: 'Could not read file content.' });
}
};
reader.onerror = () => {
setIsFileLoading(false);
setErrors({ file: 'Failed to read file.' });
};
reader.readAsText(file);
};
const handleSignupClick = () => {
onClose();
if (onSignup) {
onSignup();
}
};
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-sm">
<DialogHeader>
<DialogTitle className="text-center">Log in</DialogTitle>
</DialogHeader>
<div className="flex flex-col items-center space-y-6 py-6">
<div className="text-center">
<h3 className="font-semibold mb-2">Welcome back to Shakespeare</h3>
<p className="text-sm text-muted-foreground">Sign in to your existing account</p>
</div>
<div className="w-40 h-40 flex items-center justify-center">
<div className="w-40 h-40 bg-primary/10 rounded-full flex items-center justify-center">
<span className="text-8xl">🔑</span>
</div>
</div>
<div className="w-full space-y-4">
{/* Tab selector */}
<div className="flex space-x-1 bg-muted rounded-lg p-1">
<button
onClick={() => setActiveTab('nsec')}
className={cn(
"flex-1 px-3 py-2 text-sm font-medium rounded-md transition-colors",
activeTab === 'nsec'
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground"
)}
>
Secret Key
</button>
<button
onClick={() => setActiveTab('bunker')}
className={cn(
"flex-1 px-3 py-2 text-sm font-medium rounded-md transition-colors",
activeTab === 'bunker'
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground"
)}
>
Bunker
</button>
</div>
{activeTab === 'nsec' && (
<div className="space-y-4">
<div className="space-y-2">
<Input
type="password"
value={nsec}
onChange={(e) => {
setNsec(e.target.value);
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
}}
placeholder="nsec1..."
className={errors.nsec ? 'border-red-500' : ''}
/>
{errors.nsec && (
<p className="text-sm text-red-500">{errors.nsec}</p>
)}
</div>
<div className="flex space-x-2">
<Button
size="lg"
onClick={handleKeyLogin}
disabled={isLoading || !nsec.trim()}
className="flex-1"
>
{isLoading ? 'Verifying...' : 'Add Key'}
</Button>
<input
type="file"
accept=".txt"
className="hidden"
ref={fileInputRef}
onChange={handleFileUpload}
/>
<Button
variant="outline"
size="lg"
onClick={() => fileInputRef.current?.click()}
disabled={isLoading || isFileLoading}
className="px-3"
>
<Upload className="w-4 h-4" />
</Button>
</div>
{errors.file && (
<p className="text-sm text-red-500 text-center">{errors.file}</p>
)}
</div>
)}
{activeTab === 'bunker' && (
<div className="space-y-4">
<div className="space-y-2">
<Input
value={bunkerUri}
onChange={(e) => {
setBunkerUri(e.target.value);
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
}}
placeholder="bunker://"
className={errors.bunker ? 'border-red-500' : ''}
/>
{errors.bunker && (
<p className="text-sm text-red-500">{errors.bunker}</p>
)}
</div>
<Button
size="lg"
onClick={handleBunkerLogin}
disabled={isLoading || !bunkerUri.trim()}
className="w-full"
>
<Cloud className="w-4 h-4 mr-2" />
{isLoading ? 'Connecting...' : 'Connect'}
</Button>
</div>
)}
<div className="relative">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t"></div>
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-background px-2 text-muted-foreground">or</span>
</div>
</div>
{/* Extension indicator - only show if extension is detected */}
{window.nostr && (
<div className="rounded-lg bg-muted p-3">
<p className="text-xs text-center">
<button
onClick={handleExtensionLogin}
className="text-blue-500 hover:underline"
disabled={isLoading}
>
Sign in with browser extension
</button>
</p>
</div>
)}
<div className="flex justify-center space-x-2 text-xs">
<span className="text-muted-foreground">New to Shakespeare?</span>
<button
onClick={handleSignupClick}
className="text-blue-500 hover:underline"
>
Create Account
</button>
</div>
</div>
</div>
</DialogContent>
</Dialog>
);
};
export default SimpleLoginDialog;
+263
View File
@@ -0,0 +1,263 @@
import React, { useState, useEffect, useMemo } from 'react';
import { Download, UserPlus } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { toast } from '@/hooks/useToast';
import { useLoginActions } from '@/hooks/useLoginActions';
import { generateSecretKey, nip19 } from 'nostr-tools';
import { cn } from '@/lib/utils';
type Step = 'key' | 'keygen';
interface SimpleSignupDialogProps {
isOpen: boolean;
onClose: () => void;
onComplete?: () => void;
onLogin?: () => void;
}
const SimpleSignupDialog: React.FC<SimpleSignupDialogProps> = ({
isOpen,
onClose,
onComplete,
onLogin
}) => {
const [step, setStep] = useState<Step>('key');
const [isLoading, setIsLoading] = useState(false);
const [downloaded, setDownloaded] = useState(false);
const login = useLoginActions();
// Generate key once and keep it stable
const secretKey = useMemo(() => generateSecretKey(), []);
const nsec = useMemo(() => nip19.nsecEncode(secretKey), [secretKey]);
// Reset state when dialog opens/closes
useEffect(() => {
if (isOpen) {
// Always start with key generation as the default experience
setStep('key');
setIsLoading(false);
setDownloaded(false);
}
}, [isOpen]);
const handleExtensionSignup = async () => {
setIsLoading(true);
try {
if (!('nostr' in window)) {
throw new Error('Nostr extension not found. Please install a NIP-07 extension.');
}
await login.extension();
onClose();
if (onComplete) {
setTimeout(() => {
onComplete();
}, 600);
}
} catch (e: unknown) {
const error = e as Error;
toast({
title: 'Extension signup failed',
description: error instanceof Error ? error.message : 'Extension signup failed',
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
};
const handleDownload = () => {
try {
const blob = new Blob([nsec], { type: 'text/plain; charset=utf-8' });
const url = globalThis.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'secret-key.txt';
a.style.display = 'none';
document.body.appendChild(a);
a.click();
globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a);
setDownloaded(true);
toast({
title: 'Secret Key Saved!',
description: 'Your key has been safely stored.',
});
} catch {
toast({
title: 'Download failed',
description: 'Could not download the key file. Please copy it manually.',
variant: 'destructive',
});
}
};
const handleNext = async () => {
setIsLoading(true);
try {
login.nsec(nsec);
// Mark signup completion time for fallback welcome modal
localStorage.setItem('signup_completed', Date.now().toString());
onClose();
if (onComplete) {
setTimeout(() => {
onComplete();
}, 600);
}
} catch {
toast({
title: 'Login Failed',
description: 'Failed to login with the generated key. Please try again.',
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
};
const handleLoginClick = () => {
onClose();
if (onLogin) {
onLogin();
}
};
if (step === 'key') {
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-sm">
<DialogHeader>
<DialogTitle className="text-center">Sign up</DialogTitle>
</DialogHeader>
<div className="flex flex-col items-center space-y-6 py-6">
<div className="text-center">
<h3 className="font-semibold mb-2">Welcome to Shakespeare</h3>
<p className="text-sm text-muted-foreground">Create your account to get started</p>
</div>
<div className="w-40 h-40 flex items-center justify-center">
<div className="w-40 h-40 bg-primary/10 rounded-full flex items-center justify-center">
<span className="text-8xl">🔑</span>
</div>
</div>
<div className="flex flex-col space-y-3 w-full">
<Button
size="lg"
onClick={() => setStep('keygen')}
className="w-full"
>
<UserPlus className="w-4 h-4 mr-2" />
Create New Account
</Button>
<Button
variant="outline"
onClick={handleLoginClick}
className="w-full"
>
I already have an account
</Button>
</div>
{/* Extension indicator - only show if extension is detected */}
{window.nostr && (
<>
<div className="relative w-full">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t"></div>
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-background px-2 text-muted-foreground">or</span>
</div>
</div>
<div className="rounded-lg bg-muted p-3 w-full">
<p className="text-xs text-center">
<button
onClick={handleExtensionSignup}
className="text-blue-500 hover:underline"
disabled={isLoading}
>
Sign up with browser extension
</button>
</p>
</div>
</>
)}
</div>
</DialogContent>
</Dialog>
);
}
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-sm">
<DialogHeader>
<DialogTitle className="text-center">Your new key</DialogTitle>
</DialogHeader>
<div className="flex flex-col items-center space-y-6 py-6">
<div className="w-40 h-40 flex items-center justify-center">
<div className="w-40 h-40 bg-primary/10 rounded-full flex items-center justify-center">
<span className="text-8xl">🔑</span>
</div>
</div>
<div className="w-full space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium">Secret Key</label>
<Input
type="password"
value={nsec}
readOnly
className="font-mono"
/>
</div>
<div className="rounded-xl bg-muted p-4">
<p className="text-xs text-justify">
Back up your secret key in a secure place. If lost, your account cannot be recovered.
Never share your secret key with anyone.
</p>
</div>
<div className="flex space-x-3 justify-center">
<Button
variant="outline"
size="lg"
onClick={handleDownload}
className="flex-1"
>
<Download className="w-4 h-4 mr-2" />
Download key
</Button>
<Button
size="lg"
onClick={handleNext}
disabled={!downloaded || isLoading}
className={cn(
"flex-1",
!downloaded && "opacity-50 cursor-not-allowed"
)}
title={!downloaded ? "Download your key to continue" : ""}
>
{isLoading ? 'Setting up...' : 'Next'}
</Button>
</div>
</div>
</div>
</DialogContent>
</Dialog>
);
};
export default SimpleSignupDialog;
+63
View File
@@ -0,0 +1,63 @@
import React from 'react';
interface QuillySVGProps extends React.SVGProps<SVGSVGElement> {
className?: string;
fillColor?: string;
}
export function QuillySVG({ className = "w-4 h-4", fillColor = "currentColor", ...props }: QuillySVGProps) {
return (
<svg
className={className}
viewBox="140 30 220 420"
xmlns="http://www.w3.org/2000/svg"
{...props}
>
{/* Main quill head/top part */}
<path fill={fillColor} d="M 241.5,33.5 C 246.833,33.5 252.167,33.5 257.5,33.5C 269.508,34.507 280.508,38.3403 290.5,45C 294,47.3342 297,50.1675 299.5,53.5C 298.21,54.0577 297.377,55.0577 297,56.5C 294.888,52.8729 293.221,52.8729 292,56.5C 291.086,55.3463 290.253,55.513 289.5,57C 292.321,58.6213 292.987,60.788 291.5,63.5C 281.078,49.3135 266.911,42.3135 249,42.5C 229.512,42.5414 213.845,50.2081 202,65.5C 196.198,75.0401 193.698,85.3734 194.5,96.5C 193.546,91.1876 192.546,85.1876 191.5,78.5C 189.508,78.6715 187.842,78.0049 186.5,76.5C 183.867,77.7822 183.867,79.1156 186.5,80.5C 185.234,81.3624 183.901,82.0291 182.5,82.5C 183.047,79.2976 184.047,76.2976 185.5,73.5C 186.906,73.0269 187.573,72.0269 187.5,70.5C 188.498,66.4945 190.498,63.1612 193.5,60.5C 194.906,60.0269 195.573,59.0269 195.5,57.5C 196.833,55.8333 198.167,54.1667 199.5,52.5C 211.392,41.6322 225.392,35.2989 241.5,33.5 Z" />
{/* Main quill feather/plume part */}
<path fill={fillColor} d="M 299.5,53.5 C 305.302,58.4362 309.635,64.4362 312.5,71.5C 312.343,72.8734 312.51,74.2068 313,75.5C 313.876,77.7582 315.043,79.7582 316.5,81.5C 318.737,87.0285 320.903,92.6952 323,98.5C 328.732,104.725 334.232,111.058 339.5,117.5C 339.427,119.027 340.094,120.027 341.5,120.5C 343.293,122.426 344.293,124.759 344.5,127.5C 345.22,133.138 345.553,138.804 345.5,144.5C 344.999,150.505 342.499,155.505 338,159.5C 338.33,165.569 338.164,171.569 337.5,177.5C 336.732,178.263 336.232,179.263 336,180.5C 335.261,178.779 334.427,177.113 333.5,175.5C 333.034,177.705 333.034,179.705 333.5,181.5C 332.23,180.438 331.063,179.438 330,178.5C 329.667,178.833 329.333,179.167 329,179.5C 328.333,178.5 328.333,177.5 329,176.5C 329.718,177.451 330.551,177.617 331.5,177C 330.418,175.67 329.751,174.17 329.5,172.5C 329.799,170.396 329.466,168.396 328.5,166.5C 317.499,170.764 306.666,170.431 296,165.5C 295.617,166.056 295.117,166.389 294.5,166.5C 293.533,167.806 292.199,168.473 290.5,168.5C 290.688,170.103 290.188,171.437 289,172.5C 287.477,170.431 286.643,168.097 286.5,165.5C 287.351,161.435 288.517,157.435 290,153.5C 293.306,151.968 296.806,150.801 300.5,150C 303.708,147.229 305.708,143.729 306.5,139.5C 305.527,137.36 304.027,135.693 302,134.5C 299.684,135.367 297.684,134.701 296,132.5C 293.685,129.223 292.351,125.556 292,121.5C 292.692,108.983 293.858,96.4825 295.5,84C 295.554,78.7227 294.887,73.556 293.5,68.5C 293.771,66.6203 293.104,65.287 291.5,64.5C 291.5,64.1667 291.5,63.8333 291.5,63.5C 292.987,60.788 292.321,58.6213 289.5,57C 290.253,55.513 291.086,55.3463 292,56.5C 293.221,52.8729 294.888,52.8729 297,56.5C 297.377,55.0577 298.21,54.0577 299.5,53.5 Z" />
{/* Body/torso part */}
<path fill={fillColor} d="M 194.5,96.5 C 205.307,90.5958 215.64,91.2624 225.5,98.5C 227.97,102.11 229.304,106.11 229.5,110.5C 227.359,120.522 224.859,130.522 222,140.5C 221.176,143.882 221.343,147.216 222.5,150.5C 223.607,151.022 224.774,151.355 226,151.5C 229.926,150.727 233.759,149.727 237.5,148.5C 240.135,147.461 242.135,145.794 243.5,143.5C 247.778,147.659 247.111,151.159 241.5,154C 245.303,156.071 248.97,158.404 252.5,161C 255.77,162.66 259.103,162.994 262.5,162C 263.935,164.267 263.602,166.267 261.5,168C 258.448,169.211 255.281,170.045 252,170.5C 244.065,169.521 236.398,167.521 229,164.5C 222.843,167.108 216.51,169.108 210,170.5C 207.815,170.079 205.649,169.579 203.5,169C 202.424,167.274 202.257,165.441 203,163.5C 207.408,161.43 211.575,158.93 215.5,156C 213.504,151.729 213.004,147.229 214,142.5C 216.819,132.558 219.319,122.558 221.5,112.5C 221.81,108.306 220.143,105.139 216.5,103C 208.667,100.569 201.501,101.736 195,106.5C 191.661,123.896 191.827,141.229 195.5,158.5C 194.895,160.026 193.729,161.026 192,161.5C 191.14,156.863 188.307,154.697 183.5,155C 184.833,154.333 184.833,153.667 183.5,153C 181.934,152.7 180.601,153.2 179.5,154.5C 166.076,151.07 158.742,142.403 157.5,128.5C 158.051,123.851 159.385,119.518 161.5,115.5C 162.906,115.027 163.573,114.027 163.5,112.5C 167.455,107.373 171.622,102.373 176,97.5C 178.486,92.5113 180.652,87.5113 182.5,82.5C 183.901,82.0291 185.234,81.3624 186.5,80.5C 183.867,79.1156 183.867,77.7822 186.5,76.5C 187.842,78.0049 189.508,78.6715 191.5,78.5C 192.546,85.1876 193.546,91.1876 194.5,96.5 Z" />
{/* Additional body details */}
<path fill={fillColor} d="M 272.5,96.5 C 273.785,98.4516 275.451,100.118 277.5,101.5C 279.574,103.715 279.907,106.215 278.5,109C 275.758,109.295 273.425,108.462 271.5,106.5C 271.167,105.5 270.5,104.833 269.5,104.5C 265.505,102.79 261.339,101.456 257,100.5C 252.701,101.544 248.535,102.878 244.5,104.5C 237.97,101.229 237.97,97.7288 244.5,94C 251.789,91.6687 259.122,91.3353 266.5,93C 268.727,93.941 270.727,95.1077 272.5,96.5 Z" />
{/* Eyes */}
<path fill={fillColor} d="M 216.5,118.5 C 215.603,119.598 214.77,119.598 214,118.5C 213.59,119.901 213.09,121.234 212.5,122.5C 209.43,122.632 206.43,122.299 203.5,121.5C 200.197,118.335 199.697,114.668 202,110.5C 209.746,105.174 214.913,107.008 217.5,116C 217.257,116.902 216.923,117.735 216.5,118.5 Z" />
<path fill={fillColor} d="M 254.5,107.5 C 262.982,107.765 266.149,112.099 264,120.5C 258.514,126.08 253.514,125.747 249,119.5C 247.486,113.877 249.319,109.877 254.5,107.5 Z" />
{/* Extended body details */}
<path fill={fillColor} d="M 329.5,172.5 C 329.751,174.17 330.418,175.67 331.5,177C 330.551,177.617 329.718,177.451 329,176.5C 328.333,177.5 328.333,178.5 329,179.5C 329.333,179.167 329.667,178.833 330,178.5C 331.063,179.438 332.23,180.438 333.5,181.5C 333.034,179.705 333.034,177.705 333.5,175.5C 334.427,177.113 335.261,178.779 336,180.5C 336.232,179.263 336.732,178.263 337.5,177.5C 337.657,178.873 337.49,180.207 337,181.5C 336.124,183.758 334.957,185.758 333.5,187.5C 331.455,188.923 330.455,190.923 330.5,193.5C 321.603,207.727 311.937,221.394 301.5,234.5C 301.785,232.712 301.452,231.045 300.5,229.5C 297.606,230.909 296.606,230.242 297.5,227.5C 298.167,225.833 298.833,224.167 299.5,222.5C 306.66,212.186 313.827,201.853 321,191.5C 324.438,185.303 327.271,178.969 329.5,172.5 Z" />
{/* Main body section */}
<path fill={fillColor} d="M 195.5,158.5 C 199.127,167.099 202.794,175.765 206.5,184.5C 206.427,186.027 207.094,187.027 208.5,187.5C 213.391,196.567 220.558,202.9 230,206.5C 254.97,200.996 273.803,187.329 286.5,165.5C 286.643,168.097 287.477,170.431 289,172.5C 290.188,171.437 290.688,170.103 290.5,168.5C 292.199,168.473 293.533,167.806 294.5,166.5C 290.454,177.733 283.787,187.233 274.5,195C 259.369,206.946 243.036,214.112 225.5,216.5C 222.868,215.466 220.201,214.466 217.5,213.5C 217.5,212.833 217.5,212.167 217.5,211.5C 211.822,206.986 206.989,201.653 203,195.5C 198.434,187.483 194.434,179.15 191,170.5C 175.85,181.982 164.684,196.482 157.5,214C 164.095,213.183 170.762,212.683 177.5,212.5C 174.695,213.319 171.695,213.819 168.5,214C 170.167,214.333 171.833,214.667 173.5,215C 171.136,216.012 169.802,217.345 169.5,219C 170.448,219.483 171.448,219.649 172.5,219.5C 172.5,219.833 172.5,220.167 172.5,220.5C 164.95,221.221 157.617,222.888 150.5,225.5C 148.06,224.726 146.727,223.06 146.5,220.5C 146.886,218.068 147.553,215.734 148.5,213.5C 149.906,213.027 150.573,212.027 150.5,210.5C 153.084,202.664 156.751,195.331 161.5,188.5C 169.649,178.517 178.649,169.351 188.5,161C 187.62,159.644 187.286,158.144 187.5,156.5C 184.505,156.706 181.838,156.04 179.5,154.5C 180.601,153.2 181.934,152.7 183.5,153C 184.833,153.667 184.833,154.333 183.5,155C 188.307,154.697 191.14,156.863 192,161.5C 193.729,161.026 194.895,160.026 195.5,158.5 Z M 217.5,211.5 C 216.221,212.968 214.554,213.635 212.5,213.5C 211.167,213.5 209.833,213.5 208.5,213.5C 202.225,212.066 195.725,211.4 189,211.5C 184.985,211.501 181.151,211.835 177.5,212.5C 170.762,212.683 164.095,213.183 157.5,214C 164.684,196.482 175.85,181.982 191,170.5C 194.434,179.15 198.434,187.483 203,195.5C 206.989,201.653 211.822,206.986 217.5,211.5 Z" />
{/* Additional body details */}
<path fill={fillColor} d="M 221.5,184.5 C 224.113,183.565 226.779,183.398 229.5,184C 227.709,184.415 226.376,185.415 225.5,187C 228.167,187.667 230.833,187.667 233.5,187C 230.983,183.799 231.483,180.966 235,178.5C 235.667,177.167 235.667,175.833 235,174.5C 232.323,172.959 229.49,171.959 226.5,171.5C 232.176,171.072 237.843,170.905 243.5,171C 245.283,172.067 245.783,173.567 245,175.5C 243.247,176.627 241.413,177.627 239.5,178.5C 238.303,181.934 236.636,185.1 234.5,188C 231.167,188.667 227.833,188.667 224.5,188C 223.29,186.961 222.29,185.794 221.5,184.5 Z" />
{/* Body shading */}
<path fill={fillColor} d="M 226.5,171.5 C 229.49,171.959 232.323,172.959 235,174.5C 235.667,175.833 235.667,177.167 235,178.5C 231.483,180.966 230.983,183.799 233.5,187C 230.833,187.667 228.167,187.667 225.5,187C 226.376,185.415 227.709,184.415 229.5,184C 226.779,183.398 224.113,183.565 221.5,184.5C 221.5,183.833 221.5,183.167 221.5,182.5C 221.656,179.934 221.322,177.434 220.5,175C 220.905,174.055 221.572,173.388 222.5,173C 221.5,172.667 220.5,172.333 219.5,172C 221.81,171.503 224.143,171.337 226.5,171.5 Z" />
{/* More body shading */}
<path fill={fillColor} d="M 226.5,171.5 C 224.143,171.337 221.81,171.503 219.5,172C 220.5,172.333 221.5,172.667 222.5,173C 221.572,173.388 220.905,174.055 220.5,175C 221.322,177.434 221.656,179.934 221.5,182.5C 220.916,180.257 219.75,178.257 218,176.5C 217.333,174.833 217.333,173.167 218,171.5C 220.937,170.183 223.77,170.183 226.5,171.5 Z" />
{/* Lower body/legs area */}
<path fill={fillColor} d="M 177.5,212.5 C 187.85,212.44 198.183,212.774 208.5,213.5C 209.833,213.5 211.167,213.5 212.5,213.5C 214.167,214.833 215.833,214.833 217.5,213.5C 220.201,214.466 222.868,215.466 225.5,216.5C 225.034,218.201 225.034,219.701 225.5,221C 224.429,221.852 223.429,222.685 222.5,223.5C 219.43,223.632 216.43,223.299 213.5,222.5C 213.44,221.957 213.107,221.624 212.5,221.5C 211.516,224.428 211.183,227.428 211.5,230.5C 209.859,228.797 208.859,226.63 208.5,224C 207.258,223.689 206.258,224.189 205.5,225.5C 204.692,225.192 204.025,224.692 203.5,224C 204.833,222.667 204.833,221.333 203.5,220C 201.866,219.506 200.199,219.34 198.5,219.5C 195.102,219.18 191.768,219.513 188.5,220.5C 188.624,221.107 188.957,221.44 189.5,221.5C 188.891,224.878 190.224,226.878 193.5,227.5C 195.288,228.622 197.288,228.789 199.5,228C 200.756,227.583 201.423,226.75 201.5,225.5C 202.995,225.415 203.995,226.081 204.5,227.5C 203.092,228.243 201.759,229.077 200.5,230C 202.249,232.213 204.249,233.213 206.5,233C 204.881,233.236 203.881,234.069 203.5,235.5C 202.5,235.5 201.5,235.5 200.5,235.5C 198.167,235.5 195.833,235.5 193.5,235.5C 193.333,285.168 193.5,334.834 194,384.5C 194.232,385.737 194.732,386.737 195.5,387.5C 197.821,396.471 201.488,404.805 206.5,412.5C 207.956,415.431 207.123,416.098 204,414.5C 203.333,416.167 203.333,417.833 204,419.5C 204.333,418.833 204.667,418.167 205,417.5C 206.109,420.947 205.109,423.614 202,425.5C 200.086,424.324 200.252,423.324 202.5,422.5C 202.167,422.167 201.833,421.833 201.5,421.5C 199.557,421.535 197.557,421.202 195.5,420.5C 186.876,409.404 181.876,396.738 180.5,382.5C 180.5,328.167 180.5,273.833 180.5,219.5C 177.833,219.5 175.167,219.5 172.5,219.5C 171.448,219.649 170.448,219.483 169.5,219C 169.802,217.345 171.136,216.012 173.5,215C 171.833,214.667 170.167,214.333 168.5,214C 171.695,213.819 174.695,213.319 177.5,212.5 Z M 189.5,221.5 C 192.287,220.523 195.287,220.19 198.5,220.5C 203.5,220.134 204.5,221.8 201.5,225.5C 199.087,227.051 196.421,227.717 193.5,227.5C 191.71,225.728 190.377,223.728 189.5,221.5 Z" />
{/* Extended body section */}
<path fill={fillColor} d="M 225.5,216.5 C 247.583,219.231 268.249,225.898 287.5,236.5C 289.507,234.467 291.507,232.467 293.5,230.5C 294.906,230.027 295.573,229.027 295.5,227.5C 296.167,227.5 296.833,227.5 297.5,227.5C 296.606,230.242 297.606,230.909 300.5,229.5C 301.452,231.045 301.785,232.712 301.5,234.5C 300.585,236.754 299.252,238.754 297.5,240.5C 296.667,276.829 296.167,313.162 296,349.5C 295.065,357.682 292.231,365.016 287.5,371.5C 286.118,372.801 284.452,373.634 282.5,374C 283.252,374.671 283.586,375.504 283.5,376.5C 272.573,387.751 259.239,391.917 243.5,389C 219.325,381.522 207.825,365.022 209,339.5C 208.333,313.833 208.333,288.167 209,262.5C 209.391,257.944 211.891,255.61 216.5,255.5C 219.037,255.435 221.037,256.435 222.5,258.5C 223.333,289.495 223.833,320.495 224,351.5C 227.652,365.323 236.485,373.323 250.5,375.5C 251.793,376.158 253.293,376.492 255,376.5C 257.821,376.592 260.321,375.926 262.5,374.5C 272.878,370.283 279.044,362.616 281,351.5C 281.5,315.835 281.667,280.168 281.5,244.5C 281.027,243.094 280.027,242.427 278.5,242.5C 272.117,238.977 265.451,235.977 258.5,233.5C 257.558,233.608 256.725,233.941 256,234.5C 251.175,245.334 243.342,248.501 232.5,244C 230.622,242.457 229.122,240.624 228,238.5C 226.992,240.259 225.492,241.426 223.5,242C 220.167,242.667 216.833,242.667 213.5,242C 209.903,240.048 206.569,237.881 203.5,235.5C 203.881,234.069 204.881,233.236 206.5,233C 204.249,233.213 202.249,232.213 200.5,230C 201.759,229.077 203.092,228.243 204.5,227.5C 203.995,226.081 202.995,225.415 201.5,225.5C 204.5,221.8 203.5,220.134 198.5,220.5C 198.5,220.167 198.5,219.833 198.5,219.5C 200.199,219.34 201.866,219.506 203.5,220C 204.833,221.333 204.833,222.667 203.5,224C 204.025,224.692 204.692,225.192 205.5,225.5C 206.258,224.189 207.258,223.689 208.5,224C 208.859,226.63 209.859,228.797 211.5,230.5C 211.5,231.167 211.833,231.5 212.5,231.5C 215.518,234.97 218.852,235.304 222.5,232.5C 223.965,230.401 225.299,228.234 226.5,226C 225.644,224.405 224.311,223.572 222.5,223.5C 223.429,222.685 224.429,221.852 225.5,221C 225.034,219.701 225.034,218.201 225.5,216.5 Z M 244.5,228.5 C 245.609,229.29 246.942,229.79 248.5,230C 247.663,231.011 247.33,232.178 247.5,233.5C 238.193,240.515 234.36,238.181 236,226.5C 238.778,227.325 241.611,227.992 244.5,228.5 Z M 213.5,222.5 C 216.43,223.299 219.43,223.632 222.5,223.5C 224.311,223.572 225.644,224.405 226.5,226C 225.299,228.234 223.965,230.401 222.5,232.5C 218.852,235.304 215.518,234.97 212.5,231.5C 212.19,228.287 212.523,225.287 213.5,222.5 Z" />
{/* Additional details */}
<path fill={fillColor} d="M 325.5,381.5 C 324.176,384.148 322.843,386.814 321.5,389.5C 318.621,387.559 315.788,388.226 313,391.5C 311.798,389.323 311.298,386.989 311.5,384.5C 311.333,336.832 311.5,289.166 312,241.5C 313.399,235.938 316.899,234.105 322.5,236C 324.049,237.214 325.215,238.714 326,240.5C 326.832,287.668 326.665,334.668 325.5,381.5 Z" />
{/* Final details */}
<path fill={fillColor} d="M 287.5,371.5 C 286.92,373.749 285.587,375.415 283.5,376.5C 283.586,375.504 283.252,374.671 282.5,374C 284.452,373.634 286.118,372.801 287.5,371.5 Z" />
{/* Bottom section */}
<path fill={fillColor} d="M 325.5,381.5 C 322.774,410.382 308.44,431.215 282.5,444C 280.564,444.813 278.564,445.313 276.5,445.5C 274.447,445.402 272.78,446.069 271.5,447.5C 243.945,453.656 220.111,446.99 200,427.5C 198.25,425.266 196.75,422.932 195.5,420.5C 197.557,421.202 199.557,421.535 201.5,421.5C 201.833,421.833 202.167,422.167 202.5,422.5C 200.252,423.324 200.086,424.324 202,425.5C 205.109,423.614 206.109,420.947 205,417.5C 204.667,418.167 204.333,418.833 204,419.5C 203.333,417.833 203.333,416.167 204,414.5C 207.123,416.098 207.956,415.431 206.5,412.5C 217.31,425.907 231.31,433.573 248.5,435.5C 253.65,436.651 258.984,436.817 264.5,436C 265.416,435.722 266.082,435.222 266.5,434.5C 284.985,429.357 298.318,418.024 306.5,400.5C 307.906,400.027 308.573,399.027 308.5,397.5C 309.598,393.089 310.598,388.755 311.5,384.5C 311.298,386.989 311.798,389.323 313,391.5C 315.788,388.226 318.621,387.559 321.5,389.5C 322.843,386.814 324.176,384.148 325.5,381.5 Z" />
</svg>
);
}
+52 -12
View File
@@ -5,7 +5,7 @@ import { BrowserAddressBar } from './browser-address-bar';
describe('BrowserAddressBar', () => {
it('renders navigation buttons and address input', () => {
render(<BrowserAddressBar />);
expect(screen.getByTitle('Go back')).toBeInTheDocument();
expect(screen.getByTitle('Go forward')).toBeInTheDocument();
expect(screen.getByTitle('Refresh')).toBeInTheDocument();
@@ -15,33 +15,56 @@ describe('BrowserAddressBar', () => {
it('calls onNavigate with proper path when form is submitted', () => {
const onNavigate = vi.fn();
render(<BrowserAddressBar onNavigate={onNavigate} />);
const input = screen.getByPlaceholderText('Enter path (e.g., /, /about)');
fireEvent.change(input, { target: { value: 'about' } });
fireEvent.submit(input.closest('form')!);
expect(onNavigate).toHaveBeenCalledWith('/about');
});
it('disables back/forward buttons based on canGoBack/canGoForward props', () => {
it('disables back/forward buttons based on canGoBack/canGoForward props and handlers', () => {
// Test with handlers provided
const onBack = vi.fn();
const onForward = vi.fn();
render(
<BrowserAddressBar
canGoBack={false}
<BrowserAddressBar
onBack={onBack}
onForward={onForward}
canGoBack={false}
canGoForward={true}
/>
);
expect(screen.getByTitle('Go back')).toBeDisabled(); // disabled because canGoBack=false
expect(screen.getByTitle('Go forward')).not.toBeDisabled(); // enabled because canGoForward=true and handler provided
});
it('disables buttons when no handlers are provided', () => {
render(
<BrowserAddressBar
canGoBack={true}
canGoForward={true}
/>
);
// All buttons should be disabled when no handlers are provided
expect(screen.getByTitle('Go back')).toBeDisabled();
expect(screen.getByTitle('Go forward')).not.toBeDisabled();
expect(screen.getByTitle('Go forward')).toBeDisabled();
expect(screen.getByTitle('Refresh')).toBeDisabled();
// Input should also be disabled when no onNavigate handler is provided
expect(screen.getByPlaceholderText('Enter path (e.g., /, /about)')).toBeDisabled();
});
it('calls navigation handlers when buttons are clicked', () => {
const onBack = vi.fn();
const onForward = vi.fn();
const onRefresh = vi.fn();
render(
<BrowserAddressBar
<BrowserAddressBar
onBack={onBack}
onForward={onForward}
onRefresh={onRefresh}
@@ -49,13 +72,30 @@ describe('BrowserAddressBar', () => {
canGoForward={true}
/>
);
fireEvent.click(screen.getByTitle('Go back'));
fireEvent.click(screen.getByTitle('Go forward'));
fireEvent.click(screen.getByTitle('Refresh'));
expect(onBack).toHaveBeenCalled();
expect(onForward).toHaveBeenCalled();
expect(onRefresh).toHaveBeenCalled();
});
it('updates input value when currentPath prop changes', () => {
const { rerender } = render(<BrowserAddressBar currentPath="/" />);
const input = screen.getByPlaceholderText('Enter path (e.g., /, /about)');
expect(input).toHaveValue('/');
// Re-render with new currentPath
rerender(<BrowserAddressBar currentPath="/about" />);
expect(input).toHaveValue('/about');
// Re-render with another path
rerender(<BrowserAddressBar currentPath="/contact" />);
expect(input).toHaveValue('/contact');
});
});
+14 -5
View File
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { ChevronLeft, ChevronRight, RefreshCw } from 'lucide-react';
@@ -30,8 +30,15 @@ export function BrowserAddressBar({
}: BrowserAddressBarProps) {
const [inputValue, setInputValue] = useState(currentPath);
// Update input value when currentPath changes (e.g., when iframe navigates)
useEffect(() => {
setInputValue(currentPath);
}, [currentPath]);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!onNavigate) return;
let path = inputValue.trim();
// Ensure path starts with /
@@ -39,7 +46,7 @@ export function BrowserAddressBar({
path = '/' + path;
}
onNavigate?.(path);
onNavigate(path);
};
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
@@ -57,7 +64,7 @@ export function BrowserAddressBar({
variant="ghost"
size="sm"
onClick={onBack}
disabled={!canGoBack}
disabled={!canGoBack || !onBack}
className="h-8 w-8 p-0"
title="Go back"
>
@@ -67,7 +74,7 @@ export function BrowserAddressBar({
variant="ghost"
size="sm"
onClick={onForward}
disabled={!canGoForward}
disabled={!canGoForward || !onForward}
className="h-8 w-8 p-0"
title="Go forward"
>
@@ -77,6 +84,7 @@ export function BrowserAddressBar({
variant="ghost"
size="sm"
onClick={onRefresh}
disabled={!onRefresh}
className="h-8 w-8 p-0"
title="Refresh"
>
@@ -85,13 +93,14 @@ export function BrowserAddressBar({
</div>
{/* Address bar */}
<form onSubmit={handleSubmit} className="flex-1 mx-2">
<form onSubmit={handleSubmit} className="flex-1 mx-auto px-4 max-w-2xl">
<Input
type="text"
value={inputValue}
onChange={handleInputChange}
placeholder="Enter path (e.g., /, /about)"
className="h-8 bg-muted/50 border-muted-foreground/20 focus:bg-background"
disabled={!onNavigate}
/>
</form>
+3 -1
View File
@@ -65,7 +65,9 @@ export function FileAttachment({
size="sm"
onClick={handleButtonClick}
disabled={disabled}
className="h-8 w-8 p-0 rounded-full hover:bg-muted/50"
className="h-8 w-8 p-0 rounded-full hover:bg-muted/50 dark:hover:text-sidebar-primary"
aria-label="Attach files"
data-testid="paperclip-button"
>
<Paperclip className="h-4 w-4" />
</Button>
+1 -1
View File
@@ -29,7 +29,7 @@ const PasswordInput = React.forwardRef<HTMLInputElement, React.InputHTMLAttribut
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 rounded-sm disabled:cursor-not-allowed disabled:opacity-50"
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
disabled={props.disabled}
aria-label={showPassword ? "Hide password" : "Show password"}
>
+2 -2
View File
@@ -14,7 +14,7 @@ const ToastViewport = React.forwardRef<
<ToastPrimitives.Viewport
ref={ref}
className={cn(
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[480px]",
className
)}
{...props}
@@ -41,7 +41,7 @@ const toastVariants = cva(
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
VariantProps<typeof toastVariants>
VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => {
return (
<ToastPrimitives.Root
+6 -5
View File
@@ -1,22 +1,23 @@
import { createContext } from 'react';
export interface AIConnection {
export interface AIProvider {
id: string;
baseURL: string;
apiKey?: string;
nostr?: boolean;
}
export interface AISettings {
providers: Record<string, AIConnection>;
providers: AIProvider[];
recentlyUsedModels: string[];
}
export interface AISettingsContextType {
settings: AISettings;
updateSettings: (settings: Partial<AISettings>) => void;
addProvider: (name: string, connection: AIConnection) => void;
removeProvider: (name: string) => void;
updateProvider: (name: string, connection: Partial<AIConnection>) => void;
setProvider: (provider: AIProvider) => void;
removeProvider: (id: string) => void;
setProviders: (providers: AIProvider[]) => void;
addRecentlyUsedModel: (modelId: string) => void;
isConfigured: boolean;
}
+27 -11
View File
@@ -10,9 +10,9 @@ interface UseAIChatSessionOptions {
projectId: string;
tools?: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
customTools?: Record<string, Tool<unknown>>;
systemPrompt?: string;
maxSteps?: number;
onUpdateMetadata?: (title: string, description: string) => void;
onAIError?: (error: Error) => void;
}
interface StreamingMessage {
@@ -30,9 +30,9 @@ export function useAIChat({
projectId,
tools = {},
customTools = {},
systemPrompt,
maxSteps = 50,
onUpdateMetadata
onUpdateMetadata,
onAIError
}: UseAIChatSessionOptions) {
const sessionManager = useSessionManager();
const { isConfigured } = useAISettings();
@@ -46,14 +46,14 @@ export function useAIChat({
const initSession = useCallback(async () => {
// Load or update session
const session = await sessionManager.loadSession(projectId, tools, customTools, systemPrompt, maxSteps);
const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps);
// Initialize individual state variables from existing session
setMessages([...session.messages]);
setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined);
setIsLoading(session.isLoading);
setTotalCost(session.totalCost || 0);
setLastInputTokens(session.lastInputTokens || 0);
}, [sessionManager, projectId, tools, customTools, systemPrompt, maxSteps]);
}, [sessionManager, projectId, tools, customTools, maxSteps]);
// Initialize session
useEffect(() => {
@@ -115,14 +115,30 @@ export function useAIChat({
// Actions
const sendMessage = useCallback(async (content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>, providerModel: string) => {
await initSession();
await sessionManager.sendMessage(projectId, content, providerModel);
}, [projectId, sessionManager, initSession]);
try {
await initSession();
await sessionManager.sendMessage(projectId, content, providerModel);
} catch (error) {
if (onAIError && error instanceof Error) {
onAIError(error);
} else {
console.error('AI chat error:', error);
}
}
}, [projectId, sessionManager, initSession, onAIError]);
const startGeneration = useCallback(async (providerModel: string) => {
await initSession();
await sessionManager.startGeneration(projectId, providerModel);
}, [projectId, sessionManager, initSession]);
try {
await initSession();
await sessionManager.startGeneration(projectId, providerModel);
} catch (error) {
if (onAIError && error instanceof Error) {
onAIError(error);
} else {
console.error('AI chat error:', error);
}
}
}, [projectId, sessionManager, initSession, onAIError]);
const stopGeneration = useCallback(() => {
sessionManager.stopGeneration(projectId);
+8 -36
View File
@@ -2,59 +2,30 @@ import { useQuery } from '@tanstack/react-query';
import { z } from 'zod';
import { createAIClient } from '@/lib/ai-client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import type { AIConnection } from '@/contexts/AISettingsContext';
import { AIProvider } from '@/contexts/AISettingsContext';
// Zod schemas for the two possible response formats
const creditsResponseV1Schema = z.object({
const creditsResponseSchema = z.object({
object: z.literal('credits'),
amount: z.number(),
});
const creditsResponseV2Schema = z.object({
data: z.object({
total_credits: z.number(),
total_usage: z.number(),
}),
});
// Union schema to handle both response formats
const creditsResponseSchema = z.union([creditsResponseV1Schema, creditsResponseV2Schema]);
// Normalized response type (always in V1 format)
export interface CreditsResponse {
object: 'credits';
amount: number;
}
/**
* Custom hook to fetch AI provider credits
* @param providerId - The ID of the AI provider
* @param connection - The AI connection configuration
* @returns Query result with credits information
*/
export function useAICredits(providerId: string, connection: AIConnection) {
/** Custom hook to fetch AI provider credits */
export function useAICredits(provider: AIProvider) {
const { user } = useCurrentUser();
return useQuery({
queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId],
queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
queryFn: async (): Promise<CreditsResponse> => {
try {
const ai = createAIClient(connection, user);
const ai = createAIClient(provider, user);
const data = await ai.get('/credits');
// Validate and normalize the response
const parsed = creditsResponseSchema.parse(data);
// Convert V2 format to V1 format if needed
if ('data' in parsed) {
return {
object: 'credits',
amount: parsed.data.total_credits - parsed.data.total_usage,
};
}
// Already in V1 format
return parsed;
return creditsResponseSchema.parse(data);
} catch (error) {
if (error instanceof Error && !error.message.includes('Connection error')) {
console.error('Error fetching AI credits:', error);
@@ -65,5 +36,6 @@ export function useAICredits(providerId: string, connection: AIConnection) {
retry: false, // Don't retry as not all providers support this endpoint
refetchOnWindowFocus: false,
staleTime: 5 * 60 * 1000, // 5 minutes
enabled: provider.id === 'shakespeare' && !!user,
});
}
+66 -57
View File
@@ -42,9 +42,8 @@ describe('useAIProjectId', () => {
// Mock parseProviderModel
mockParseProviderModel.mockReturnValue({
provider: 'openai',
provider: { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
model: 'gpt-4',
connection: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
});
// Mock createAIClient
@@ -63,12 +62,12 @@ describe('useAIProjectId', () => {
it('should return not configured when AI settings are not configured', () => {
mockUseAISettings.mockReturnValue({
settings: { providers: {}, recentlyUsedModels: [] },
settings: { providers: [], recentlyUsedModels: [] },
isConfigured: false,
updateSettings: vi.fn(),
addProvider: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
updateProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -80,12 +79,13 @@ describe('useAIProjectId', () => {
it('should throw error when trying to generate ID without configuration', async () => {
mockUseAISettings.mockReturnValue({
settings: { providers: {}, recentlyUsedModels: [] },
settings: { providers: [], recentlyUsedModels: [] },
isConfigured: false,
updateSettings: vi.fn(),
addProvider: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
updateProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -99,16 +99,17 @@ describe('useAIProjectId', () => {
it('should throw error when prompt is empty', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
},
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
addProvider: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
updateProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -122,16 +123,17 @@ describe('useAIProjectId', () => {
it('should have configured status when providers are available', () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
},
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
addProvider: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
updateProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -144,16 +146,17 @@ describe('useAIProjectId', () => {
it('should successfully generate project ID', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
},
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
addProvider: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
updateProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -162,11 +165,11 @@ describe('useAIProjectId', () => {
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('test-project-name');
expect(mockParseProviderModel).toHaveBeenCalledWith('openai/gpt-4', {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
});
expect(mockParseProviderModel).toHaveBeenCalledWith('openai/gpt-4', [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
]);
expect(mockCreateAIClient).toHaveBeenCalledWith(
{ apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
undefined
);
});
@@ -174,16 +177,17 @@ describe('useAIProjectId', () => {
it('should fallback to untitled when project exists', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
},
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
addProvider: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
updateProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -226,16 +230,17 @@ describe('useAIProjectId', () => {
it('should fallback to untitled-1 when untitled exists', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
},
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
addProvider: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
updateProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -280,16 +285,17 @@ describe('useAIProjectId', () => {
it('should fallback to untitled when AI generates too long name', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
},
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
addProvider: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
updateProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -329,16 +335,17 @@ describe('useAIProjectId', () => {
it('should fallback to untitled when AI generates invalid name', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
},
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
addProvider: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
updateProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -378,16 +385,17 @@ describe('useAIProjectId', () => {
it('should fallback to untitled-2 when untitled and untitled-1 exist', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
},
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
addProvider: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
updateProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
@@ -434,16 +442,17 @@ describe('useAIProjectId', () => {
it('should handle loading state correctly', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: {
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
},
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
addProvider: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
updateProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
});
+3 -3
View File
@@ -28,8 +28,8 @@ export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
try {
// Initialize OpenAI client
const { model, connection } = parseProviderModel(providerModel, settings.providers);
const openai = createAIClient(connection, user);
const { model, provider } = parseProviderModel(providerModel, settings.providers);
const openai = createAIClient(provider, user);
const systemPrompt = `You are a product expert. Given the user's project description, come up with a short, unique, and memorable name for their product or brand. Generate only the name without any additional text or punctuation. The name should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens. Avoid using special characters or underscores.`;
@@ -80,7 +80,7 @@ export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Failed to generate project ID';
onError?.(errorMessage);
throw new Error(errorMessage);
throw error;
} finally {
setIsLoading(false);
}
+17
View File
@@ -0,0 +1,17 @@
import { useMutation } from "@tanstack/react-query";
import { buildProject } from "@/lib/build";
import { useFS } from "./useFS";
export function useBuildProject(projectId: string) {
const { fs } = useFS();
return useMutation({
mutationFn: async () => {
return await buildProject({
fs,
projectPath: `/projects/${projectId}`,
domParser: new DOMParser(),
});
},
});
}
+26
View File
@@ -0,0 +1,26 @@
import { useMutation } from "@tanstack/react-query";
import { deployProject } from "@/lib/deploy";
import { useFS } from "./useFS";
import { useAppContext } from "./useAppContext";
import { useCurrentUser } from "./useCurrentUser";
export function useDeployProject(projectId: string) {
const { fs } = useFS();
const { user } = useCurrentUser();
const { config } = useAppContext();
return useMutation({
mutationFn: async () => {
if (!user) {
throw new Error("You must be logged into Nostr to deploy a project");
}
return await deployProject({
fs,
projectId: projectId,
deployServer: config.deployServer,
projectPath: `/projects/${projectId}`,
signer: user.signer,
});
},
});
}
+43 -9
View File
@@ -5,22 +5,40 @@ import { useFS } from './useFS';
import { useGitSettings } from './useGitSettings';
import { Git } from '@/lib/git';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import type { NPool } from '@nostrify/nostrify';
// Mock the dependencies
vi.mock('./useFS');
vi.mock('./useGitSettings');
vi.mock('@nostrify/react', () => ({
useNostr: vi.fn(),
}));
vi.mock('@/lib/git');
const mockUseFS = vi.mocked(useFS);
const mockUseGitSettings = vi.mocked(useGitSettings);
const MockGit = vi.mocked(Git);
// Import the mocked useNostr after mocking
import { useNostr } from '@nostrify/react';
const mockUseNostr = vi.mocked(useNostr);
describe('useGit', () => {
const mockFS = {} as JSRuntimeFS;
const mockNostr = {
req: vi.fn(),
query: vi.fn(),
event: vi.fn(),
group: vi.fn(),
relay: vi.fn(),
relays: new Map(),
close: vi.fn(),
} as unknown as NPool;
beforeEach(() => {
vi.clearAllMocks();
mockUseFS.mockReturnValue({ fs: mockFS });
mockUseNostr.mockReturnValue({ nostr: mockNostr });
});
it('creates Git instance with default CORS proxy', () => {
@@ -36,9 +54,14 @@ describe('useGit', () => {
isConfigured: false,
});
renderHook(() => useGit());
const { result } = renderHook(() => useGit());
expect(MockGit).toHaveBeenCalledWith(mockFS, 'https://cors.isomorphic-git.org');
expect(MockGit).toHaveBeenCalledWith({
fs: mockFS,
nostr: mockNostr,
corsProxy: 'https://cors.isomorphic-git.org',
});
expect(result.current).toEqual({ git: expect.any(Object) });
});
it('creates Git instance with custom CORS proxy', () => {
@@ -54,14 +77,17 @@ describe('useGit', () => {
isConfigured: false,
});
renderHook(() => useGit());
const { result } = renderHook(() => useGit());
expect(MockGit).toHaveBeenCalledWith(mockFS, 'https://custom-cors.example.com');
expect(MockGit).toHaveBeenCalledWith({
fs: mockFS,
nostr: mockNostr,
corsProxy: 'https://custom-cors.example.com',
});
expect(result.current).toEqual({ git: expect.any(Object) });
});
it('recreates Git instance when CORS proxy changes', () => {
const { rerender } = renderHook(() => useGit());
// First render with default proxy
mockUseGitSettings.mockReturnValue({
settings: {
@@ -75,8 +101,12 @@ describe('useGit', () => {
isConfigured: false,
});
rerender();
expect(MockGit).toHaveBeenCalledWith(mockFS, 'https://cors.isomorphic-git.org');
const { rerender } = renderHook(() => useGit());
expect(MockGit).toHaveBeenCalledWith({
fs: mockFS,
nostr: mockNostr,
corsProxy: 'https://cors.isomorphic-git.org',
});
// Second render with custom proxy
mockUseGitSettings.mockReturnValue({
@@ -92,6 +122,10 @@ describe('useGit', () => {
});
rerender();
expect(MockGit).toHaveBeenLastCalledWith(mockFS, 'https://custom-cors.example.com');
expect(MockGit).toHaveBeenLastCalledWith({
fs: mockFS,
nostr: mockNostr,
corsProxy: 'https://custom-cors.example.com',
});
});
});
+7 -4
View File
@@ -1,19 +1,22 @@
import { useMemo } from 'react';
import { Git } from '@/lib/git';
import { useFS } from '@/hooks/useFS';
import { useNostr } from '@nostrify/react';
import { useGitSettings } from '@/hooks/useGitSettings';
/**
* Hook that provides a Git instance configured with the virtual filesystem
* and configurable CORS proxy for GitHub/GitLab repositories.
*/
export function useGit() {
export function useGit(): { git: Git } {
const { fs } = useFS();
const { nostr } = useNostr();
const { settings } = useGitSettings();
const { corsProxy } = settings;
const git = useMemo(() => {
return new Git(fs, settings.corsProxy);
}, [fs, settings.corsProxy]);
return new Git({ fs, nostr, corsProxy });
}, [fs, nostr, corsProxy]);
return git;
return { git };
}
+2 -2
View File
@@ -61,7 +61,7 @@ describe('useGitHubOAuth PKCE', () => {
wrapper: TestApp,
});
// Mock fetch for token exchange and user info (using corsproxy.io URLs)
// Mock fetch for token exchange and user info (using proxy URLs)
const mockFetch = vi.fn()
.mockResolvedValueOnce({
ok: true,
@@ -147,7 +147,7 @@ describe('useGitHubOAuth PKCE', () => {
// Check that the token request includes the code verifier
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('corsproxy.io/?url=https://github.com/login/oauth/access_token'),
'https://proxy.shakespeare.diy/?url=https%3A%2F%2Fgithub.com%2Flogin%2Foauth%2Faccess_token',
expect.objectContaining({
method: 'POST',
body: expect.stringContaining('"code_verifier":"test-verifier"'),
+9 -5
View File
@@ -1,5 +1,6 @@
import { useState, useCallback } from 'react';
import { useGitSettings } from './useGitSettings';
import { proxyUrl } from '@/lib/proxyUrl';
interface GitHubOAuthState {
isLoading: boolean;
@@ -17,7 +18,8 @@ export function useGitHubOAuth() {
isLoading: false,
error: null,
});
const { addCredential } = useGitSettings();
const { settings, addCredential } = useGitSettings();
const { corsProxy } = settings;
// Check if OAuth is configured
const isOAuthConfigured = !!(
@@ -70,7 +72,7 @@ export function useGitHubOAuth() {
const params = new URLSearchParams({
client_id: clientId,
redirect_uri: window.location.origin + '/oauth/github',
scope: 'repo',
scope: 'repo workflow',
state: state,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
@@ -122,7 +124,8 @@ export function useGitHubOAuth() {
code_verifier: codeVerifier,
};
const tokenResponse = await fetch('https://corsproxy.io/?url=https://github.com/login/oauth/access_token', {
const tokenUrl = proxyUrl(corsProxy, 'https://github.com/login/oauth/access_token');
const tokenResponse = await fetch(tokenUrl, {
method: 'POST',
headers: {
'Accept': 'application/json',
@@ -142,7 +145,8 @@ export function useGitHubOAuth() {
}
// Get user info to verify the token works
const userResponse = await fetch('https://corsproxy.io/?url=https://api.github.com/user', {
const userUrl = proxyUrl(corsProxy, 'https://api.github.com/user');
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${tokenData.access_token}`,
'Accept': 'application/vnd.github.v3+json',
@@ -177,7 +181,7 @@ export function useGitHubOAuth() {
}));
return false;
}
}, [addCredential]);
}, [addCredential, corsProxy]);
return {
...state,
+1 -1
View File
@@ -40,7 +40,7 @@ interface GitStatus {
}
export function useGitStatus(projectId: string | null) {
const git = useGit();
const { git } = useGit();
return useQuery({
queryKey: ['git-status', projectId],
+1 -1
View File
@@ -1,6 +1,6 @@
import { useEffect, useState } from "react"
const MOBILE_BREAKPOINT = 768;
const MOBILE_BREAKPOINT = 1080;
export function useIsMobile(): boolean {
const [isMobile, setIsMobile] = useState(window.innerWidth < MOBILE_BREAKPOINT);
+117
View File
@@ -0,0 +1,117 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { useIsProjectPreviewable } from './useIsProjectPreviewable';
import { TestApp } from '@/test/TestApp';
// Mock the useProjectsManager hook
const mockFileExists = vi.fn();
vi.mock('./useProjectsManager', () => ({
useProjectsManager: () => ({
fileExists: mockFileExists,
}),
}));
describe('useIsProjectPreviewable', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('returns true when all required files exist', async () => {
mockFileExists.mockResolvedValue(true);
const { result } = renderHook(
() => useIsProjectPreviewable('test-project'),
{ wrapper: TestApp }
);
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toBe(true);
expect(mockFileExists).toHaveBeenCalledWith('test-project', 'index.html');
expect(mockFileExists).toHaveBeenCalledWith('test-project', 'package.json');
expect(mockFileExists).toHaveBeenCalledWith('test-project', 'package-lock.json');
});
it('returns false when index.html is missing', async () => {
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
if (filePath === 'index.html') return Promise.resolve(false);
return Promise.resolve(true);
});
const { result } = renderHook(
() => useIsProjectPreviewable('test-project'),
{ wrapper: TestApp }
);
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toBe(false);
});
it('returns false when package.json is missing', async () => {
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
if (filePath === 'package.json') return Promise.resolve(false);
return Promise.resolve(true);
});
const { result } = renderHook(
() => useIsProjectPreviewable('test-project'),
{ wrapper: TestApp }
);
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toBe(false);
});
it('returns false when package-lock.json is missing', async () => {
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
if (filePath === 'package-lock.json') return Promise.resolve(false);
return Promise.resolve(true);
});
const { result } = renderHook(
() => useIsProjectPreviewable('test-project'),
{ wrapper: TestApp }
);
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toBe(false);
});
it('returns false when projectId is empty', async () => {
const { result } = renderHook(
() => useIsProjectPreviewable(''),
{ wrapper: TestApp }
);
// When projectId is empty, the query is disabled, so it should not be loading or successful
expect(result.current.data).toBe(false);
expect(result.current.isLoading).toBe(false);
expect(mockFileExists).not.toHaveBeenCalled();
});
it('returns false when file check throws an error', async () => {
mockFileExists.mockRejectedValue(new Error('File system error'));
const { result } = renderHook(
() => useIsProjectPreviewable('test-project'),
{ wrapper: TestApp }
);
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toBe(false);
});
});
+38
View File
@@ -0,0 +1,38 @@
import { useQuery } from '@tanstack/react-query';
import { useProjectsManager } from './useProjectsManager';
/**
* Hook to check if a project is previewable
* A project is previewable if it has index.html, package.json, and package-lock.json
*/
export function useIsProjectPreviewable(projectId: string) {
const projectsManager = useProjectsManager();
const result = useQuery({
queryKey: ['project-previewable', projectId],
queryFn: async () => {
try {
// Check for required files
const [hasIndexHtml, hasPackageJson, hasPackageLock] = await Promise.all([
projectsManager.fileExists(projectId, 'index.html'),
projectsManager.fileExists(projectId, 'package.json'),
projectsManager.fileExists(projectId, 'package-lock.json'),
]);
return hasIndexHtml && hasPackageJson && hasPackageLock;
} catch (error) {
console.error('Failed to check if project is previewable:', error);
return false;
}
},
enabled: !!projectId,
staleTime: 5000, // Cache for 5 seconds
refetchOnWindowFocus: false,
});
// Return false when query is disabled (empty projectId) or when data is undefined
return {
...result,
data: result.data ?? false,
};
}
+5 -1
View File
@@ -1,6 +1,7 @@
import { useMemo } from 'react';
import { ProjectsManager } from '@/lib/ProjectsManager';
import { useFS } from '@/hooks/useFS';
import { useGit } from './useGit';
/**
* Hook that provides a ProjectsManager instance.
@@ -8,8 +9,11 @@ import { useFS } from '@/hooks/useFS';
*/
export function useProjectsManager() {
const { fs } = useFS();
const { git } = useGit();
const projectsManager = useMemo(() => new ProjectsManager(fs), [fs]);
const projectsManager = useMemo(() => {
return new ProjectsManager({ fs, git });
}, [fs, git]);
return projectsManager;
}
+19 -11
View File
@@ -7,9 +7,10 @@ import { createAIClient } from '@/lib/ai-client';
interface ProviderModel {
id: string;
name: string;
name?: string;
provider: string;
fullId: string; // provider/model format
description?: string;
/** Maximum size of context window, if available */
contextLength?: number;
/** Pricing information, if available */
@@ -38,14 +39,14 @@ export function useProviderModels(): ModelFetchResult {
isLoading,
refetch,
} = useQuery({
queryKey: ['provider-models'],
queryKey: ['provider-models', settings.providers],
queryFn: async () => {
const errors: string[] = [];
// Fetch models from each configured provider in parallel
const providerPromises = Object.entries(settings.providers).map(async ([providerKey, connection]) => {
const providerPromises = settings.providers.map(async (provider) => {
try {
const openai = createAIClient(connection, user);
const openai = createAIClient(provider, user);
// Fetch models with timeout
try {
@@ -57,11 +58,18 @@ export function useProviderModels(): ModelFetchResult {
const providerModels = response.data.map((model) => {
const providerModel: ProviderModel = {
id: model.id,
name: model.id,
provider: providerKey,
fullId: `${providerKey}/${model.id}`,
provider: provider.id,
fullId: `${provider.id}/${model.id}`,
};
if ('name' in model && typeof model.name === 'string') {
providerModel.name = model.name;
}
if ('description' in model && typeof model.description === 'string') {
providerModel.description = model.description;
}
if ('context_length' in model && typeof model.context_length === 'number') {
providerModel.contextLength = model.context_length;
}
@@ -86,16 +94,16 @@ export function useProviderModels(): ModelFetchResult {
return providerModels;
} catch (fetchError) {
if (fetchError instanceof Error && fetchError.name === 'AbortError') {
errors.push(`${providerKey}: Request timeout`);
errors.push(`${provider.id}: Request timeout`);
} else {
throw fetchError;
}
return [];
}
} catch (providerError) {
console.warn(`Failed to fetch models from ${providerKey}:`, providerError);
console.warn(`Failed to fetch models from ${provider.id}:`, providerError);
errors.push(
`${providerKey}: ${
`${provider.id}: ${
providerError instanceof Error ? providerError.message : 'Unknown error'
}`
);
@@ -118,7 +126,7 @@ export function useProviderModels(): ModelFetchResult {
return allModels;
},
enabled: Object.keys(settings.providers).length > 0,
enabled: settings.providers.length > 0,
staleTime: 5 * 60 * 1000, // Cache for 5 minutes
retry: false, // Don't retry on failure
});
+37 -4
View File
@@ -110,11 +110,13 @@
@layer base {
* {
@apply border-border;
border-color: hsl(var(--border));
}
body {
@apply bg-background text-foreground font-sans;
background-color: hsl(var(--background));
color: hsl(var(--foreground));
font-family: 'Inter Variable', 'Inter', 'system-ui', 'sans-serif';
font-feature-settings: "rlig" 1, "calt" 1;
}
@@ -138,8 +140,10 @@
}
/* GitHub-style focus rings */
.focus-ring {
@apply focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2;
.focus-ring:focus-visible {
outline: none;
box-shadow: 0 0 0 2px hsl(var(--ring));
outline-offset: 2px;
}
/* Smooth transitions for theme switching */
@@ -247,6 +251,35 @@
max-height: 100dvh;
}
/* iOS Safe Area Support */
.safe-area-inset-bottom {
padding-bottom: env(safe-area-inset-bottom);
}
.safe-area-inset-top {
padding-top: env(safe-area-inset-top);
}
.bottom-safe-nav {
bottom: calc(env(safe-area-inset-bottom) + 3.75rem);
}
/* Mobile navigation button styles - text/icon highlighting only */
.mobile-nav-button,
.mobile-nav-button:hover,
.mobile-nav-button:active,
.mobile-nav-button-active,
.mobile-nav-button-active:hover,
.mobile-nav-button-active:active {
background-color: transparent !important;
}
.mobile-nav-button-active,
.mobile-nav-button-active:hover,
.mobile-nav-button-active:active {
color: hsl(var(--primary)) !important;
}
pre.shiki {
background-color: transparent !important;
}
+8 -54
View File
@@ -28,17 +28,8 @@ describe('DotAI', () => {
});
describe('readLastSessionHistory', () => {
it('should return null when AI is not enabled', async () => {
// Mock isEnabled to return false
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(false);
const result = await dotAI.readLastSessionHistory();
expect(result).toBeNull();
});
it('should return null when history directory does not exist', async () => {
// Mock isEnabled to return true but historyDirExists to return false
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
// Mock historyDirExists to return false
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false);
const result = await dotAI.readLastSessionHistory();
@@ -46,8 +37,7 @@ describe('DotAI', () => {
});
it('should return null when no session files exist', async () => {
// Mock isEnabled and historyDirExists to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
// Mock historyDirExists to return true
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock readdir to return empty array
@@ -58,8 +48,7 @@ describe('DotAI', () => {
});
it('should return messages and session name from most recent file', async () => {
// Mock isEnabled and historyDirExists to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
// Mock historyDirExists to return true
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock readdir to return session files
@@ -84,8 +73,7 @@ describe('DotAI', () => {
});
it('should handle malformed JSON lines gracefully', async () => {
// Mock isEnabled and historyDirExists to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
// Mock historyDirExists to return true
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock readdir to return session files
@@ -107,28 +95,9 @@ invalid json line
});
describe('setHistory', () => {
it('should not save when AI is not enabled', async () => {
// Mock isEnabled to return false
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(false);
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'user', content: 'Hello' },
{ role: 'assistant', content: 'Hi there!' }
];
await dotAI.setHistory('test-session', messages);
// Verify writeFile was not called
expect(mockFS.writeFile).not.toHaveBeenCalled();
});
it('should create history directory if it does not exist', async () => {
// Mock isEnabled to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
// Mock historyDirExists to return false initially
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false);
// Mock setupAiHistoryDir
vi.spyOn(dotAI, 'setupAiHistoryDir').mockResolvedValue();
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'user', content: 'Hello' }
@@ -136,13 +105,11 @@ invalid json line
await dotAI.setHistory('test-session', messages);
// Verify setupAiHistoryDir was called
expect(dotAI.setupAiHistoryDir).toHaveBeenCalled();
// Verify mkdir was called with recursive option
expect(mockFS.mkdir).toHaveBeenCalledWith('/test-project/.git/ai/history', { recursive: true });
});
it('should write messages as JSONL format', async () => {
// Mock isEnabled to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
// Mock historyDirExists to return true
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
@@ -155,14 +122,12 @@ invalid json line
// Verify writeFile was called with correct content
expect(mockFS.writeFile).toHaveBeenCalledWith(
'/test-project/.ai/history/test-session.jsonl',
'/test-project/.git/ai/history/test-session.jsonl',
'{"role":"user","content":"Hello"}\n{"role":"assistant","content":"Hi there!"}\n'
);
});
it('should handle empty messages array', async () => {
// Mock isEnabled to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
// Mock historyDirExists to return true
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
@@ -170,14 +135,12 @@ invalid json line
// Verify writeFile was called with empty content
expect(mockFS.writeFile).toHaveBeenCalledWith(
'/test-project/.ai/history/test-session.jsonl',
'/test-project/.git/ai/history/test-session.jsonl',
''
);
});
it('should handle write errors gracefully', async () => {
// Mock isEnabled to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
// Mock historyDirExists to return true
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock writeFile to throw an error
@@ -190,9 +153,6 @@ invalid json line
});
it('should validate tool messages have matching tool_call_id', async () => {
// Mock isEnabled to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
const validMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'user', content: 'Hello' },
{
@@ -249,9 +209,6 @@ invalid json line
});
it('should validate multiple tool messages correctly', async () => {
// Mock isEnabled to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
const validMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'user', content: 'Hello' },
{
@@ -271,9 +228,6 @@ invalid json line
});
it('should allow tool messages to reference tool calls from the most recent assistant message', async () => {
// Mock isEnabled to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
const validMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'user', content: 'First request' },
{
+19 -132
View File
@@ -1,8 +1,8 @@
import { join } from "@std/path";
import { join } from "path-browserify";
import type OpenAI from "openai";
import type { JSRuntimeFS } from "./JSRuntime";
/** AI message history manager and .ai directory utilities */
/** AI message history manager and .git/ai directory utilities */
export class DotAI {
readonly fs: JSRuntimeFS;
readonly historyDir: string;
@@ -11,7 +11,7 @@ export class DotAI {
constructor(fs: JSRuntimeFS, workingDir: string = "/") {
this.fs = fs;
this.workingDir = workingDir;
this.historyDir = join(workingDir, ".ai", "history");
this.historyDir = join(workingDir, ".git", "ai", "history");
}
/** Generate a unique session name based on the current date and time */
@@ -31,46 +31,6 @@ export class DotAI {
return filename;
}
/** Check if AI history should be enabled based on the new criteria */
async isEnabled(): Promise<boolean> {
// Check if .ai directory exists
try {
const stat = await this.fs.stat(join(this.workingDir, ".ai"));
if (stat.isDirectory()) {
return true;
}
} catch {
// Continue to next check
}
// Check if .ai/ or .ai is gitignored
try {
const gitignorePath = join(this.workingDir, ".gitignore");
const gitignoreContent = await this.fs.readFile(gitignorePath, "utf8");
const lines = gitignoreContent.split("\n").map((line) => line.trim());
// Check for .ai/ or .ai patterns (ignore comments and empty lines)
for (const line of lines) {
if (line.startsWith("#") || line === "") {
continue;
}
// Check for various .ai patterns
if (
line === ".ai" || line === ".ai/" || line === "/.ai" ||
line === "/.ai/" ||
line === ".ai/*" || line === "/.ai/*"
) {
return true;
}
}
} catch {
// .gitignore doesn't exist or can't be read
}
return false;
}
/** Check if the history directory exists */
async historyDirExists(): Promise<boolean> {
try {
@@ -89,14 +49,9 @@ export class DotAI {
// Validate messages before saving
this.validateMessages(messages);
// Only save if history should be enabled based on the new criteria
if (!(await this.isEnabled())) {
return;
}
// Create the history directory if it doesn't exist
if (!(await this.historyDirExists())) {
await this.setupAiHistoryDir();
await this.fs.mkdir(this.historyDir, { recursive: true });
}
const sessionFile = join(this.historyDir, sessionName + ".jsonl");
@@ -164,29 +119,11 @@ export class DotAI {
}
/**
* Creates .ai/history directory and ensures .ai/ is gitignored at the project root.
*/
async setupAiHistoryDir(): Promise<void> {
const aiHistoryDir = join(this.workingDir, ".ai", "history");
try {
// Create .ai/history directory
await this.fs.mkdir(aiHistoryDir, { recursive: true });
// Ensure .ai/ is gitignored at the project root
await this.ensureAiGitignored();
} catch (error) {
// Log error but don't fail the main operation
console.warn(`Failed to setup .ai/history directory: ${error}`);
}
}
/**
* Read the model from .ai/MODEL file
* Read the model from .git/ai/MODEL file
*/
async readAiModel(): Promise<string | undefined> {
try {
const modelPath = join(this.workingDir, ".ai", "MODEL");
const modelPath = join(this.workingDir, ".git", "ai", "MODEL");
const content = await this.fs.readFile(modelPath, "utf8");
return content.trim();
} catch {
@@ -195,29 +132,29 @@ export class DotAI {
}
/**
* Write the model to .ai/MODEL file
* Write the model to .git/ai/MODEL file
*/
async writeAiModel(model: string): Promise<void> {
const aiDir = join(this.workingDir, ".ai");
const aiDir = join(this.workingDir, ".git", "ai");
const modelPath = join(aiDir, "MODEL");
try {
// Ensure .ai directory exists
// Ensure .git/ai directory exists
await this.fs.mkdir(aiDir, { recursive: true });
// Write the model
await this.fs.writeFile(modelPath, model.trim() + "\n");
} catch (error) {
console.warn(`Failed to write .ai/MODEL file: ${error}`);
console.warn(`Failed to write .git/ai/MODEL file: ${error}`);
}
}
/**
* Read parameters from .ai/PARAMETERS file
* Read parameters from .git/ai/PARAMETERS file
*/
async readAiParameters(): Promise<Record<string, string>> {
try {
const parametersPath = join(this.workingDir, ".ai", "PARAMETERS");
const parametersPath = join(this.workingDir, ".git", "ai", "PARAMETERS");
const content = await this.fs.readFile(parametersPath, "utf8");
const parameters: Record<string, string> = {};
@@ -242,21 +179,14 @@ export class DotAI {
}
/**
* Write parameters to .ai/PARAMETERS file
* Write parameters to .git/ai/PARAMETERS file
*/
async writeAiParameters(parameters: Record<string, string>): Promise<void> {
// Check if we should create the .ai directory based on the same logic as MODEL
const shouldCreate = await this.isEnabled();
if (!shouldCreate) {
return;
}
const aiDir = join(this.workingDir, ".ai");
const aiDir = join(this.workingDir, ".git", "ai");
const parametersPath = join(aiDir, "PARAMETERS");
try {
// Ensure .ai directory exists
// Ensure .git/ai directory exists
await this.fs.mkdir(aiDir, { recursive: true });
// Format parameters as key=value pairs
@@ -268,12 +198,12 @@ export class DotAI {
// Write the parameters
await this.fs.writeFile(parametersPath, content);
} catch (error) {
console.warn(`Failed to write .ai/PARAMETERS file: ${error}`);
console.warn(`Failed to write .git/ai/PARAMETERS file: ${error}`);
}
}
/**
* Update a single parameter in .ai/PARAMETERS file
* Update a single parameter in .git/ai/PARAMETERS file
*/
async updateAiParameter(key: string, value: string): Promise<void> {
const currentParameters = await this.readAiParameters();
@@ -290,8 +220,8 @@ export class DotAI {
sessionName: string;
} | null> {
try {
// Check if AI history is enabled for this project
if (!(await this.isEnabled()) || !(await this.historyDirExists())) {
// Check if history directory exists
if (!(await this.historyDirExists())) {
return null;
}
@@ -344,47 +274,4 @@ export class DotAI {
return null;
}
}
/**
* Ensures that .ai/ is gitignored at the project root level.
* Creates a .gitignore file if it doesn't exist, or adds the line if not already present.
*/
async ensureAiGitignored(): Promise<void> {
const gitignorePath = join(this.workingDir, ".gitignore");
const aiPattern = ".ai/";
try {
// Try to read existing .gitignore
let gitignoreContent = "";
try {
gitignoreContent = await this.fs.readFile(gitignorePath, "utf8");
} catch {
// .gitignore doesn't exist, will create it
}
// Check if .ai/ is already gitignored
const lines = gitignoreContent.split("\n").map((line) => line.trim());
const hasAiPattern = lines.some((line) => {
if (line.startsWith("#") || line === "") {
return false;
}
// Check for various .ai patterns
return line === ".ai" || line === ".ai/" || line === "/.ai" ||
line === "/.ai/" ||
line === ".ai/*" || line === "/.ai/*";
});
if (!hasAiPattern) {
// Add .ai/ to .gitignore
const newContent = gitignoreContent.trim() === ""
? aiPattern
: gitignoreContent.trim() + "\n" + aiPattern;
await this.fs.writeFile(gitignorePath, newContent + "\n");
}
} catch (error) {
// Log error but don't fail the main operation
console.warn(`Failed to ensure .ai/ is gitignored: ${error}`);
}
}
}
+391 -10
View File
@@ -1,11 +1,49 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { ProjectsManager } from './ProjectsManager';
import { JSRuntimeFS } from './JSRuntime';
import { Git } from './git';
import type { NPool } from '@nostrify/nostrify';
import type JSZip from 'jszip';
const createMockNostr = (): NPool => ({
req: vi.fn(),
query: vi.fn(),
event: vi.fn(),
group: vi.fn(),
relay: vi.fn(),
relays: new Map(),
close: vi.fn(),
}) as unknown as NPool;
// Mock JSZip
vi.mock('jszip', () => ({
default: class MockJSZip {
files: Record<string, { dir: boolean; async: () => Uint8Array }> = {};
static async loadAsync(buffer: ArrayBuffer) {
const instance = new MockJSZip();
// Add a mock file entry
instance.files['package.json'] = {
dir: false,
async: () => new Uint8Array(buffer)
};
return instance;
}
async file(name: string) {
return this.files[name];
}
}
}));
// Mock filesystem for testing
class MockFS {
class MockFS implements JSRuntimeFS {
private files: Map<string, string | Uint8Array> = new Map();
private dirs: Set<string> = new Set();
async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, encoding: "utf8"): Promise<string>;
async readFile(path: string, encoding: string): Promise<string | Uint8Array>;
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
const content = this.files.get(path);
if (content === undefined) {
@@ -13,10 +51,18 @@ class MockFS {
error.code = 'ENOENT';
throw error;
}
if (encoding === 'utf8' && typeof content === 'string') {
return content;
if (encoding === 'utf8') {
if (typeof content === 'string') {
return content;
}
// Convert Uint8Array to string
return new TextDecoder('utf-8').decode(content as Uint8Array);
}
return content;
if (typeof content === 'string') {
// Convert string to Uint8Array
return new TextEncoder().encode(content);
}
return content as Uint8Array;
}
async writeFile(path: string, data: string | Uint8Array): Promise<void> {
@@ -28,7 +74,8 @@ class MockFS {
}
}
async readdir(path: string): Promise<string[]> {
// @ts-expect-error I don't know how to type this properly
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
if (!this.dirs.has(path)) {
const error = new Error(`ENOENT: no such file or directory, scandir '${path}'`) as NodeJS.ErrnoException;
error.code = 'ENOENT';
@@ -51,7 +98,22 @@ class MockFS {
}
}
return [...new Set(entries)];
const uniqueEntries = [...new Set(entries)];
if (options && options.withFileTypes) {
// Provide a minimal DirectoryEntry mock
return uniqueEntries.map(name => {
const fullPath = path.endsWith('/') ? path + name : path + '/' + name;
const isDir = this.dirs.has(fullPath);
return {
name,
isDirectory: () => isDir,
isFile: () => !isDir,
} as unknown as DirectoryEntry;
});
}
return uniqueEntries;
}
async mkdir(path: string): Promise<void> {
@@ -85,15 +147,76 @@ class MockFS {
async rmdir(path: string): Promise<void> {
this.dirs.delete(path);
}
async rename(oldPath: string, newPath: string): Promise<void> {
// Handle both files and directories
if (this.files.has(oldPath)) {
const content = this.files.get(oldPath);
this.files.delete(oldPath);
this.files.set(newPath, content!);
}
if (this.dirs.has(oldPath)) {
this.dirs.delete(oldPath);
this.dirs.add(newPath);
// Also move all subdirectories and files
const itemsToMove: Array<{ oldPath: string; newPath: string; isDir: boolean }> = [];
// Collect directories to move
for (const dir of this.dirs) {
if (dir.startsWith(oldPath + '/')) {
const relativePath = dir.slice(oldPath.length);
itemsToMove.push({
oldPath: dir,
newPath: newPath + relativePath,
isDir: true
});
}
}
// Collect files to move
for (const file of this.files.keys()) {
if (file.startsWith(oldPath + '/')) {
const relativePath = file.slice(oldPath.length);
itemsToMove.push({
oldPath: file,
newPath: newPath + relativePath,
isDir: false
});
}
}
// Move all items
for (const item of itemsToMove) {
if (item.isDir) {
this.dirs.delete(item.oldPath);
this.dirs.add(item.newPath);
} else {
const content = this.files.get(item.oldPath);
this.files.delete(item.oldPath);
this.files.set(item.newPath, content!);
}
}
}
}
async lstat(path: string): Promise<{ isDirectory(): boolean; isFile(): boolean; mtimeMs?: number }> {
return this.stat(path);
}
}
describe('ProjectsManager', () => {
let fs: MockFS;
let fs: JSRuntimeFS;
let git: Git;
let nostr: NPool;
let projectsManager: ProjectsManager;
beforeEach(() => {
fs = new MockFS();
projectsManager = new ProjectsManager(fs as unknown as import('./JSRuntime').JSRuntimeFS);
fs = new MockFS() as unknown as JSRuntimeFS;
nostr = createMockNostr();
git = new Git({ fs, nostr });
projectsManager = new ProjectsManager({ fs, git });
});
describe('getProjects', () => {
@@ -167,4 +290,262 @@ describe('ProjectsManager', () => {
expect(project).toBeNull();
});
});
describe('importProjectFromZip', () => {
it('should preserve original project name when overwriting', async () => {
await projectsManager.init();
// Create an existing project with a specific name
await fs.mkdir('/projects/my-project');
await fs.mkdir('/projects/my-project/.git');
await fs.writeFile('/projects/my-project/package.json', '{"name": "original-name"}');
// Mock the git methods to simulate existing project
const mockGit = {
init: vi.fn(),
clone: vi.fn(),
add: vi.fn(),
commit: vi.fn(),
getConfig: vi.fn(),
getAllFiles: vi.fn().mockResolvedValue(['package.json']),
} as Partial<import('./git').Git>;
// Replace git instance
Object.assign(projectsManager, { git: mockGit });
// Create a mock ZIP file with different name
const zipFile = new File(['test content'], 'different-name.zip', { type: 'application/zip' });
// Mock arrayBuffer method
Object.defineProperty(zipFile, 'arrayBuffer', {
value: () => Promise.resolve(new TextEncoder().encode('test content').buffer),
writable: false
});
// Import with overwrite
const project = await projectsManager.importProjectFromZip(zipFile, 'my-project', true);
// Should preserve original project name
expect(project.name).toBe('my-project');
expect(project.id).toBe('my-project');
});
it('should use new project name when not overwriting', async () => {
await projectsManager.init();
// Mock the git methods
const mockGit = {
init: vi.fn(),
clone: vi.fn(),
add: vi.fn(),
commit: vi.fn(),
getConfig: vi.fn(),
getAllFiles: vi.fn().mockResolvedValue(['package.json']),
} as Partial<import('./git').Git>;
// Replace git instance
Object.assign(projectsManager, { git: mockGit });
// Create a mock ZIP file
const zipFile = new File(['test content'], 'new-project.zip', { type: 'application/zip' });
// Mock arrayBuffer method
Object.defineProperty(zipFile, 'arrayBuffer', {
value: () => Promise.resolve(new TextEncoder().encode('test content').buffer),
writable: false
});
// Import without overwrite
const project = await projectsManager.importProjectFromZip(zipFile, undefined, false);
// Should use formatted name from ID
expect(project.name).toBe('new-project');
expect(project.id).toBe('new-project');
});
it('should prevent zip slip attacks during import', async () => {
await projectsManager.init();
// Mock the git methods
const mockGit = {
init: vi.fn(),
clone: vi.fn(),
add: vi.fn(),
commit: vi.fn(),
getConfig: vi.fn(),
getAllFiles: vi.fn().mockResolvedValue([]),
} as Partial<import('./git').Git>;
// Replace git instance
Object.assign(projectsManager, { git: mockGit });
// Create a mock ZIP file that would try to escape the project directory
const zipFile = new File(['malicious content'], 'malicious.zip', { type: 'application/zip' });
// Mock JSZip to simulate a malicious ZIP with path traversal
const JSZip = await import('jszip');
const mockLoadAsync = vi.fn().mockResolvedValue({
files: {
'../../../etc/passwd': {
dir: false,
async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3]))
},
'../../outside.txt': {
dir: false,
async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6]))
},
'safe-file.txt': {
dir: false,
async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9]))
}
}
});
vi.spyOn(JSZip.default, 'loadAsync').mockImplementation(mockLoadAsync);
// Mock arrayBuffer method
Object.defineProperty(zipFile, 'arrayBuffer', {
value: () => Promise.resolve(new ArrayBuffer(0)),
writable: false
});
// Spy on console.warn to check for security warnings
const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
// Import the malicious ZIP
const project = await projectsManager.importProjectFromZip(zipFile, undefined, false);
// Should have completed successfully (safe files extracted)
expect(project).toBeDefined();
// Should have logged a security warning about skipped files
expect(consoleSpy).toHaveBeenCalledWith(
expect.stringContaining('Skipped 2 files due to resolving to paths outside the project direcotry:'),
['../../../etc/passwd', '../../outside.txt']
);
// Verify that only safe files would be written (check writeFile calls)
const writeFileCalls = (fs.writeFile as unknown as { mock?: { calls: [string, unknown][] } }).mock?.calls || [];
const maliciousPaths = writeFileCalls.filter((call: [string, unknown]) =>
call[0].includes('../') || call[0].includes('etc/passwd') || call[0].includes('outside.txt')
);
expect(maliciousPaths).toHaveLength(0);
} finally {
// Restore mocks
consoleSpy.mockRestore();
vi.restoreAllMocks();
}
});
it('should prevent zip slip attacks during bulk file extraction', async () => {
await projectsManager.init();
// Create a mock ZIP with malicious paths for bulk import
const mockZip = {
files: {
'projects/project1/../../../etc/passwd': {
dir: false,
async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3]))
},
'projects/project1/../../outside.txt': {
dir: false,
async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6]))
},
'projects/project1/safe-file.txt': {
dir: false,
async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9]))
}
}
};
// Spy on console.warn to check for security warnings
const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
// Extract files from the malicious ZIP for bulk import
const files = await projectsManager.extractFilesFromZip(mockZip as unknown as JSZip, 'projects/project1');
// Should only contain safe files
expect(Object.keys(files)).toEqual(['safe-file.txt']);
expect(files['safe-file.txt']).toEqual(new Uint8Array([7, 8, 9]));
// Should have logged a security warning about skipped files
expect(consoleSpy).toHaveBeenCalledWith(
expect.stringContaining('Skipped 2 files due to resolving to paths outside of project directory:'),
['projects/project1/../../../etc/passwd', 'projects/project1/../../outside.txt']
);
} finally {
// Restore mocks
consoleSpy.mockRestore();
}
});
});
describe('renameProject', () => {
it('should rename a project directory', async () => {
await projectsManager.init();
// Create a project
await fs.mkdir('/projects/old-name');
await fs.writeFile('/projects/old-name/package.json', '{}');
// Verify the project exists
const originalProject = await projectsManager.getProject('old-name');
expect(originalProject).not.toBeNull();
// Rename the project
const renamedProject = await projectsManager.renameProject('old-name', 'new-name');
// Verify the renamed project
expect(renamedProject.id).toBe('new-name');
expect(renamedProject.name).toBe('new-name');
expect(renamedProject.path).toBe('/projects/new-name');
// Verify old project no longer exists
const oldProject = await projectsManager.getProject('old-name');
expect(oldProject).toBeNull();
// Verify new project exists
const newProject = await projectsManager.getProject('new-name');
expect(newProject).not.toBeNull();
expect(newProject?.id).toBe('new-name');
});
it('should throw error when old project does not exist', async () => {
await projectsManager.init();
await expect(projectsManager.renameProject('non-existent', 'new-name'))
.rejects.toThrow('Project with ID "non-existent" does not exist');
});
it('should throw error when new project name already exists', async () => {
await projectsManager.init();
// Create two projects
await fs.mkdir('/projects/project-1');
await fs.mkdir('/projects/project-2');
await expect(projectsManager.renameProject('project-1', 'project-2'))
.rejects.toThrow('Project with ID "project-2" already exists');
});
it('should validate and normalize project names', async () => {
await projectsManager.init();
// Create a project
await fs.mkdir('/projects/old-name');
// Try to rename with invalid characters
await expect(projectsManager.renameProject('old-name', 'New Name With Spaces'))
.rejects.toThrow('Project name must contain only lowercase letters, numbers, and hyphens');
// Try to rename with empty name
await expect(projectsManager.renameProject('old-name', ''))
.rejects.toThrow('Project name cannot be empty');
});
});
});
+633 -45
View File
@@ -1,7 +1,8 @@
import { Buffer } from 'buffer';
import JSZip from 'jszip';
import { Git } from '@/lib/git';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import { ensurePersistentStorage } from '@/lib/persistentStorage';
// Polyfill Buffer for browser
if (typeof window !== 'undefined') {
@@ -18,14 +19,19 @@ export interface Project {
lastModified: Date;
}
export interface ProjectsManagerOptions {
fs: JSRuntimeFS;
git: Git;
}
export class ProjectsManager {
fs: JSRuntimeFS;
git: Git;
dir: string;
constructor(fs: JSRuntimeFS) {
this.fs = fs;
this.git = new Git(fs, 'https://cors.isomorphic-git.org');
constructor(options: ProjectsManagerOptions) {
this.fs = options.fs;
this.git = options.git;
this.dir = '/projects';
}
@@ -40,57 +46,484 @@ export class ProjectsManager {
async createProject(name: string, customId?: string): Promise<Project> {
const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId, { depth: 1 });
try {
await this.fs.mkdir(this.dir + `/${project.id}/.ai/history`, { recursive: true });
} catch {
// Directory might already exist
}
// Delete README.md if it exists
// Delete README.md if it exists (template-specific cleanup)
try {
await this.fs.unlink(`${project.path}/README.md`);
} catch {
// README.md might not exist, ignore error
}
// Delete .git directory and reinitialize
try {
await this.deleteDirectory(`${project.path}/.git`);
} catch {
// .git directory might not exist, ignore error
}
// Initialize new git repository
await this.git.init({
dir: project.path,
defaultBranch: 'main',
});
// Add all files to git
const files = await this.getAllFiles(project.path);
for (const file of files) {
// Skip .git directory and other hidden files we don't want to track
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
await this.git.add({
dir: project.path,
filepath: file,
});
}
}
// Make initial commit
await this.git.commit({
dir: project.path,
message: 'New project created with Shakespeare',
author: {
name: 'shakespeare.diy',
email: '[email protected]',
},
// Setup project infrastructure using unified method
await this.setupProjectInfrastructure(project.path, {
isOverwrite: false,
commitMessage: 'New project created with Shakespeare',
skipPersistentStorage: false,
});
return project;
}
/**
* Unified method for setting up project infrastructure.
* Handles git initialization/management, .ai directory creation, and persistent storage.
*/
private async setupProjectInfrastructure(
projectPath: string,
options: {
isOverwrite?: boolean;
commitMessage?: string;
skipPersistentStorage?: boolean;
} = {}
): Promise<void> {
const { isOverwrite = false, commitMessage = 'Project setup', skipPersistentStorage = false } = options;
// Initialize git repository if there's no .git directory
try {
await this.fs.stat(`${projectPath}/.git`);
// If git exists and we're overwriting, stage the new files
if (isOverwrite) {
const projectFiles = await this.getAllFiles(projectPath);
for (const file of projectFiles) {
// Skip .git directory and .ai directory
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
try {
await this.git.add({
dir: projectPath,
filepath: file,
});
} catch {
// Ignore git add errors for files that might be gitignored
}
}
}
// Make commit for the overwrite
await this.git.commit({
dir: projectPath,
message: commitMessage,
author: {
name: 'shakespeare.diy',
email: '[email protected]',
},
});
}
} catch {
// No .git directory found, initialize new repository
await this.git.init({
dir: projectPath,
defaultBranch: 'main',
});
// Add all files to git (excluding .ai directory)
const projectFiles = await this.getAllFiles(projectPath);
for (const file of projectFiles) {
// Skip .git directory and .ai directory
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
await this.git.add({
dir: projectPath,
filepath: file,
});
}
}
// Make initial commit
await this.git.commit({
dir: projectPath,
message: commitMessage,
author: {
name: 'shakespeare.diy',
email: '[email protected]',
},
});
}
// Create .ai/history directory
try {
await this.fs.mkdir(`${projectPath}/.ai/history`, { recursive: true });
} catch {
// Directory might already exist
}
// Automatically request persistent storage (unless skipped)
if (!skipPersistentStorage) {
try {
await ensurePersistentStorage();
} catch (error) {
// Don't fail project setup if persistent storage request fails
console.warn('Failed to request persistent storage after project setup:', error);
}
}
}
/**
* Unified project import method that handles both ZIP files and direct file objects
*/
async importProject(
source: File | { files: { [path: string]: Uint8Array } },
options: {
projectId?: string;
overwrite?: boolean;
projectName?: string;
} = {}
): Promise<Project> {
const { projectId, overwrite = false, projectName } = options;
let finalProjectId: string;
let finalProjectName: string;
let files: { [path: string]: Uint8Array };
if (source instanceof File) {
// Handle ZIP file import
finalProjectId = projectId || await this.generateUniqueProjectId(source.name.replace(/\.zip$/i, ''));
finalProjectName = projectName || this.formatProjectName(finalProjectId);
// Extract files from ZIP
const arrayBuffer = await source.arrayBuffer();
const zip = await JSZip.loadAsync(arrayBuffer);
files = {};
const skippedFiles: string[] = [];
for (const [relativePath, zipEntry] of Object.entries(zip.files)) {
if (zipEntry.dir) continue;
// Validate extraction path is within project directory
const projectPath = `${this.dir}/${finalProjectId}`;
const extractPath = this.join(projectPath, relativePath);
if (!this.isPathWithinProject(extractPath, projectPath)) {
skippedFiles.push(relativePath);
continue;
}
const content = await zipEntry.async('uint8array');
files[relativePath] = content;
}
if (skippedFiles.length > 0) {
console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside of project directory:`, skippedFiles);
}
} else {
// Handle direct files import
finalProjectId = projectId || await this.generateUniqueProjectId('imported-project');
finalProjectName = projectName || this.formatProjectName(finalProjectId);
files = source.files;
}
const projectPath = `${this.dir}/${finalProjectId}`;
const projectExists = await this.projectExists(finalProjectId);
// Check if project with this ID already exists when not overwriting
if (projectExists && !overwrite) {
throw new Error(`Project with ID "${finalProjectId}" already exists`);
}
try {
// Create project directory (or ensure it exists for overwrite)
await this.fs.mkdir(projectPath, { recursive: true });
// If overwriting, delete existing files except .ai directory and .git directory
if (projectExists && overwrite) {
const existingFiles = await this.getAllFiles(projectPath);
for (const file of existingFiles) {
// Preserve .ai directory and .git directory
if (!file.startsWith('.ai/') && !file.startsWith('.git/')) {
try {
await this.fs.unlink(`${projectPath}/${file}`);
} catch {
// Ignore deletion errors
}
}
}
}
// Extract all files with security validation
const extractedFiles: string[] = [];
const skippedFiles: string[] = [];
for (const [relativePath, content] of Object.entries(files)) {
// Validate extraction path is within project directory
const extractPath = this.join(projectPath, relativePath);
if (!this.isPathWithinProject(extractPath, projectPath)) {
skippedFiles.push(relativePath);
continue;
}
// Ensure parent directory exists
const dirPath = extractPath.split('/').slice(0, -1).join('/');
if (dirPath) {
await this.fs.mkdir(dirPath, { recursive: true });
}
// Write the file (this will overwrite existing files)
await this.fs.writeFile(extractPath, content);
extractedFiles.push(relativePath);
}
if (skippedFiles.length > 0) {
console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside of project directory:`, skippedFiles);
}
// Get filesystem stats for timestamps
const stats = await this.fs.stat(projectPath);
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
// Setup project infrastructure using unified method
await this.setupProjectInfrastructure(projectPath, {
isOverwrite: overwrite,
commitMessage: source instanceof File
? `Import project from ${source.name}`
: `Import project from files`,
skipPersistentStorage: false,
});
return {
id: finalProjectId,
name: finalProjectName,
path: projectPath,
lastModified: timestamp,
};
} catch (error) {
// Clean up on error (only if this was a new project creation)
if (!projectExists) {
try {
await this.deleteDirectory(projectPath);
} catch {
// Ignore cleanup errors
}
}
throw error;
}
}
// Legacy method for backward compatibility
async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise<Project> {
// Generate a project ID based on the zip file name or use custom ID
const baseName = zipFile.name.replace(/\.zip$/i, '');
const generatedId = baseName
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
// Determine the project ID to use
let id: string;
if (customId) {
// Use the provided custom ID (for overwrite scenarios)
id = customId;
} else {
// If no custom ID, generate a unique ID (for new projects)
id = await this.generateUniqueProjectId(generatedId);
}
const projectPath = `${this.dir}/${id}`;
const projectExists = await this.projectExists(id);
// Check if project with this ID already exists when not overwriting
if (projectExists && !overwrite) {
throw new Error(`Project with ID "${id}" already exists`);
}
// Get original project name if overwriting, otherwise use formatted name
let projectName: string;
if (overwrite && projectExists) {
const existingProject = await this.getProject(id);
projectName = existingProject?.name || this.formatProjectName(id);
} else {
projectName = this.formatProjectName(id);
}
try {
// Create project directory (or ensure it exists for overwrite)
await this.fs.mkdir(projectPath, { recursive: true });
// If overwriting, delete existing files except .git directory
if (projectExists && overwrite) {
const existingFiles = await this.getAllFiles(projectPath);
for (const file of existingFiles) {
// Preserve .git directory
if (!file.startsWith('.git/')) {
try {
await this.fs.unlink(`${projectPath}/${file}`);
} catch {
// Ignore deletion errors
}
}
}
}
// Read the zip file
const arrayBuffer = await zipFile.arrayBuffer();
const zip = await JSZip.loadAsync(arrayBuffer);
// Extract all files from the zip with security validation
const extractedFiles: string[] = [];
const skippedFiles: string[] = [];
for (const [relativePath, zipEntry] of Object.entries(zip.files)) {
// Validate the extraction path is within the project directory
const extractPath = this.join(projectPath, relativePath);
if (!this.isPathWithinProject(extractPath, projectPath)) {
skippedFiles.push(relativePath);
continue;
}
if (zipEntry.dir) {
// Create the directory structure
await this.fs.mkdir(extractPath, { recursive: true });
continue;
}
// Extract file content
const content = await zipEntry.async('uint8array');
// Ensure parent directory exists
const dirPath = extractPath.split('/').slice(0, -1).join('/');
if (dirPath) {
await this.fs.mkdir(dirPath, { recursive: true });
}
// Write the file (this will overwrite existing files)
await this.fs.writeFile(extractPath, content);
extractedFiles.push(relativePath);
}
if (skippedFiles.length > 0) {
console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside the project direcotry:`, skippedFiles);
}
// Get filesystem stats for timestamps
const stats = await this.fs.stat(projectPath);
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
// Setup project infrastructure using unified method
await this.setupProjectInfrastructure(projectPath, {
isOverwrite: overwrite,
commitMessage: `Import project from ${zipFile.name}`,
skipPersistentStorage: false,
});
return {
id,
name: projectName,
path: projectPath,
lastModified: timestamp,
};
} catch (error) {
// Clean up on error (only if this was a new project creation)
if (!projectExists) {
try {
await this.deleteDirectory(projectPath);
} catch {
// Ignore cleanup errors
}
}
throw error;
}
}
/**
* Import project directly from files object (bypasses ZIP creation)
* Used by bulk import to avoid unnecessary ZIP repackaging
*/
async importProjectFromFiles(
projectId: string,
files: { [path: string]: Uint8Array },
overwrite = false,
projectName?: string
): Promise<Project> {
const projectPath = `${this.dir}/${projectId}`;
const projectExists = await this.projectExists(projectId);
// Check if project with this ID already exists when not overwriting
if (projectExists && !overwrite) {
throw new Error(`Project with ID "${projectId}" already exists`);
}
// Determine project name
const finalProjectName = projectName || this.formatProjectName(projectId);
try {
// Create project directory (or ensure it exists for overwrite)
await this.fs.mkdir(projectPath, { recursive: true });
// If overwriting, delete existing files except .ai directory and .git directory
if (projectExists && overwrite) {
const existingFiles = await this.getAllFiles(projectPath);
for (const file of existingFiles) {
// Preserve .ai directory and .git directory
if (!file.startsWith('.ai/') && !file.startsWith('.git/')) {
try {
await this.fs.unlink(`${projectPath}/${file}`);
} catch {
// Ignore deletion errors
}
}
}
}
// Extract all files with security validation
const extractedFiles: string[] = [];
const skippedFiles: string[] = [];
for (const [relativePath, content] of Object.entries(files)) {
// Validate the extraction path is within the project directory
const extractPath = this.join(projectPath, relativePath);
if (!this.isPathWithinProject(extractPath, projectPath)) {
skippedFiles.push(relativePath);
continue;
}
// Ensure parent directory exists
const dirPath = extractPath.split('/').slice(0, -1).join('/');
if (dirPath) {
await this.fs.mkdir(dirPath, { recursive: true });
}
// Write the file (this will overwrite existing files)
await this.fs.writeFile(extractPath, content);
extractedFiles.push(relativePath);
}
if (skippedFiles.length > 0) {
console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside the project directory:`, skippedFiles);
}
// Get filesystem stats for timestamps
const stats = await this.fs.stat(projectPath);
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
// Setup project infrastructure using unified method
await this.setupProjectInfrastructure(projectPath, {
isOverwrite: overwrite,
commitMessage: `Import project from files`,
skipPersistentStorage: false,
});
return {
id: projectId,
name: finalProjectName,
path: projectPath,
lastModified: timestamp,
};
} catch (error) {
// Clean up on error (only if this was a new project creation)
if (!projectExists) {
try {
await this.deleteDirectory(projectPath);
} catch {
// Ignore cleanup errors
}
}
throw error;
}
}
async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise<Project> {
const id = customId || await this.generateUniqueProjectId(name);
@@ -103,7 +536,7 @@ export class ProjectsManager {
await this.fs.mkdir(projectPath);
// Clone the repository
// Clone the repository (Git class now handles Nostr URIs automatically)
await this.git.clone({
dir: projectPath,
url: repoUrl,
@@ -115,6 +548,14 @@ export class ProjectsManager {
const stats = await this.fs.stat(projectPath);
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
// Automatically request persistent storage after project cloning
try {
await ensurePersistentStorage();
} catch (error) {
// Don't fail project cloning if persistent storage request fails
console.warn('Failed to request persistent storage after project cloning:', error);
}
// Return the full project object with dynamically generated properties
return {
id,
@@ -260,6 +701,50 @@ export class ProjectsManager {
await this.deleteDirectory(projectPath);
}
async renameProject(oldId: string, newId: string): Promise<Project> {
// Validate that the old project exists
const oldProject = await this.getProject(oldId);
if (!oldProject) {
throw new Error(`Project with ID "${oldId}" does not exist`);
}
// Validate that the new ID doesn't already exist
if (await this.projectExists(newId)) {
throw new Error(`Project with ID "${newId}" already exists`);
}
// Validate the new ID format (same rules as generateUniqueProjectId)
const validatedNewId = newId
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
if (validatedNewId !== newId) {
throw new Error(`Project name must contain only lowercase letters, numbers, and hyphens`);
}
if (!validatedNewId) {
throw new Error(`Project name cannot be empty`);
}
const oldPath = `${this.dir}/${oldId}`;
const newPath = `${this.dir}/${newId}`;
// Rename the directory
await this.fs.rename(oldPath, newPath);
// Return the updated project object
const stats = await this.fs.stat(newPath);
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
return {
id: newId,
name: this.formatProjectName(newId),
path: newPath,
lastModified: timestamp,
};
}
private async deleteDirectory(dirPath: string): Promise<void> {
const files = await this.fs.readdir(dirPath);
@@ -354,4 +839,107 @@ export class ProjectsManager {
return files;
}
/**
* Safe path join that normalizes the result to prevent directory traversal
*/
private join(...paths: string[]): string {
// Simple path joining with normalization
const joined = paths.join('/').replace(/\/+/g, '/');
// Normalize path separators and resolve .. and . components
const parts = joined.split('/').filter(part => part !== '');
const normalized: string[] = [];
for (const part of parts) {
if (part === '..') {
normalized.pop();
} else if (part !== '.') {
normalized.push(part);
}
}
return '/' + normalized.join('/');
}
/**
* Check if a path is within the project directory
*/
private isPathWithinProject(extractPath: string, projectPath: string): boolean {
// Normalize both paths
const normalizedExtractPath = this.normalize(extractPath);
const normalizedProjectPath = this.normalize(projectPath);
// Check if the extract path starts with the project path
return normalizedExtractPath.startsWith(normalizedProjectPath + '/') ||
normalizedExtractPath === normalizedProjectPath;
}
/**
* Normalize a path by resolving . and .. components
*/
private normalize(path: string): string {
const parts = path.split('/').filter(part => part !== '');
const normalized: string[] = [];
for (const part of parts) {
if (part === '..') {
normalized.pop();
} else if (part !== '.') {
normalized.push(part);
}
}
return '/' + normalized.join('/');
}
/**
* Extract files from a ZIP archive for a specific project path
* Used by bulk import to extract files from a specific directory within a ZIP
*/
async extractFilesFromZip(zip: JSZip, projectPath: string): Promise<{ [path: string]: Uint8Array }> {
const files: { [path: string]: Uint8Array } = {};
const skippedFiles: string[] = [];
const securitySkippedFiles: string[] = [];
for (const [relativePath, zipEntry] of Object.entries(zip.files)) {
if (zipEntry.dir) continue;
// Check if this file is within the specified project path
if (!relativePath.startsWith(projectPath + '/')) {
continue;
}
// Get the relative path within the project
const fileRelativePath = relativePath.substring(projectPath.length + 1);
// Skip empty paths (shouldn't happen due to the dir check above, but just in case)
if (!fileRelativePath) continue;
// Validate extraction path is safe (zip slip protection)
// Check for directory traversal attempts in the original path
if (fileRelativePath.includes('../') || fileRelativePath.includes('..\\') || fileRelativePath.startsWith('/') || fileRelativePath.startsWith('\\')) {
securitySkippedFiles.push(relativePath);
continue;
}
try {
const content = await zipEntry.async('uint8array');
files[fileRelativePath] = content;
} catch (error) {
console.warn(`Failed to extract file ${relativePath}:`, error);
skippedFiles.push(relativePath);
}
}
if (securitySkippedFiles.length > 0) {
console.warn(`Skipped ${securitySkippedFiles.length} files due to resolving to paths outside of project directory:`, securitySkippedFiles);
}
if (skippedFiles.length > 0) {
console.warn(`Skipped ${skippedFiles.length} files due to extraction errors:`, skippedFiles);
}
return files;
}
}
+26 -3
View File
@@ -25,12 +25,13 @@ const mockFS: JSRuntimeFS = {
describe('SessionManager', () => {
let sessionManager: SessionManager;
const mockAISettings = {
providers: {
'test-provider': {
providers: [
{
id: 'test-provider',
baseURL: 'https://api.test.com',
apiKey: 'test-key'
}
}
]
};
beforeEach(() => {
@@ -94,4 +95,26 @@ describe('SessionManager', () => {
expect(messageWithReasoning.reasoning_content).toBe('Let me think about this step by step...');
}
});
it('should throw service errors instead of adding them to message history', async () => {
const projectId = 'test-project';
const tools = {};
const customTools = {};
// Load a session
await sessionManager.loadSession(projectId, tools, customTools);
// Add a user message to enable generation
await sessionManager.addMessage(projectId, { role: 'user', content: 'test message' });
// Attempt to start generation with invalid provider - should throw error instead of adding to messages
await expect(
sessionManager.startGeneration(projectId, 'invalid-provider/invalid-model')
).rejects.toThrow('Provider "invalid-provider" not found');
// Verify that no error message was added to the conversation
const updatedSession = sessionManager.getSession(projectId);
expect(updatedSession?.messages).toHaveLength(1); // Only the user message
expect(updatedSession?.messages[0].role).toBe('user');
});
});
+71 -45
View File
@@ -5,6 +5,9 @@ import { parseProviderModel } from './parseProviderModel';
import { createAIClient } from './ai-client';
import type { Tool } from './tools/Tool';
import type { NUser } from '@nostrify/react/login';
import type { AIProvider } from '@/contexts/AISettingsContext';
import { makeSystemPrompt } from './system';
import { NostrMetadata } from '@nostrify/nostrify';
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
role: 'assistant';
@@ -17,7 +20,6 @@ export interface SessionState {
projectId: string;
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
customTools: Record<string, Tool<unknown>>;
systemPrompt?: string;
maxSteps?: number;
messages: AIMessage[];
streamingMessage?: {
@@ -52,15 +54,15 @@ export class SessionManager {
private sessions = new Map<string, SessionState>();
private listeners: Partial<Record<keyof SessionManagerEvents, Set<(...args: unknown[]) => void>>> = {};
private fs: JSRuntimeFS;
private aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string; nostr?: boolean }> };
private aiSettings: { providers: AIProvider[] };
private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>;
private getCurrentUser?: () => NUser | undefined;
private getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata };
constructor(
fs: JSRuntimeFS,
aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string; nostr?: boolean }> },
aiSettings: { providers: AIProvider[] },
getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>,
getCurrentUser?: () => NUser | undefined
getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata },
) {
this.fs = fs;
this.aiSettings = aiSettings;
@@ -75,7 +77,6 @@ export class SessionManager {
projectId: string,
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>,
customTools: Record<string, Tool<unknown>>,
systemPrompt?: string,
maxSteps?: number
): Promise<SessionState> {
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
@@ -97,7 +98,6 @@ export class SessionManager {
projectId,
tools,
customTools,
systemPrompt,
maxSteps,
isLoading: false,
lastActivity: new Date(),
@@ -113,7 +113,6 @@ export class SessionManager {
session.tools = tools;
session.customTools = customTools;
session.systemPrompt = systemPrompt;
session.maxSteps = maxSteps;
this.sessions.set(projectId, session);
@@ -179,6 +178,7 @@ export class SessionManager {
* Start AI generation for a session
*/
async startGeneration(projectId: string, providerModel: string): Promise<void> {
console.log('Starting AI generation for project:', projectId, 'with model:', providerModel);
let session = this.sessions.get(projectId);
if (!session) {
@@ -202,12 +202,12 @@ export class SessionManager {
try {
// Parse provider and model
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
const connectionConfig = parsed.connection;
const modelName = parsed.model;
const provider = parsed.provider;
const model = parsed.model;
// Initialize OpenAI client
const currentUser = this.getCurrentUser?.();
const openai = createAIClient(connectionConfig, currentUser);
const { user, metadata } = this.getCurrentUser?.() ?? {};
const openai = createAIClient(provider, user);
let stepCount = 0;
const maxSteps = session.maxSteps || 50;
@@ -229,17 +229,27 @@ export class SessionManager {
tool_calls: undefined
};
const systemPrompt = await makeSystemPrompt({
cwd: `/projects/${projectId}`,
fs: this.fs,
mode: "agent",
name: "Shakespeare",
profession: "software extraordinaire",
tools: Object.values(session.tools),
user,
metadata,
});
// Prepare messages for AI
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = session.systemPrompt
? [{ role: 'system', content: session.systemPrompt }, ...session.messages]
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = systemPrompt
? [{ role: 'system', content: systemPrompt }, ...session.messages]
: session.messages;
// Prepare completion options
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
model: modelName,
model,
messages,
tools: session.tools && Object.keys(session.tools).length > 0 ? Object.values(session.tools) : undefined,
tool_choice: session.tools && Object.keys(session.tools).length > 0 ? 'auto' : undefined,
stream: true,
stream_options: {
include_usage: true,
@@ -257,12 +267,12 @@ export class SessionManager {
let finishReason: string | null = null;
// Process the stream
let usage: { prompt_tokens: number; completion_tokens: number } | undefined;
let usage: { prompt_tokens: number; completion_tokens: number; cost?: number } | undefined;
for await (const chunk of stream) {
// Check if session was cancelled
if (!session.isLoading) break;
const delta = chunk.choices[0]?.delta;
const delta = chunk.choices[0]?.delta as OpenAI.Chat.Completions.ChatCompletionChunk.Choice.Delta | undefined;
if (delta?.content) {
accumulatedContent += delta.content;
@@ -273,19 +283,26 @@ export class SessionManager {
}
// Handle reasoning content if present (some providers may include this)
const deltaWithReasoning = delta as { reasoning_content?: string };
if (deltaWithReasoning?.reasoning_content) {
accumulatedReasoningContent += deltaWithReasoning.reasoning_content;
let reasoningContent: string | undefined;
// LiteLLM, Z.ai, etc. use 'reasoning_content'
if (delta && 'reasoning_content' in delta && typeof delta.reasoning_content === 'string') {
reasoningContent = delta.reasoning_content;
// ollama uses 'reasoning'
} else if (delta && 'reasoning' in delta && typeof delta.reasoning === 'string') {
reasoningContent = delta.reasoning;
}
if (reasoningContent) {
accumulatedReasoningContent += reasoningContent;
if (session.streamingMessage) {
session.streamingMessage.reasoning_content += deltaWithReasoning.reasoning_content;
session.streamingMessage.reasoning_content += reasoningContent;
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.reasoning_content, session.streamingMessage.tool_calls);
}
}
if (delta?.tool_calls) {
for (const toolCallDelta of delta.tool_calls) {
const index = toolCallDelta.index;
if (index === undefined) continue;
for (let i = 0; i < delta.tool_calls.length; i++) {
const toolCallDelta = delta.tool_calls[i];
const index = toolCallDelta.index ?? i; // Fix for Gemini models
accumulatedToolCalls[index] ??= {
id: '',
@@ -311,13 +328,25 @@ export class SessionManager {
// Capture usage data if available (some providers include it in the final chunk)
if (chunk.usage) {
const cost = 'cost' in chunk.usage && typeof chunk.usage.cost === 'number'
? chunk.usage.cost
: undefined;
usage = {
prompt_tokens: chunk.usage.prompt_tokens || 0,
completion_tokens: chunk.usage.completion_tokens || 0
completion_tokens: chunk.usage.completion_tokens || 0,
cost,
};
}
}
// Fix tool calls with empty arguments
for (const toolCall of accumulatedToolCalls) {
if (toolCall.type === 'function') {
toolCall.function.arguments = toolCall.function.arguments || '{}';
}
}
// Create final assistant message
const assistantMessage: AIMessage = {
role: 'assistant',
@@ -374,23 +403,13 @@ export class SessionManager {
} catch (error) {
console.error('AI generation error:', error);
// Handle different error types
if (error?.name === 'AbortError') return; // User cancelled
let errorMessage = 'Sorry, I encountered an unexpected error. Please try again.';
const errorMsg = error?.message || '';
if (error?.name === 'TypeError' && errorMsg.includes('fetch')) {
errorMessage = 'Network error: Unable to connect to AI service. Please check your internet connection and AI settings.';
} else if (errorMsg.includes('API key')) {
errorMessage = 'Authentication error: Please check your API key in AI settings.';
} else if (errorMsg.includes('rate limit')) {
errorMessage = 'Rate limit exceeded. Please wait a moment before trying again.';
} else if (errorMsg) {
errorMessage = `AI service error: ${errorMsg}`;
// Handle user cancellation
if (error instanceof OpenAI.APIUserAbortError || error?.name === 'AbortError') {
return; // User cancelled
}
await this.addMessage(projectId, { role: 'assistant', content: errorMessage });
// Re-throw service errors to be handled at the UI level
throw error;
} finally {
if (session) {
session.isLoading = false;
@@ -453,20 +472,28 @@ export class SessionManager {
/**
* Update session cost and context usage based on usage data
*/
private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number }, providerModel: string): void {
private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number; cost?: number }, providerModel: string): void {
if (!this.getProviderModels) return;
const session = this.sessions.get(projectId);
if (!session) return;
// If provider gives direct cost, use it
if (typeof usage.cost === 'number') {
session.totalCost = (session.totalCost || 0) + usage.cost;
this.emit('costUpdated', projectId, session.totalCost);
return;
}
// Otherwise, get the cost from the models endpoint
try {
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
const modelName = parsed.model;
const providerName = parsed.provider;
const provider = parsed.provider;
// Find the model in provider models to get pricing and context length
const models = this.getProviderModels();
const model = models.find(m => m.id === modelName && m.provider === providerName);
const model = models.find(m => m.id === modelName && m.provider === provider.id);
// Update input tokens for context usage tracking
session.lastInputTokens = usage.prompt_tokens;
@@ -483,7 +510,6 @@ export class SessionManager {
// Update session total cost
session.totalCost = (session.totalCost || 0) + requestCost;
this.emit('costUpdated', projectId, session.totalCost);
} catch (error) {
console.warn('Failed to calculate session cost:', error);
+30 -8
View File
@@ -1,30 +1,52 @@
import OpenAI from 'openai';
import { NIP98Client } from '@nostrify/nostrify';
import type { AIConnection } from '@/contexts/AISettingsContext';
import type { NUser } from '@nostrify/react/login';
import type { AIProvider } from '@/contexts/AISettingsContext';
/**
* Create an OpenAI client instance with the appropriate configuration.
* If the connection requires Nostr authentication (NIP-98), it will use
* the NIP98Client for authenticated requests.
*/
export function createAIClient(connection: AIConnection, user?: NUser): OpenAI {
export function createAIClient(provider: AIProvider, user?: NUser): OpenAI {
const baseConfig: ConstructorParameters<typeof OpenAI>[0] = {
baseURL: connection.baseURL,
apiKey: connection.apiKey ?? '',
baseURL: provider.baseURL,
apiKey: provider.apiKey ?? '',
dangerouslyAllowBrowser: true,
defaultHeaders: provider.id === 'openrouter' ? {
// https://openrouter.ai/docs/app-attribution
'HTTP-Referer': 'https://shakespeare.diy',
'X-Title': 'Shakespeare',
} : {},
};
let openai: OpenAI;
// If Nostr authentication is required and we have a user, use NIP-98
if (connection.nostr && user?.signer) {
if (provider.nostr && user?.signer) {
const nip98Client = new NIP98Client({ signer: user.signer });
return new OpenAI({
openai = new OpenAI({
...baseConfig,
fetch: (input, init) => nip98Client.fetch(input, init),
});
} else {
// Standard OpenAI client
openai = new OpenAI(baseConfig);
}
// Standard OpenAI client
return new OpenAI(baseConfig);
const createCompletion: typeof openai.chat.completions.create
= openai.chat.completions.create.bind(openai.chat.completions);
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
// OpenRouter usage accounting
// https://openrouter.ai/docs/use-cases/usage-accounting
if (provider.id === 'openrouter') {
(body as { usage?: { include?: boolean } }).usage = { include: true };
}
return createCompletion(body, options);
}) as typeof createCompletion;
return openai;
}
-21
View File
@@ -1,21 +0,0 @@
import OpenAI from "openai";
export function assistantContentEmpty(
content: OpenAI.ChatCompletionAssistantMessageParam['content'],
): boolean {
if (!content) return true;
const text: string[] = [];
if (typeof content === 'string') {
text.push(content);
} else if (Array.isArray(content)) {
for (const part of content) {
if (part.type === 'text') {
text.push(part.text);
}
}
}
const result = text.join('\n\n');
return !result.trim();
}
+29 -6
View File
@@ -5,6 +5,7 @@ interface PackageLock {
[key: string]: {
name?: string;
version: string;
peerDependencies?: { [key: string]: string };
} | undefined;
};
}
@@ -61,6 +62,14 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
}
});
// Legacy (Internet Explorer) "behavior" syntax
build.onResolve({ filter: /^#default#/, namespace: "esm" }, (args) => {
return {
path: args.path,
external: true,
};
});
// Handle bare imports like "react"
build.onResolve({ filter: /^[^./].*/ }, (args) => {
const packageName = args.path.startsWith("@")
@@ -69,8 +78,13 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
// Handle transitive dependency versions
const keys: string[] = [];
let importerPackage: string | undefined;
try {
const importerPackage = extractPackageName(args.importer);
const { pathname } = new URL(args.importer);
if (/\.css$/.test(pathname)) {
return; // CSS imports don't have external dependencies
}
importerPackage = extractPackageName(args.importer);
keys.push(
`node_modules/${importerPackage}/node_modules/${packageName}`,
);
@@ -89,12 +103,13 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
.find((info) => info);
const packagePath = args.path.slice(packageName.length);
const version = packageInfo?.version;
const version = packageInfo?.version
|| packageLock.packages[`node_modules/${importerPackage}`]?.peerDependencies?.[packageName];
if (!version) return;
const name = packageInfo.name ?? packageName;
const specifier = `${name}@${version}${packagePath}`;
const name = packageInfo?.name ?? packageName;
const specifier = version
? `${name}@${version}${packagePath}`
: `${name}${packagePath}`;
const url = new URL(`https://esm.sh/*${specifier}`);
@@ -131,6 +146,14 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
}
}
// Skip static assets
if (/\.(woff2?|ttf|otf|eot)$/.test(fullURL.pathname)) {
return {
path: fullURL.toString(),
external: true,
};
}
return {
path: fullURL.toString(),
namespace: "esm",
+31 -10
View File
@@ -1,4 +1,4 @@
import path from "path-browserify";
import { join, dirname, extname } from "path-browserify";
import type { Loader, Plugin } from "esbuild-wasm";
import type { JSRuntimeFS } from '@/lib/JSRuntime';
@@ -8,27 +8,37 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin {
name: "fs",
setup(build) {
build.onResolve({ filter: /^data:/ }, (args) => {
return {
path: args.path,
external: true,
};
});
build.onResolve({ filter: /.*/ }, async (args) => {
let resolved: string;
if (args.path.startsWith("@/")) {
resolved = path.join(cwd, args.path.slice(2));
resolved = join(cwd, args.path.slice(2));
} else if (args.kind === "entry-point") {
resolved = path.join(cwd, args.path);
resolved = join(cwd, args.path);
} else if (args.importer) {
resolved = path.join(path.dirname(args.importer), args.path);
resolved = join(dirname(args.importer), args.path);
} else {
return;
}
// Vite query parameters https://vite.dev/guide/assets
const [cleaned, query] = resolved.split("?");
try {
resolved = await tryFileVariants(fs, resolved);
resolved = await tryFileVariants(fs, cleaned);
} catch {
return; // Let other plugins handle this
}
return {
path: resolved,
path: resolved + (typeof query === "string" ? "?" + query : ""),
namespace: "fs",
};
});
@@ -36,14 +46,25 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin {
build.onLoad(
{ filter: /.*/, namespace: "fs" },
async (args) => {
const ext = path.extname(args.path).slice(1);
const [path, query] = args.path.split("?");
const params = new URLSearchParams(query);
if (!["ts", "tsx", "js", "jsx", "css"].includes(ext)) {
// https://vite.dev/guide/assets.html#importing-asset-as-string
if (params.has("raw")) {
return {
contents: await fs.readFile(path, "utf8"),
loader: "text",
};
}
const ext = extname(path).slice(1);
if (!["ts", "tsx", "js", "jsx", "css", "json"].includes(ext)) {
return;
}
return {
contents: await fs.readFile(args.path, "utf8"),
contents: await fs.readFile(path, "utf8"),
loader: ext as Loader,
};
},
@@ -67,7 +88,7 @@ async function tryFileVariants(
// If it's a directory, try index files
if (stat.isDirectory()) {
for (const ext of extensions) {
const indexFile = path.join(basePath, "index" + ext);
const indexFile = join(basePath, "index" + ext);
const indexStat = await statSafe(fs, indexFile);
if (indexStat.isFile()) {
return indexFile;
+11 -6
View File
@@ -1,6 +1,7 @@
import { getEsbuild } from "@/lib/esbuild";
import { copyFiles } from "@/lib/copyFiles";
import { shakespearePlugin } from "./shakespearePlugin";
import { esmPlugin } from "./esmPlugin";
import { fsPlugin } from "./fsPlugin";
@@ -49,6 +50,7 @@ async function bundle(
outdir: "/",
jsx: "automatic",
plugins: [
shakespearePlugin(), // Takes precedence over esmPlugin
fsPlugin(fs, `${projectPath}/src`),
esmPlugin(JSON.parse(packageLockText), target),
],
@@ -71,7 +73,7 @@ async function bundle(
}
// Update index.html with proper script and link tags
updateIndexHtml(doc);
updateIndexHtml(doc, dist);
const updatedHtml = "<!DOCTYPE html>\n" + doc.documentElement.outerHTML;
dist["index.html"] = new TextEncoder().encode(updatedHtml);
@@ -154,7 +156,7 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
};
}
function updateIndexHtml(doc: Document): void {
function updateIndexHtml(doc: Document, dist: Record<string, Uint8Array>): void {
const entrypoint = doc.querySelector('script[src="/src/main.tsx"]');
if (!entrypoint) {
@@ -163,8 +165,11 @@ function updateIndexHtml(doc: Document): void {
entrypoint.setAttribute("src", "/main.js");
const style = doc.createElement("link");
style.setAttribute("rel", "stylesheet");
style.setAttribute("href", "/main.css");
doc.head.appendChild(style);
const css = dist["main.css"];
if (css) {
const style = doc.createElement("style");
style.setAttribute("type", "text/tailwindcss");
style.textContent = new TextDecoder().decode(css);
doc.head.appendChild(style);
}
}
+168
View File
@@ -0,0 +1,168 @@
import type { Plugin } from "esbuild-wasm";
/**
* Shakespeare plugin for dependency polyfills and workarounds.
* This plugin handles specific dependencies that need custom implementations
* or dummy APIs to work correctly in the browser environment.
*/
export function shakespearePlugin(): Plugin {
return {
name: "shakespeare",
setup(build) {
// Handle "sonner" imports with a dummy API
build.onResolve({ filter: /^sonner$/ }, (args) => {
return {
path: args.path,
namespace: "shakespeare-sonner",
};
});
// Provide dummy sonner implementation
build.onLoad({ filter: /.*/, namespace: "shakespeare-sonner" }, () => {
return {
contents: `
// Dummy implementation of sonner toast library
// Toast function that does nothing
const toast = (message, options) => {
console.log('[Shakespeare Sonner Mock]:', message, options);
return { id: Math.random().toString(36) };
};
// Add common toast methods
toast.success = (message, options) => {
console.log('[Shakespeare Sonner Mock] Success:', message, options);
return { id: Math.random().toString(36) };
};
toast.error = (message, options) => {
console.log('[Shakespeare Sonner Mock] Error:', message, options);
return { id: Math.random().toString(36) };
};
toast.info = (message, options) => {
console.log('[Shakespeare Sonner Mock] Info:', message, options);
return { id: Math.random().toString(36) };
};
toast.warning = (message, options) => {
console.log('[Shakespeare Sonner Mock] Warning:', message, options);
return { id: Math.random().toString(36) };
};
toast.loading = (message, options) => {
console.log('[Shakespeare Sonner Mock] Loading:', message, options);
return { id: Math.random().toString(36) };
};
toast.promise = (promise, options) => {
console.log('[Shakespeare Sonner Mock] Promise:', promise, options);
return promise;
};
toast.dismiss = (id) => {
console.log('[Shakespeare Sonner Mock] Dismiss:', id);
};
// Toaster component (dummy React component)
const Toaster = (props) => {
console.log('[Shakespeare Sonner Mock] Toaster component rendered:', props);
return null;
};
// Export both named and default exports to match sonner API
export { toast, Toaster };
export default toast;
`,
loader: "js",
};
});
// Handle "next-themes" imports with a dummy API
build.onResolve({ filter: /^next-themes$/ }, (args) => {
return {
path: args.path,
namespace: "shakespeare-next-themes",
};
});
// Provide dummy next-themes implementation
build.onLoad({ filter: /.*/, namespace: "shakespeare-next-themes" }, () => {
return {
contents: `
// Dummy implementation of next-themes
// useTheme hook that returns system theme
const useTheme = () => {
return { theme: "system" };
};
// ThemeProvider component (dummy React component)
const ThemeProvider = ({ children, ...props }) => {
console.log('[Shakespeare next-themes Mock] ThemeProvider rendered:', props);
return children;
};
// Export both named and default exports to match next-themes API
export { useTheme, ThemeProvider };
`,
loader: "js",
};
});
// Handle "virtual:pwa-register/react" imports with a dummy API
build.onResolve({ filter: /^virtual:pwa-register\/react$/ }, (args) => {
return {
path: args.path,
namespace: "shakespeare-pwa-register",
};
});
// Provide dummy PWA register implementation
build.onLoad({ filter: /.*/, namespace: "shakespeare-pwa-register" }, () => {
return {
contents: `
// Dummy implementation of virtual:pwa-register/react
// useRegisterSW hook that returns dummy functions
const useRegisterSW = (options = {}) => {
console.log('[Shakespeare PWA Mock] useRegisterSW called:', options);
return {
needRefresh: [false, () => {}],
offlineReady: [false, () => {}],
updateServiceWorker: (reloadPage) => {
console.log('[Shakespeare PWA Mock] updateServiceWorker called:', reloadPage);
if (reloadPage) {
window.location.reload();
}
},
};
};
// Export the hook
export { useRegisterSW };
`,
loader: "js",
};
});
// Add more dependency polyfills here as needed
// Example structure for future dependencies:
// build.onResolve({ filter: /^some-other-package$/ }, (args) => {
// return {
// path: args.path,
// namespace: "shakespeare-other-package",
// };
// });
//
// build.onLoad({ filter: /.*/, namespace: "shakespeare-other-package" }, () => {
// return {
// contents: `// Custom implementation for some-other-package`,
// loader: "js",
// };
// });
},
};
}
+3 -2
View File
@@ -78,15 +78,16 @@ Change the current working directory.
**Examples:**
```bash
cd # Go to project root
cd # Stay in current directory
cd src/ # Change to src directory
cd .. # Go to parent directory
cd . # Stay in current directory
cd /projects/my-project # Change to absolute path
```
**Features:**
- Changes working directory for subsequent commands
- Supports relative paths (., .., subdirectories)
- Supports both relative and absolute paths
- Validates target exists and is a directory
- Updates shell working directory state
+1 -1
View File
@@ -1,4 +1,4 @@
import { join } from "@std/path";
import { join } from "path-browserify";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
+16 -2
View File
@@ -98,11 +98,25 @@ describe('CdCommand', () => {
expect(result.stderr).toContain('Not a directory');
});
it('should reject absolute paths', async () => {
it('should handle absolute paths to non-existent directories', async () => {
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory'));
const result = await cdCommand.execute(['/absolute/path'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('absolute paths are not supported');
expect(result.stderr).toContain('No such file or directory');
});
it('should handle absolute paths to existing directories', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
const result = await cdCommand.execute(['/projects/my-project'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.newCwd).toBe('/projects/my-project');
});
it('should reject too many arguments', async () => {
+9 -9
View File
@@ -1,7 +1,8 @@
import { join, resolve, dirname } from "@std/path";
import { join, resolve, dirname } from "path-browserify";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { isAbsolutePath } from "../security";
/**
* Implementation of the 'cd' command
@@ -31,20 +32,19 @@ export class CdCommand implements ShellCommand {
return createErrorResult(`${this.name}: too many arguments`);
}
// Handle absolute paths
if (targetPath.startsWith('/') || targetPath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(targetPath)) {
return createErrorResult(`${this.name}: absolute paths are not supported: ${targetPath}`);
}
// Resolve the new path
// Handle both absolute and relative paths
let newCwd: string;
if (targetPath === '.') {
if (isAbsolutePath(targetPath)) {
// Absolute path - use it directly
newCwd = targetPath;
} else if (targetPath === '.') {
// Current directory
newCwd = cwd;
} else if (targetPath === '..') {
// Parent directory
const parentPath = dirname(cwd);
// Don't allow going above the project root
// Don't allow going above the filesystem root
if (parentPath === cwd) {
return createErrorResult(`${this.name}: cannot access parent directory: Permission denied`);
}
+1 -1
View File
@@ -1,4 +1,4 @@
import { join, dirname, basename } from "@std/path";
import { join, dirname, basename } from "path-browserify";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff. Show more